// 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 BingxCore {
pub exchange: crate::exchange::Exchange,
}
impl BingxCore {
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 = BingxCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for BingxCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_funding_rate(self, rate, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_open_interest(self, interest, &[market])
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_liquidation(self, liquidation, &[market])
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_funding_rate_history(self, entry, &[market])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_margin_modification(self, data, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_transaction(self, transaction, &[currency])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_income(self, info, &[market])
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::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 BingxCore.
BingxCore::parse_leverage(self, leverage, &[market])
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_market_leverage_tiers(self, info, &[market])
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::parse_deposit_withdraw_fee(self, fee, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on BingxCore.
BingxCore::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 BingxCore.
BingxCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BingxCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_all_positions" => self.close_all_positions(&args[..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_market_order_with_cost" => self.create_market_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"create_market_sell_order_with_cost" => self.create_market_sell_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_addresses_by_network" => self.fetch_deposit_addresses_by_network(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_withdraw_fees" => self.fetch_deposit_withdraw_fees(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_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_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_inverse_swap_markets" => self.fetch_inverse_swap_markets(args.get(0).cloned().unwrap_or(crate::Value::Null)).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_mark_price" => self.fetch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_mark_prices" => self.fetch_mark_prices(&args[..]).await,
"fetch_market_leverage_tiers" => self.fetch_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_liquidations" => self.fetch_my_liquidations(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_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_spot_markets" => self.fetch_spot_markets(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_swap_markets" => self.fetch_swap_markets(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transfers" => self.fetch_transfers(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"nonce" => self.nonce(),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_deposit_withdraw_fee" => self.parse_deposit_withdraw_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_rate_history" => self.parse_funding_rate_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_liquidation" => self.parse_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_mode" => self.parse_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market_leverage_tiers" => self.parse_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_type" => self.parse_order_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_params" => self.parse_params(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin" => self.set_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_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,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for BingxCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for BingxCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl BingxCore {
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("bingx".into()));
m.insert("name".to_string(), Value::Str("BingX".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("certified".to_string(), Value::Bool(true));
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(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
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("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(true));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLossOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(true));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(true));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
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(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(true));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMarkPrice".to_string(), Value::Bool(true));
m.insert("fetchMarkPrices".to_string(), Value::Bool(true));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("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(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionHistory".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".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(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(true));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("hostname".to_string(), Value::Str("bingx.com".into()));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github-production-user-asset-6210df.s3.amazonaws.com/1294454/253675376-6983b72e-4999-4549-b177-33b374c195e3.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fund".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("spot".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("swap".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("contract".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("wallets".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("user".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("subAccount".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("account".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("copyTrading".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("cswap".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m.insert("api".to_string(), Value::Str("https://open-api.{hostname}/openApi".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fund".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("spot".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("swap".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("contract".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("wallets".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("user".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("subAccount".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("account".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("copyTrading".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("cswap".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m.insert("api".to_string(), Value::Str("https://open-api-vst.{hostname}/openApi".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://bingx.com/".into()));
m.insert("doc".to_string(), Value::Str("https://bingx-api.github.io/docs/".into()));
m.insert("referral".to_string(), Value::Str("https://bingx.com/invite/OHETOM".into()));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.001".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.001".into()), &[]));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("feeSide".to_string(), Value::Str("quote".into()));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0002".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0005".into()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fund".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".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("server/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("common/symbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ticker/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ticker/bookTicker".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("trade/query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/historyOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/myTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/commissionRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("oco/orderList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("oco/openOrderList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("oco/historyOrderList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/batchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/order/cancelReplace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/cancelOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/cancelOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/cancelAllAfter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("oco/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("oco/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m
}));
m.insert("v2".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("market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("ticker/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/bookTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/historicalKlines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/historicalTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get/asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/deposit/hisrec".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/withdraw/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post/asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".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("ticker/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/historicalTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/markPriceKlines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/multiAssetsRules".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingRules".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("positionSide/dual".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/batchCancelReplace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/fullOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("maintMarginRatio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/positionHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("positionMargin/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("twap/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("twap/historyOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("twap/orderDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/assetMode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/marginAssets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/amend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/cancelReplace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("positionSide/dual".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/batchCancelReplace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/closePosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/getVst".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("twap/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("twap/cancelOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/assetMode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/reverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/autoAddMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m
}));
m.insert("v2".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("server/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/contracts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/premiumIndex".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/fundingRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/openInterest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("quote/bookTicker".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("user/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/income".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/openOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/marginType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/forceOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/allOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/allFillOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/fillHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/positionHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/income/export".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/commissionRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("quote/bookTicker".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("trade/getVst".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/batchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/closeAllPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/cancelAllAfter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/marginType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/positionMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/order/test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/batchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/allOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m.insert("v3".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("quote/klines".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("user/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("cswap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".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("market/contracts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/premiumIndex".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/openInterest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/ticker".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("trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/forceOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/allFillOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/orderDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/orderHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/marginType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/commissionRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("user/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/allOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/closeAllPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/marginType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/positionMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/allOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/cancelOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m.insert("v2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("allPosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("allOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("wallets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("capital/config/getall".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/deposit/address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/innerTransfer/records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/subAccount/deposit/address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/deposit/subHisrec".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("capital/subAccount/innerTransfer/records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/deposit/riskRecords".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("capital/withdraw/apply".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/innerTransfer/apply".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/subAccountInnerTransfer/apply".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("capital/deposit/createSubAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("subAccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("allAccountBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("apiKey/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("apiKey/edit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("apiKey/del".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("updateStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("uid".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("apiKey/query".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/apiPermissions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/apiRestrictions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("allAccountBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("innerTransfer/authorizeSubAccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subAccount/asset/transferHistory".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("subAccount/transferAsset/supportCoins".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("subAccount/transferAsset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("user".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("auth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("userDataStream".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("userDataStream".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("userDataStream".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("copyTrading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("PFutures/traderDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("PFutures/profitHistorySummarys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("PFutures/profitDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("PFutures/tradingPairs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/traderDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/profitHistorySummarys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/profitDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/historyOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap/trace/setTPSL".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("PFutures/setCommission".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/trader/sellOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/transferRecord".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capital/deposit/hisrec".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/withdraw/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post/asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("asset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
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("transfer/supportCoins".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("agent".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account/inviteAccountList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("reward/commissionDataList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/inviteRelationCheck".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("asset/depositDetailList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("reward/third/commissionDataList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("asset/partnerData".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("commissionDataList/referralCode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/superiorCheck".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("wealth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product/dual-currency/pre-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("product/dual-currency/position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("product/dual-currency/order-records".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product/dual-currency/invest-asset-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("product/dual-currency/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
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.insert("3d".to_string(), Value::Str("3d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1M".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("400".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("401".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("403".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("404".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("429".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("418".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("504".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("100001".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("100004".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("100412".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("100413".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("100202".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("100204".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("100400".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("100410".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("100421".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("100440".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("100500".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("100503".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("80001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("80012".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("80014".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("80016".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("80017".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("100414".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("100419".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("100437".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("101204".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("110425".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("100490".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("101481".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("109201".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("109400".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("109418".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("109421".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("109425".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("109500".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("110500".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("Insufficient assets".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("illegal transferType".to_string(), Value::Str("BadRequest".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("SNOW".to_string(), Value::Str("Snowman".into()));
m.insert("OMNI".to_string(), Value::Str("OmniCat".into()));
m.insert("NAP".to_string(), Value::Str("$NAP".into()));
m.insert("TRUMP".to_string(), Value::Str("TRUMPMAGA".into()));
m.insert("TRUMPSOL".to_string(), Value::Str("TRUMP".into()));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("spot".into()));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeZone".to_string(), Value::Int(0));
m
}));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funding".to_string(), Value::Str("fund".into()));
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("future".to_string(), Value::Str("stdFutures".into()));
m.insert("swap".to_string(), Value::Str("USDTMPerp".into()));
m.insert("linear".to_string(), Value::Str("USDTMPerp".into()));
m.insert("inverse".to_string(), Value::Str("coinMPerp".into()));
m
}));
m.insert("accountsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fund".to_string(), Value::Str("funding".into()));
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("stdFutures".to_string(), Value::Str("future".into()));
m.insert("USDTMPerp".to_string(), Value::Str("linear".into()));
m.insert("coinMPerp".to_string(), Value::Str("inverse".into()));
m
}));
m.insert("recvWindow".to_string(), (match (&(Value::Int(5)), &(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 }));
m.insert("broker".to_string(), Value::Str("CCXT".into()));
m.insert("defaultNetworks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ETH".to_string(), Value::Str("ETH".into()));
m.insert("USDT".to_string(), Value::Str("ERC20".into()));
m.insert("USDC".to_string(), Value::Str("ERC20".into()));
m.insert("BTC".to_string(), Value::Str("BTC".into()));
m.insert("LTC".to_string(), Value::Str("LTC".into()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ARBITRUM".to_string(), Value::Str("ARB".into()));
m.insert("MATIC".to_string(), Value::Str("POLYGON".into()));
m.insert("ZKSYNC".to_string(), Value::Str("ZKSYNCERA".into()));
m.insert("AVAXC".to_string(), Value::Str("AVAX-C".into()));
m.insert("HBAR".to_string(), Value::Str("HEDERA".into()));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultForLinear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(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("limit".to_string(), Value::Int(512));
m.insert("daysBack".to_string(), Value::Int(30));
m.insert("untilDays".to_string(), Value::Int(30));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrder".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(false));
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::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Int(20000));
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::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
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("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1440));
m
}));
m
}));
m.insert("defaultForInverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("defaultForLinear".into()));
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("defaultForLinear".into()));
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Bool(true));
m
}));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("trailing".to_string(), Value::Bool(false));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Int(1));
m.insert("untilDays".to_string(), Value::Int(1));
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(100));
m.insert("untilDays".to_string(), Value::Null);
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("defaultForLinear".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("defaultForInverse".into()));
m
}));
m
}));
m
}));
m.insert("rollingWindowSize".to_string(), Value::Int(2000));
m
})]);
Value::Null
}
/*
* @method
* @name bingx#fetchTime
* @description fetches the current integer timestamp in milliseconds from the bingx server
* @see https://bingx-api.github.io/docs/#/swapV2/base-info.html#Get%20Server%20Time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the bingx server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.swap_v2_public_get_server_time(&[params]).await;
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "serverTime": 1675319535362
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[]);
return self.safe_integer_k(data, "serverTime", &[]);
Value::Null
}
/*
* @method
* @name bingx#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Wallet%20Deposits%20and%20Withdrawals/Query%20currency%20deposit%20and%20withdrawal%20data
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if !(self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true)) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut isSandbox: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if (isSandbox.as_bool() == Some(true)) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
let mut response: Value = self.wallets_v1_private_get_capital_config_getall(&[params]).await;
//
// {
// "code": "0",
// "timestamp": "1779364918914",
// "data": [
// {
// "coin": "BTC",
// "name": "BTC",
// "networkList": [
// {
// "name": "BTC",
// "network": "BTC",
// "isDefault": true,
// "minConfirm": "2",
// "withdrawEnable": true,
// "depositEnable": true,
// "withdrawFee": "0.00004",
// "withdrawMax": "64.77131128",
// "withdrawMin": "0.000046",
// "depositMin": "0.00009",
// "withdrawPrecision": "8",
// "depositPrecision": "8",
// "contractAddress": "",
// "needTagOrMemo": "false",
// "displayName": "BTC"
// },
// {
// "name": "BTC",
// "network": "BEP20",
// "isDefault": true,
// "minConfirm": "10",
// "withdrawEnable": true,
// "depositEnable": true,
// "withdrawFee": "0.000001",
// "withdrawMax": "64.77131128",
// "withdrawMin": "0.000065",
// "depositMin": "0.000012",
// "withdrawPrecision": "8",
// "depositPrecision": "18",
// "contractAddress": "0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c",
// "needTagOrMemo": "false",
// "displayName": "BTCBEP20"
// }
// ]
// },
// ...
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_currencies(data);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut currencyId: Value = self.safe_string_k(rawCurrency.clone(), "coin", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut name: Value = self.safe_string_k(rawCurrency.clone(), "name", &[]);
let mut networkList: Value = self.safe_list_k(rawCurrency.clone(), "networkList", &[]);
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_295: bool = true;
while { if !__for_first_295 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_295 = false; j.as_f64().unwrap_or(f64::NAN) < ((networkList.len() as i64) as f64) } {
let mut rawNetwork: Value = networkList.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut network: Value = self.safe_string_k(rawNetwork.clone(), "network", &[]);
let mut networkCode: Value = self.network_id_to_code(&[network.clone(), code.clone()]);
let mut limits: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(rawNetwork.clone(), "withdrawMin", &[]));
m.insert("max".to_string(), self.safe_number_k(rawNetwork.clone(), "withdrawMax", &[]));
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(rawNetwork.clone(), "depositMin", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
});
let mut precision: Value = self.parse_number(self.parse_precision(&[self.safe_string_k(rawNetwork.clone(), "withdrawPrecision", &[])]), &[]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkCode), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rawNetwork.clone());
m.insert("id".to_string(), network);
m.insert("network".to_string(), networkCode.clone());
m.insert("fee".to_string(), self.safe_number_k(rawNetwork.clone(), "withdrawFee", &[]));
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), self.safe_bool_k(rawNetwork.clone(), "depositEnable", &[]));
m.insert("withdraw".to_string(), self.safe_bool_k(rawNetwork, "withdrawEnable", &[]));
m.insert("precision".to_string(), precision);
m.insert("limits".to_string(), limits);
m
})); }
}
}
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rawCurrency);
m.insert("code".to_string(), code);
m.insert("id".to_string(), currencyId);
m.insert("precision".to_string(), Value::Null);
m.insert("name".to_string(), name);
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("networks".to_string(), networks);
m.insert("fee".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("crypto".into()));
m
}));
Value::Null
}
pub async fn fetch_spot_markets(&mut self, mut params: Value) -> Value {
let mut response: Value = self.spot_v1_public_get_common_symbols(&[params]).await;
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "symbols": [
// {
// "symbol": "GEAR-USDT",
// "minQty": 735, // deprecated
// "maxQty": 2941177, // deprecated.
// "minNotional": 5,
// "maxNotional": 20000,
// "status": 1,
// "tickSize": 0.000001,
// "stepSize": 1,
// "apiStateSell": true,
// "apiStateBuy": true,
// "timeOnline": 0,
// "offTime": 0,
// "maintainTime": 0
// },
// ...
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[]);
let mut markets: Value = self.safe_list_k(data, "symbols", &[Value::from(vec![])]);
return self.parse_markets(markets);
Value::Null
}
pub async fn fetch_swap_markets(&mut self, mut params: Value) -> Value {
let mut response: Value = self.swap_v2_public_get_quote_contracts(&[params]).await;
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "contractId": "100",
// "symbol": "BTC-USDT",
// "size": "0.0001",
// "quantityPrecision": "4",
// "pricePrecision": "1",
// "feeRate": "0.0005",
// "makerFeeRate": "0.0002",
// "takerFeeRate": "0.0005",
// "tradeMinLimit": "0",
// "tradeMinQuantity": "0.0001",
// "tradeMinUSDT": "2",
// "maxLongLeverage": "125",
// "maxShortLeverage": "125",
// "currency": "USDT",
// "asset": "BTC",
// "status": "1",
// "apiStateOpen": "true",
// "apiStateClose": "true",
// "ensureTrigger": true,
// "triggerFeeRate": "0.00020000"
// },
// ...
// ]
// }
//
let mut markets: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_markets(markets);
Value::Null
}
pub async fn fetch_inverse_swap_markets(&mut self, mut params: Value) -> Value {
let mut response: Value = self.cswap_v1_public_get_market_contracts(&[params]).await;
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720074487610,
// "data": [
// {
// "symbol": "BNB-USD",
// "pricePrecision": 2,
// "minTickSize": "10",
// "minTradeValue": "10",
// "minQty": "1.00000000",
// "status": 1,
// "timeOnline": 1713175200000
// },
// ]
// }
//
let mut markets: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_markets(markets);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut symbolParts: Value = split(&id, &Value::Str("-".into()));
let mut baseId: Value = symbolParts.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut quoteId: Value = symbolParts.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut currency: Value = self.safe_string_k(market.clone(), "currency", &[]);
let mut checkIsInverse: Value = Value::Bool(false);
let mut checkIsLinear: Value = Value::Bool(true);
let mut inverseContractSize: Value = self.safe_number_k(market.clone(), "minTickSize", &[]);
if (inverseContractSize != Value::Null) {
// inverse swap market
currency = baseId.clone();
checkIsInverse = Value::Bool(true);
checkIsLinear = Value::Bool(false);
}
let mut settle: Value = self.safe_currency_code(currency.clone(), &[]);
let mut pricePrecision: Value = self.safe_number_k(market.clone(), "tickSize", &[]);
if (pricePrecision == Value::Null) {
pricePrecision = self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "pricePrecision", &[])]), &[]);
}
let mut quantityPrecision: Value = self.safe_number_k(market.clone(), "stepSize", &[]);
if (quantityPrecision == Value::Null) {
quantityPrecision = self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "quantityPrecision", &[])]), &[]);
}
let mut type_var: Value = Value::Str("spot".into());
if (settle != Value::Null) {
type_var = Value::Str("swap".into());
}
let mut spot: Value = Value::Bool(type_var.as_str() == Some("spot"));
let mut swap: Value = Value::Bool(type_var.as_str() == Some("swap"));
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if (settle != Value::Null) {
symbol = Value::Str(format!("{}{}", symbol, Value::Str(format!("{}{}", Value::Str(":".into()), settle).into())).into());
}
let mut fees: Value = self.safe_dict(self.fees.clone(), type_var.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut contractSize: Value = Value::Null;
if matches!(&swap, Value::Bool(true)) {
contractSize = (if checkIsInverse.as_bool() == Some(true) { inverseContractSize } else { self.parse_number(Value::Str("1".into()), &[]) });
}
let mut isActive: Value = Value::Bool(false);
if (self.safe_string_k(market.clone(), "apiStateOpen", &[]).as_str() == Some("true")) && (self.safe_string_k(market.clone(), "apiStateClose", &[]).as_str() == Some("true")) {
isActive = Value::Bool(true); // swap active
} else if matches!((self.safe_bool_k(market.clone(), "apiStateSell", &[Value::Bool(false)])), Value::Bool(true)) && matches!((self.safe_bool_k(market.clone(), "apiStateBuy", &[Value::Bool(false)])), Value::Bool(true)) && (self.safe_string_k(market.clone(), "status", &[]).as_str() == Some("1")) {
isActive = Value::Bool(true); // spot active
} else if checkIsInverse.as_bool() == Some(true) && (self.safe_string_k(market.clone(), "status", &[]).as_str() == Some("1")) {
isActive = Value::Bool(true); // inverse swap active
}
let mut isInverse: Value = (if matches!(&spot, Value::Bool(true)) { Value::Null } else { checkIsInverse });
let mut isLinear: Value = (if matches!(&spot, Value::Bool(true)) { Value::Null } else { checkIsLinear });
let mut minAmount: Value = Value::Null;
if !(matches!(&spot, Value::Bool(true))) {
minAmount = self.safe_number2(market.clone(), Value::Str("minQty".into()), Value::Str("tradeMinQuantity".into()), &[]);
}
let mut timeOnline: Value = self.safe_integer_k(market.clone(), "timeOnline", &[]);
if (timeOnline.as_f64() == Some(0.0)) {
timeOnline = Value::Null;
}
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(), currency);
m.insert("type".to_string(), type_var);
m.insert("spot".to_string(), spot);
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), swap.clone());
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), isActive);
m.insert("contract".to_string(), swap);
m.insert("linear".to_string(), isLinear);
m.insert("inverse".to_string(), isInverse);
m.insert("taker".to_string(), self.safe_number_k(fees.clone(), "taker", &[]));
m.insert("maker".to_string(), self.safe_number_k(fees.clone(), "maker", &[]));
m.insert("feeSide".to_string(), self.safe_string_k(fees, "feeSide", &[]));
m.insert("contractSize".to_string(), 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(), quantityPrecision);
m.insert("price".to_string(), pricePrecision);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minAmount);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_n(market.clone(), Value::from(vec![Value::Str("minNotional".into()), Value::Str("tradeMinUSDT".into()), Value::Str("minTradeValue".into())]), &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "maxNotional", &[]));
m
}));
m
}));
m.insert("created".to_string(), timeOnline);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
/*
* @method
* @name bingx#fetchMarkets
* @description retrieves data on all markets for bingx
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/Spot%20trading%20symbols
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/USDT-M%20Perp%20Futures%20symbols
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Contract%20Information
* @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 requests: Value = Value::from(vec![self.fetch_swap_markets(params.clone()).await]);
let mut isSandbox: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if (isSandbox.as_bool() != Some(true)) {
append_to_array(&mut requests, self.fetch_inverse_swap_markets(params.clone()).await);
append_to_array(&mut requests, self.fetch_spot_markets(params).await); // sandbox is swap only
}
let mut promises: Value = promise_all(&requests).await;
let mut linearSwapMarkets: Value = self.safe_list(promises.clone(), Value::Int(0), &[Value::from(vec![])]);
let mut inverseSwapMarkets: Value = self.safe_list(promises.clone(), Value::Int(1), &[Value::from(vec![])]);
let mut spotMarkets: Value = self.safe_list(promises, Value::Int(2), &[Value::from(vec![])]);
let mut swapMarkets: Value = self.array_concat(linearSwapMarkets, inverseSwapMarkets);
return self.array_concat(spotMarkets, swapMarkets);
Value::Null
}
/*
* @method
* @name bingx#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/Kline%2FCandlestick%20Data
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Kline%2FCandlestick%20Data
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Mark%20Price%20Kline%2FCandlestick%20Data
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Get%20K-line%20Data
* @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 1000 for inverse swaps, 1440 otherwise)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut maxLimit: Value = (if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Int(1000) } else { Value::Int(1440) });
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, since.clone(), limit.clone(), timeframe.clone(), paramsPaginate.clone(), maxLimit.clone()]).await;
}
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 let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("interval".into(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()])); }
let mut requestLimit: Value = (if (limit == Value::Null) { Value::Int(500) } else { crate::runtime::Math::min(&limit, &maxLimit) });
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), crate::runtime::Math::max(&(match (&(since), &(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 }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), requestLimit.clone()); }
}
let mut until: Value = self.safe_integer2(paramsPaginate.clone(), Value::Str("until".into()), Value::Str("endTime".into()), &[]);
let mut paramsUntil: Value = (if (until != Value::Null) { self.omit(paramsPaginate.clone(), Value::from(vec![Value::Str("until".into())]), &[]) } else { paramsPaginate });
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
} else if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (since != Value::Null) {
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 });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), self.sum(&[since.clone(), (match (&(duration), &(requestLimit)) { (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 response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
// bingx spot klines are anchored to UTC+8 by default, unlike the swap klines and other exchanges
// the timeZone request parameter aligns the candle boundaries to UTC, live-verified for the spot endpoint
let mut timeZoneparamsTimeZoneVariable = self.handle_option_integer_and_params(paramsUntil.clone(), Value::Str("fetchOHLCV".into()), Value::Str("timeZone".into()), &[Value::Int(0)]);
let mut timeZone: Value = timeZoneparamsTimeZoneVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsTimeZone: Value = timeZoneparamsTimeZoneVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (timeZone != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeZone".into(), timeZone); }
}
let __ws_arg_0 = self.extend(request.clone(), &[paramsTimeZone]);
response = self.spot_v1_public_get_market_kline(&[__ws_arg_0]).await;
} else {
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_1 = self.extend(request.clone(), &[paramsUntil.clone()]);
response = self.cswap_v1_public_get_market_klines(&[__ws_arg_1]).await;
} else {
let mut price: Option<String> = self.safe_string_k(paramsUntil.clone(), "price", &[]).as_str().map(str::to_owned);
let mut paramsPrice: Value = self.omit(paramsUntil, Value::Str("price".into()), &[]);
if (price.as_deref() == Some("mark")) {
let __ws_arg_2 = self.extend(request.clone(), &[paramsPrice.clone()]);
response = self.swap_v1_public_get_market_mark_price_klines(&[__ws_arg_2]).await;
} else {
let __ws_arg_3 = self.extend(request, &[paramsPrice]);
response = self.swap_v3_public_get_quote_klines(&[__ws_arg_3]).await;
}
}
}
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "open": "19396.8",
// "close": "19394.4",
// "high": "19397.5",
// "low": "19385.7",
// "volume": "110.05",
// "time": 1666583700000
// },
// ...
// ]
// }
//
// fetchMarkOHLCV
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "open": "42191.7",
// "close": "42189.5",
// "high": "42196.5",
// "low": "42189.5",
// "volume": "0.00",
// "openTime": 1706508840000,
// "closeTime": 1706508840000
// }
// ]
// }
//
let mut ohlcvs: Value = self.safe_value_k(response, "data", &[Value::from(vec![])]);
if !(matches!(&ohlcvs, Value::Arr(_))) {
ohlcvs = Value::from(vec![ohlcvs.clone()]);
}
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "open": "19394.4",
// "close": "19379.0",
// "high": "19394.4",
// "low": "19368.3",
// "volume": "167.44",
// "time": 1666584000000
// }
//
// fetchMarkOHLCV
//
// {
// "open": "42191.7",
// "close": "42189.5",
// "high": "42196.5",
// "low": "42189.5",
// "volume": "0.00",
// "openTime": 1706508840000,
// "closeTime": 1706508840000
// }
// spot
// [
// 1691402580000,
// 29093.61,
// 29093.93,
// 29087.73,
// 29093.24,
// 0.59,
// 1691402639999,
// 17221.07
// ]
//
if (matches!(&ohlcv, Value::Arr(_))) {
return Value::from(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv.clone(), Value::Int(5), &[])]);
}
return Value::from(vec![self.safe_integer2(ohlcv.clone(), Value::Str("time".into()), Value::Str("closeTime".into()), &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number_k(ohlcv, "volume", &[])]);
Value::Null
}
/*
* @method
* @name bingx#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/Recent%20Trades%20List
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Recent%20Trades%20List
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn 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);
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() is not supported for inverse swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut response: Value = Value::Null;
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTrades".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (limit != Value::Null) {
let mut maxLimit: Value = (if (marketType.as_str() == Some("spot")) { Value::Int(500) } else { Value::Int(1000) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &maxLimit)); }
}
if (marketType.as_str() == Some("spot")) {
let __ws_arg_4 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.spot_v1_public_get_market_trades(&[__ws_arg_4]).await;
} else {
let __ws_arg_5 = self.extend(request, &[paramsMarketType]);
response = self.swap_v2_public_get_quote_trades(&[__ws_arg_5]).await;
}
//
// spot
//
// {
// "code": 0,
// "data": [
// {
// "id": 43148253,
// "price": 25714.71,
// "qty": 1.674571,
// "time": 1655085975589,
// "buyerMaker": false
// }
// ]
// }
//
// swap
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "time": 1672025549368,
// "isBuyerMaker": true,
// "price": "16885.0",
// "qty": "3.3002",
// "quoteQty": "55723.87"
// },
// ...
// ]
// }
//
let mut trades: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(trades, &[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);
//
// spot fetchTrades
//
// {
// "id": 43148253,
// "price": 25714.71,
// "qty": 1.674571,
// "time": 1655085975589,
// "buyerMaker": false
// }
//
// spot fetchMyTrades
//
// {
// "symbol": "LTC-USDT",
// "id": 36237072,
// "orderId": 1674069326895775744,
// "price": "85.891",
// "qty": "0.0582",
// "quoteQty": "4.9988562000000005",
// "commission": -0.00005820000000000001,
// "commissionAsset": "LTC",
// "time": 1687964205000,
// "isBuyer": true,
// "isMaker": false
// }
//
// swap fetchTrades
//
// {
// "time": 1672025549368,
// "isBuyerMaker": true,
// "price": "16885.0",
// "qty": "3.3002",
// "quoteQty": "55723.87"
// }
//
// swap fetchMyTrades
//
// {
// "volume": "0.1",
// "price": "106.75",
// "amount": "10.6750",
// "commission": "-0.0053",
// "currency": "USDT",
// "orderId": "1676213270274379776",
// "liquidatedPrice": "0.00",
// "liquidatedMarginRatio": "0.00",
// "filledTime": "2023-07-04T20:56:01.000+0800"
// }
//
// ws spot
//
// {
// "E": 1690214529432,
// "T": 1690214529386,
// "e": "trade",
// "m": true,
// "p": "29110.19",
// "q": "0.1868",
// "s": "BTC-USDT",
// "t": "57903921"
// }
//
// ws linear swap
//
// {
// "q": "0.0421",
// "p": "29023.5",
// "T": 1690221401344,
// "m": false,
// "s": "BTC-USDT"
// }
//
// ws inverse swap
//
// {
// "e": "trade",
// "E": 1722920589665,
// "s": "BTC-USD",
// "t": "39125001",
// "p": "55360.0",
// "q": "1",
// "T": 1722920589582,
// "m": false
// }
//
// inverse swap fetchMyTrades
//
// {
// "orderId": "1817441228670648320",
// "symbol": "SOL-USD",
// "type": "MARKET",
// "side": "BUY",
// "positionSide": "LONG",
// "tradeId": "97244554",
// "volume": "2",
// "tradePrice": "182.652",
// "amount": "20.00000000",
// "realizedPnl": "0.00000000",
// "commission": "-0.00005475",
// "currency": "SOL",
// "buyer": true,
// "maker": false,
// "tradeTime": 1722146730000
// }
//
let mut time: Value = self.safe_integer_n(trade.clone(), Value::from(vec![Value::Str("time".into()), Value::Str("filledTm".into()), Value::Str("T".into()), Value::Str("tradeTime".into())]), &[]);
let mut datetimeId: Value = self.safe_string_k(trade.clone(), "filledTm", &[]);
if (datetimeId != Value::Null) {
time = self.parse8601(datetimeId);
}
if (time.as_f64() == Some(0.0)) {
time = Value::Null;
}
let mut cost: Value = self.safe_string_k(trade.clone(), "quoteQty", &[]);
// const type = (cost === undefined) ? 'spot' : 'swap'; this is not reliable
let mut currencyId: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("currency".into()), Value::Str("N".into()), Value::Str("commissionAsset".into())]), &[]);
let mut currencyCode: Value = self.safe_currency_code(currencyId, &[]);
let mut m: Value = self.safe_bool_k(trade.clone(), "m", &[]);
let mut marketId: Value = self.safe_string2(trade.clone(), Value::Str("s".into()), Value::Str("symbol".into()), &[]);
let mut isBuyerMaker: Value = self.safe_bool_n(trade.clone(), Value::from(vec![Value::Str("buyerMaker".into()), Value::Str("isBuyerMaker".into()), Value::Str("maker".into())]), &[]);
let mut takeOrMaker: Value = Value::Null;
let mut isMakerSide: bool = (isBuyerMaker.as_bool() == Some(true)) || (m.as_bool() == Some(true));
if (isBuyerMaker != Value::Null) || (m != Value::Null) {
takeOrMaker = (if isMakerSide { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
let mut side: Value = self.safe_string_lower2(trade.clone(), Value::Str("side".into()), Value::Str("S".into()), &[]);
if (side == Value::Null) {
if (isBuyerMaker != Value::Null) || (m != Value::Null) {
side = (if isMakerSide { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
takeOrMaker = Value::Str("taker".into());
}
}
let mut isBuyer: Value = self.safe_bool_k(trade.clone(), "isBuyer", &[]);
if (isBuyer != Value::Null) {
side = (if isBuyer.as_bool() == Some(true) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
let mut isMaker: Value = self.safe_bool_k(trade.clone(), "isMaker", &[]);
if (isMaker != Value::Null) {
takeOrMaker = (if isMaker.as_bool() == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
let mut amount: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("qty".into()), Value::Str("amount".into()), Value::Str("q".into())]), &[]);
if (market != Value::Null) && (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (matches!(&trade, Value::Dict(__d) if __d.contains_key("volume"))) {
// Linear volume is the base quantity (contractSize 1); inverse volume is the contract count.
// safeTrade applies contractSize when calculating inverse cost.
amount = self.safe_string_k(trade.clone(), "volume", &[]);
}
let mut price: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("price".into()), Value::Str("p".into()), Value::Str("tradePrice".into())]), &[]);
if (market != Value::Null) && (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (self.safe_string_k(trade.clone(), "x", &[]).as_str() == Some("TRADE")) {
let mut lastAmount: Value = self.safe_string_k(trade.clone(), "l", &[]);
let mut lastPrice: Value = self.safe_string_k(trade.clone(), "L", &[]);
if (lastAmount != Value::Null) && (lastPrice != Value::Null) {
// Linear WS l/L describe the last fill, not the original order's q/p.
amount = lastAmount;
price = lastPrice;
}
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("id".into()), Value::Str("t".into()), Value::Str("fillId".into()), Value::Str("tradeId".into())]), &[]));
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), time.clone());
m.insert("datetime".to_string(), self.iso8601(time));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone(), Value::Str("-".into())]));
m.insert("order".to_string(), self.safe_string2(trade.clone(), Value::Str("orderId".into()), Value::Str("i".into()), &[]));
m.insert("type".to_string(), self.safe_string_lower_k(trade.clone(), "o", &[]));
m.insert("side".to_string(), self.parse_order_side(side).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("takerOrMaker".to_string(), takeOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(crate::precise::Precise::stringAbs(&self.safe_string2(trade, Value::Str("commission".into()), Value::Str("n".into()), &[])), &[]));
m.insert("currency".to_string(), currencyCode);
m
}));
m
}), &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/Order%20Book
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Order%20Book
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Query%20Depth%20Data
* @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 (max 1000)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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 response: Value = Value::Null;
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOrderBook".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (limit != Value::Null) {
if (marketType.as_str() == Some("spot")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), self.find_nearest_ceiling(Value::from(vec![Value::Int(5), Value::Int(10), Value::Int(20), Value::Int(50), Value::Int(100), Value::Int(500), Value::Int(1000)]), limit)); }
}
}
if (marketType.as_str() == Some("spot")) {
let __ws_arg_6 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.spot_v1_public_get_market_depth(&[__ws_arg_6]).await;
} else {
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_7 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.cswap_v1_public_get_market_depth(&[__ws_arg_7]).await;
} else {
let __ws_arg_8 = self.extend(request, &[paramsMarketType]);
response = self.swap_v2_public_get_quote_depth(&[__ws_arg_8]).await;
}
}
//
// spot
//
// {
// "code":0,
// "timestamp":1743240504535,
// "data":{
// "bids":[
// ["83775.39","1.981875"],
// ["83775.38","0.001076"],
// ["83775.34","0.254716"],
// ],
// "asks":[
// ["83985.40","0.000013"],
// ["83980.00","0.000011"],
// ["83975.70","0.000061000000000000005"],
// ],
// "ts":1743240504535,
// "lastUpdateId":13565639906
// }
// }
//
//
// linear swap
//
// {
// "code":0,
// "msg":"",
// "data":{
// "T":1743240836255,
// "bids":[
// ["83760.7","7.0861"],
// ["83760.6","0.0044"],
// ["83757.7","1.9526"],
// ],
// "asks":[
// ["83784.3","8.3531"],
// ["83782.8","23.7289"],
// ["83780.1","18.0617"],
// ],
// "bidsCoin":[
// ["83760.7","0.0007"],
// ["83760.6","0.0000"],
// ["83757.7","0.0002"],
// ],
// "asksCoin":[
// ["83784.3","0.0008"],
// ["83782.8","0.0024"],
// ["83780.1","0.0018"],
// ]
// }
// }
//
// inverse swap
//
// {
// "code":0,
// "msg":"",
// "timestamp":1743240979146,
// "data":{
// "T":1743240978691,
// "bids":[
// ["83611.4","241.0"],
// ["83611.3","1.0"],
// ["83602.9","666.0"],
// ],
// "asks":[
// ["83645.0","4253.0"],
// ["83640.5","3188.0"],
// ["83636.0","5540.0"],
// ]
// }
// }
//
let mut orderbook: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "lastUpdateId", &[]);
let mut timestamp: Value = self.safe_integer2(orderbook.clone(), Value::Str("T".into()), Value::Str("ts".into()), &[]);
let mut result: Value = self.parse_order_book(orderbook, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Int(0), Value::Int(1)]);
add_element_to_object(&mut result, &Value::Str("nonce".into()), nonce);
return result;
Value::Null
}
/*
* @method
* @name bingx#fetchFundingRate
* @description fetch the current funding rate
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Mark%20Price%20and%20Funding%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Price%20%26%20Current%20Funding%20Rate
* @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 mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_public_get_market_premium_index(&[__ws_arg_9]).await;
} else {
let __ws_arg_10 = self.extend(request, &[params]);
response = self.swap_v2_public_get_quote_premium_index(&[__ws_arg_10]).await;
}
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "symbol": "BTC-USDT",
// "markPrice": "16884.5",
// "indexPrice": "16886.9",
// "lastFundingRate": "0.0001",
// "nextFundingTime": 1672041600000
// },
// ...
// ]
// }
//
let mut data: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut dataList: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
data = self.safe_dict(dataList, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
data = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
return self.parse_funding_rate(data, &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchFundingRates
* @description fetch the current funding rate for multiple symbols
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Mark%20Price%20and%20Funding%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Price%20%26%20Current%20Funding%20Rate
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subType] "linear" or "inverse" (default is linear)
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Str("swap".into()), Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut firstMarket: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut subType: Value = Value::Str("linear".into());
let mut subTypeOptionparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchFundingRates".into()), &[firstMarket, params, subType]);
let mut subTypeOption: Value = subTypeOptionparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeOptionparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (subTypeOption.as_str() == Some("inverse")) {
response = self.cswap_v1_public_get_market_premium_index(&[paramsSubType.clone()]).await;
} else {
response = self.swap_v2_public_get_quote_premium_index(&[paramsSubType]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_funding_rates(data, &[symbolsNormalized]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "symbol": "BTC-USDT",
// "markPrice": "16884.5",
// "indexPrice": "16886.9",
// "lastFundingRate": "0.0001",
// "nextFundingTime": 1672041600000,
// "fundingIntervalHours": 8,
// "updateTime": 1672012800000
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut nextFundingTimestamp: Value = self.safe_integer_k(contract.clone(), "nextFundingTime", &[]);
let mut timestamp: Value = self.safe_integer_k(contract.clone(), "updateTime", &[]);
let mut interval: Value = self.safe_string_k(contract.clone(), "fundingIntervalHours", &[]);
let mut intervalString: Value = Value::Null;
if (interval != Value::Null) {
intervalString = Value::Str(format!("{}{}", interval, Value::Str("h".into())).into());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Str("-".into()), Value::Str("swap".into())]));
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "markPrice", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract.clone(), "indexPrice", &[]));
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(), intervalString);
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Get%20Funding%20Rate%20History
* @param {string} symbol unified symbol of the market to fetch the funding rate history for, inverse (Coin-M) markets are not supported
* @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 (max 1000)
* @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
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() is not supported for inverse swap markets".into()))));
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchFundingRateHistory".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("fetchFundingRateHistory".into()), &[symbol, since.clone(), limit.clone(), Value::Str("8h".into()), paramsPaginate.clone()]).await;
}
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(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, paramsPaginate, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_11 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.swap_v2_public_get_quote_funding_rate(&[__ws_arg_11]).await;
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "symbol": "BTC-USDT",
// "fundingRate": "0.0001",
// "fundingTime": 1585684800000
// },
// ...
// ]
// }
//
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": "BTC-USDT",
// "fundingRate": "0.0001",
// "fundingTime": 1585684800000
// }
//
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(self.safe_string_k(contract.clone(), "symbol", &[]), &[market, Value::Str("-".into()), Value::Str("swap".into())]));
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 bingx#fetchFundingHistory
* @description fetches historical funding received
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Account%20Endpoints/Get%20Account%20Profit%20and%20Loss%20Fund%20Flow
* @param {string} symbol unified symbol of the market to fetch the funding history for, inverse (Coin-M) markets are not supported
* @param {int} [since] timestamp in ms of the earliest funding to fetch
* @param {int} [limit] the maximum amount of [funding history structures]{@link https://docs.ccxt.com/?id=funding-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subType] 'linear' or 'inverse' (default is 'linear'), 'inverse' is not supported
* @param {int} [params.until] timestamp in ms of the latest funding to fetch
* @returns {object[]} a list of [funding history structures]{@link https://docs.ccxt.com/?id=funding-history-structure}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchFundingHistory".into()), &[market.clone(), params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut isInverse: Value = (if (market != Value::Null) { (Value::Bool(market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) } else { (Value::Bool(subType.as_str() == Some("inverse"))) });
if is_true(&isInverse) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() is not supported for inverse swap markets".into()))));
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(paramsSubType, Value::Str("fetchFundingHistory".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("fetchFundingHistory".into()), &[symbol, since.clone(), limit.clone(), Value::Str("24h".into()), paramsPaginate.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("incomeType".to_string(), Value::Str("FUNDING_FEE".into()));
m
});
if (market != Value::Null) {
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 (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 until: Value = self.safe_integer2(paramsPaginate.clone(), Value::Str("until".into()), Value::Str("endTime".into()), &[]);
let mut paramsUntil: Value = (if (until != Value::Null) { self.omit(paramsPaginate.clone(), Value::from(vec![Value::Str("until".into())]), &[]) } else { paramsPaginate });
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_12 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.swap_v2_private_get_user_income(&[__ws_arg_12]).await;
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "symbol": "LDO-USDT",
// "incomeType": "FUNDING_FEE",
// "income": "-0.0292",
// "asset": "USDT",
// "info": "Funding Fee",
// "time": 1702713615000,
// "tranId": "170***6*2_3*9_20***97",
// "tradeId": "170***6*2_3*9_20***97"
// }
// ]
// }
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_incomes(data, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// {
// "symbol": "LDO-USDT",
// "incomeType": "FUNDING_FEE",
// "income": "-0.0292",
// "asset": "USDT",
// "info": "Funding Fee",
// "time": 1702713615000,
// "tranId": "170***6*2_3*9_20***97",
// "tradeId": "170***6*2_3*9_20***97"
// }
let mut marketId: Value = self.safe_string_k(income.clone(), "symbol", &[]);
let mut currencyId: Value = self.safe_string_k(income.clone(), "asset", &[]);
let mut timestamp: Value = self.safe_integer_k(income.clone(), "time", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("swap".into())]));
m.insert("code".to_string(), self.safe_currency_code(currencyId, &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), self.safe_string_k(income.clone(), "tranId", &[]));
m.insert("amount".to_string(), self.safe_number_k(income, "income", &[]));
m.insert("type".to_string(), Value::Str("funding".into()));
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchOpenInterest
* @description retrieves the open interest of a trading pair
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Open%20Interest%20Statistics
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Get%20Swap%20Open%20Positions
* @param {string} symbol unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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 response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_13 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_public_get_market_open_interest(&[__ws_arg_13]).await;
} else {
let __ws_arg_14 = self.extend(request, &[params]);
response = self.swap_v2_public_get_quote_open_interest(&[__ws_arg_14]).await;
}
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "openInterest": "3289641547.10",
// "symbol": "BTC-USDT",
// "time": 1672026617364
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720328247986,
// "data": [
// {
// "symbol": "BTC-USD",
// "openInterest": "749.1160",
// "timestamp": 1720310400000
// }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
result = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
result = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
return self.parse_open_interest(result, &[market]);
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// linear swap
//
// {
// "openInterest": "3289641547.10",
// "symbol": "BTC-USDT",
// "time": 1672026617364
// }
//
// inverse swap
//
// {
// "symbol": "BTC-USD",
// "openInterest": "749.1160",
// "timestamp": 1720310400000
// }
//
let mut timestamp: Value = self.safe_integer2(interest.clone(), Value::Str("time".into()), Value::Str("timestamp".into()), &[]);
let mut id: Value = self.safe_string_k(interest.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(id, &[market.clone(), Value::Str("-".into()), Value::Str("swap".into())]);
let mut openInterest: Value = self.safe_number_k(interest.clone(), "openInterest", &[]);
let mut inverse: Value = self.safe_bool_k(market.clone(), "inverse", &[Value::Bool(false)]);
let mut isInverse: bool = inverse.as_bool() == Some(true);
let mut openInterestAmount: Value = (if isInverse { openInterest.clone() } else { Value::Null });
let mut openInterestValue: Value = (if isInverse { Value::Null } else { openInterest });
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("openInterestAmount".to_string(), openInterestAmount);
m.insert("openInterestValue".to_string(), openInterestValue);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), interest);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/24hr%20Ticker%20Price%20Change%20Statistics
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/24hr%20Ticker%20Price%20Change%20Statistics
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Query%2024-Hour%20Price%20Change
* @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 mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
response = self.spot_v1_public_get_ticker24hr(&[__ws_arg_15]).await;
} else {
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_public_get_market_ticker(&[__ws_arg_16]).await;
} else {
let __ws_arg_17 = self.extend(request, &[params]);
response = self.swap_v2_public_get_quote_ticker(&[__ws_arg_17]).await;
}
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[]);
if (data != Value::Null) {
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market.clone()]);
}
let mut dataDict: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(dataDict, &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Market%20Data/24hr%20Ticker%20Price%20Change%20Statistics
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/24hr%20Ticker%20Price%20Change%20Statistics
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Query%2024-Hour%20Price%20Change
* @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 market: Value = Value::Null;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
if (symbolsNormalized != Value::Null) {
let mut firstSymbol: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
if (firstSymbol != Value::Null) {
market = self.market(firstSymbol);
}
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTickers".into()), &[market.clone(), 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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchTickers".into()), &[market, paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
response = self.spot_v1_public_get_ticker24hr(&[paramsSubType.clone()]).await;
} else {
if (subType.as_str() == Some("inverse")) {
response = self.cswap_v1_public_get_market_ticker(&[paramsSubType.clone()]).await;
} else {
response = self.swap_v2_public_get_quote_ticker(&[paramsSubType]).await;
}
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// },
// ...
// ]
// }
//
let mut tickers: Value = self.safe_list_k(response, "data", &[]);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name bingx#fetchMarkPrice
* @description fetches mark prices for the market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Mark%20Price%20and%20Funding%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Price%20%26%20Current%20Funding%20Rate
* @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 dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_mark_price(&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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchMarkPrice".into()), &[market.clone(), params, Value::Str("linear".into())]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.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
});
let mut response: Value = Value::Null;
if (subType.as_str() == Some("inverse")) {
let __ws_arg_18 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_public_get_market_premium_index(&[__ws_arg_18]).await;
} else {
let __ws_arg_19 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_public_get_quote_premium_index(&[__ws_arg_19]).await;
}
if (matches!(&response.as_map().and_then(|__m| __m.get("data")).cloned().unwrap_or(Value::Null), Value::Arr(_))) {
return self.parse_ticker(self.safe_dict(response.as_map().and_then(|__m| __m.get("data")).cloned().unwrap_or(Value::Null), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), &[market.clone()]);
}
return self.parse_ticker(response.as_map().and_then(|__m| __m.get("data")).cloned().unwrap_or(Value::Null), &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchMarkPrices
* @description fetches mark prices for multiple markets
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Market%20Data/Mark%20Price%20and%20Funding%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Market%20Data/Price%20%26%20Current%20Funding%20Rate
* @param {string[]} [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_mark_prices(&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 market: Value = Value::Null;
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
if (symbolsNormalized != Value::Null) {
let mut firstSymbol: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
if (firstSymbol != Value::Null) {
market = self.market(firstSymbol);
}
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchMarkPrices".into()), &[market, params, Value::Str("linear".into())]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (subType.as_str() == Some("inverse")) {
response = self.cswap_v1_public_get_market_premium_index(&[paramsSubType.clone()]).await;
} else {
response = self.swap_v2_public_get_quote_premium_index(&[paramsSubType]).await;
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// },
// ...
// ]
// }
//
let mut tickers: Value = self.safe_list_k(response, "data", &[]);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// mark price
// {
// "symbol": "string",
// "lastFundingRate": "string",
// "markPrice": "string",
// "indexPrice": "string",
// "nextFundingTime": "int64"
// }
//
// spot
// {
// "symbol": "BTC-USDT",
// "openPrice": "26032.08",
// "highPrice": "26178.86",
// "lowPrice": "25968.18",
// "lastPrice": "26113.60",
// "volume": "1161.79",
// "quoteVolume": "30288466.44",
// "openTime": "1693081020762",
// "closeTime": "1693167420762",
// added 2023-11-10:
// "bidPrice": 16726.0,
// "bidQty": 0.05,
// "askPrice": 16726.0,
// "askQty": 0.05,
// }
// swap
//
// {
// "symbol": "BTC-USDT",
// "priceChange": "52.5",
// "priceChangePercent": "0.31%", // they started to add the percent sign in value
// "lastPrice": "16880.5",
// "lastQty": "2.2238", // only present in swap!
// "highPrice": "16897.5",
// "lowPrice": "16726.0",
// "volume": "245870.1692",
// "quoteVolume": "4151395117.73",
// "openPrice": "16832.0",
// "openTime": 1672026667803,
// "closeTime": 1672026648425,
// added 2023-11-10:
// "bidPrice": 16726.0,
// "bidQty": 0.05,
// "askPrice": 16726.0,
// "askQty": 0.05,
// }
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
let mut lastQty: Option<String> = self.safe_string_k(ticker.clone(), "lastQty", &[]).as_str().map(str::to_owned);
// in spot markets, lastQty is not present
// it's (bad, but) the only way we can check the tickers origin
let mut type_var: Value = Value::Str("swap".into());
if (lastQty.is_none()) {
type_var = Value::Str("spot".into());
}
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, type_var]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut open: Value = self.safe_string_k(ticker.clone(), "openPrice", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "highPrice", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "lowPrice", &[]);
let mut close: Value = self.safe_string_k(ticker.clone(), "lastPrice", &[]);
let mut quoteVolume: Value = self.safe_string_k(ticker.clone(), "quoteVolume", &[]);
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "volume", &[]);
let mut percentage: Value = self.safe_string_k(ticker.clone(), "priceChangePercent", &[]);
if (percentage != Value::Null) {
percentage = replace_str(&percentage, &Value::Str("%".into()), &Value::Str("".into()));
}
let mut change: Value = self.safe_string_k(ticker.clone(), "priceChange", &[]);
let mut ts: Value = self.safe_integer_k(ticker.clone(), "closeTime", &[]);
if (ts.as_f64() == Some(0.0)) {
ts = Value::Null;
}
let mut datetime: Value = self.iso8601(ts.clone());
let mut bid: Value = self.safe_string_k(ticker.clone(), "bidPrice", &[]);
let mut bidVolume: Value = self.safe_string_k(ticker.clone(), "bidQty", &[]);
let mut ask: Value = self.safe_string_k(ticker.clone(), "askPrice", &[]);
let mut askVolume: Value = self.safe_string_k(ticker.clone(), "askQty", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), ts);
m.insert("datetime".to_string(), datetime);
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bid".to_string(), bid);
m.insert("bidVolume".to_string(), bidVolume);
m.insert("ask".to_string(), ask);
m.insert("askVolume".to_string(), askVolume);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), open);
m.insert("close".to_string(), close);
m.insert("last".to_string(), Value::Null);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), change);
m.insert("percentage".to_string(), percentage);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "markPrice", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "indexPrice", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name bingx#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Account%20Endpoints/Query%20Assets
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Account%20Endpoints/Query%20account%20data
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Account%20Assets
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Fund%20Account/Query%20Assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.standard] whether to fetch standard contract balances
* @param {string} [params.type] the type of balance to fetch (spot, swap, funding) default is `spot`
* @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 response: Value = Value::Null;
let mut standardparamsStandardVariable = self.handle_option_bool_and_params(params, Value::Str("fetchBalance".into()), Value::Str("standard".into()), &[Value::Bool(false)]);
let mut standard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsStandard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, paramsStandard]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut marketTypemarketTypeQueryVariable = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, paramsSubType]);
let mut marketType: Value = marketTypemarketTypeQueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut marketTypeQuery: Value = marketTypemarketTypeQueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&standard) {
response = self.contract_v1_private_get_balance(&[marketTypeQuery.clone()]).await;
} else if (marketType.as_str() == Some("funding")) || (marketType.as_str() == Some("fund")) {
response = self.fund_v1_private_get_account_balance(&[marketTypeQuery.clone()]).await;
} else if (marketType.as_str() == Some("spot")) {
response = self.spot_v1_private_get_account_balance(&[marketTypeQuery.clone()]).await;
} else {
if (subType.as_str() == Some("inverse")) {
response = self.cswap_v1_private_get_user_balance(&[marketTypeQuery.clone()]).await;
} else {
response = self.swap_v3_private_get_user_balance(&[marketTypeQuery]).await;
}
}
return self.parse_balance(response);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// standard
//
// {
// "code": 0,
// "timestamp": 1721192833454,
// "data": [
// {
// "asset": "USDT",
// "balance": "4.72644300000000000000",
// "crossWalletBalance": "4.72644300000000000000",
// "crossUnPnl": "0",
// "availableBalance": "4.72644300000000000000",
// "maxWithdrawAmount": "4.72644300000000000000",
// "marginAvailable": false,
// "updateTime": 1721192833443
// },
// ]
// }
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "balances": [
// {
// "asset": "USDT",
// "free": "45.733046995800514",
// "locked": "0"
// },
// ]
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721191833813,
// "data": [
// {
// "asset": "SOL",
// "balance": "0.35707951",
// "equity": "0.35791051",
// "unrealizedProfit": "0.00083099",
// "availableMargin": "0.35160653",
// "usedMargin": "0.00630397",
// "freezedMargin": "0",
// "shortUid": "12851936"
// }
// ]
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "userId": "116***295",
// "asset": "USDT",
// "balance": "194.8212",
// "equity": "196.7431",
// "unrealizedProfit": "1.9219",
// "realisedProfit": "-109.2504",
// "availableMargin": "193.7609",
// "usedMargin": "1.0602",
// "freezedMargin": "0.0000",
// "shortUid": "12851936"
// }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut contractBalances: Value = self.safe_list_k(response.clone(), "data", &[]);
let mut firstContractBalances: Value = self.safe_dict(contractBalances.clone(), Value::Int(0), &[]);
let mut isContract: bool = firstContractBalances != Value::Null;
let mut spotData: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut spotBalances: Value = self.safe_list2(spotData, Value::Str("balances".into()), Value::Str("assets".into()), &[Value::from(vec![])]);
if isContract {
{
let mut i: Value = Value::Int(0);
let mut __for_first_296: bool = true;
while { if !__for_first_296 { 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_296 = false; i.as_f64().unwrap_or(f64::NAN) < ((contractBalances.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(contractBalances.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "asset", &[]);
if (currencyId == Value::Null) {
break;
}
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string2(balance.clone(), Value::Str("availableMargin".into()), Value::Str("availableBalance".into()), &[]));
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(balance.clone(), "usedMargin", &[]));
add_element_to_object(&mut account, &Value::Str("total".into()), self.safe_string_k(balance.clone(), "maxWithdrawAmount", &[]));
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_297: bool = true;
while { if !__for_first_297 { 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_297 = false; i.as_f64().unwrap_or(f64::NAN) < ((spotBalances.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(spotBalances.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), self.safe_string_k(balance.clone(), "free", &[]));
add_element_to_object(&mut account, &Value::Str("used".into()), self.safe_string_k(balance, "locked", &[]));
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 bingx#fetchPositionHistory
* @description fetches historical positions
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Position%20History
* @param {string} symbol unified contract symbol
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum amount of records to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch positions for
* @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.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
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("pageSize".into(), limit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTs".into(), since.clone()); }
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTs".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_20 = self.extend(requestUntil, &[paramsUntil]);
response = self.swap_v1_private_get_trade_position_history(&[__ws_arg_20]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPositionHistory() is not supported for inverse swap positions".into()))));
}
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "positionHistory": [
// {
// "positionId": "1861675561156571136",
// "symbol": "LTC-USDT",
// "isolated": false,
// "positionSide": "LONG",
// "openTime": 1732693017000,
// "updateTime": 1733310292000,
// "avgPrice": "95.18",
// "avgClosePrice": "129.48",
// "realisedProfit": "102.89",
// "netProfit": "99.63",
// "positionAmt": "30.0",
// "closePositionAmt": "30.0",
// "leverage": 6,
// "closeAllPositions": true,
// "positionCommission": "-0.33699650000000003",
// "totalFunding": "-2.921461693902908"
// },
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut records: Value = self.safe_list_k(data, "positionHistory", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(records, &[]);
return self.filter_by_symbol_since_limit(positions, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name bingx#fetchPositions
* @description fetch all open positions
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Account%20Endpoints/Query%20position%20data
* @see https://bingx-api.github.io/docs/#/en-us/standard/contract-interface.html#position
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20warehouse
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.standard] whether to fetch standard contract positions
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut standardparamsStandardVariable = self.handle_option_bool_and_params(params, Value::Str("fetchPositions".into()), Value::Str("standard".into()), &[Value::Bool(false)]);
let mut standard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsStandard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if is_true(&standard) {
response = self.contract_v1_private_get_all_position(&[paramsStandard.clone()]).await;
} else {
let mut market: Value = Value::Null;
if (symbolsNormalized != Value::Null) {
let mut firstSymbol: Value = self.safe_string(symbolsNormalized.clone(), Value::Int(0), &[]);
if (firstSymbol != Value::Null) {
market = self.market(firstSymbol);
}
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchPositions".into()), &[market, paramsStandard]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) {
response = self.cswap_v1_private_get_user_positions(&[paramsSubType.clone()]).await;
} else {
response = self.swap_v2_private_get_user_positions(&[paramsSubType]).await;
}
}
let mut positions: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_positions(positions, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name bingx#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Account%20Endpoints/Query%20position%20data
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20warehouse
* @param {string} symbol unified market symbol of the market the position is held in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() supports swap markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_private_get_user_positions(&[__ws_arg_21]).await;
} else {
let __ws_arg_22 = self.extend(request, &[params]);
response = self.swap_v2_private_get_user_positions(&[__ws_arg_22]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_position(first, &[market]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// inverse swap
//
// {
// "symbol": "SOL-USD",
// "positionId": "1813080351385337856",
// "positionSide": "LONG",
// "isolated": false,
// "positionAmt": "1",
// "availableAmt": "1",
// "unrealizedProfit": "-0.00009074",
// "initialMargin": "0.00630398",
// "liquidationPrice": 23.968303426677032,
// "avgPrice": "158.63",
// "leverage": 10,
// "markPrice": "158.402",
// "riskRate": "0.00123783",
// "maxMarginReduction": "0",
// "updateTime": 1721107015848
// }
//
// linear swap
//
// {
// "positionId": "1792480725958881280",
// "symbol": "LTC-USDT",
// "currency": "USDT",
// "positionAmt": "0.1",
// "availableAmt": "0.1",
// "positionSide": "LONG",
// "isolated": false,
// "avgPrice": "83.53",
// "initialMargin": "1.3922",
// "margin": "0.3528",
// "leverage": 6,
// "unrealizedProfit": "-1.0393",
// "realisedProfit": "-0.2119",
// "liquidationPrice": 0,
// "pnlRatio": "-0.7465",
// "maxMarginReduction": "0.0000",
// "riskRate": "0.0008",
// "markPrice": "73.14",
// "positionValue": "7.3136",
// "onlyOnePosition": true,
// "updateTime": 1721088016688
// }
//
// standard position
//
// {
// "currentPrice": "82.91",
// "symbol": "LTC/USDT",
// "initialMargin": "5.00000000000000000000",
// "unrealizedProfit": "-0.26464500",
// "leverage": "20.000000000",
// "isolated": true,
// "entryPrice": "83.13",
// "positionSide": "LONG",
// "positionAmt": "1.20365912",
// }
//
// linear swap fetchPositionHistory
//
// {
// "positionId": "1861675561156571136",
// "symbol": "LTC-USDT",
// "isolated": false,
// "positionSide": "LONG",
// "openTime": 1732693017000,
// "updateTime": 1733310292000,
// "avgPrice": "95.18",
// "avgClosePrice": "129.48",
// "realisedProfit": "102.89",
// "netProfit": "99.63",
// "positionAmt": "30.0",
// "closePositionAmt": "30.0",
// "leverage": 6,
// "closeAllPositions": true,
// "positionCommission": "-0.33699650000000003",
// "totalFunding": "-2.921461693902908"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[Value::Str("".into())]);
marketId = replace_str(&marketId, &Value::Str("/".into()), &Value::Str("-".into())); // standard return different format
let mut isolated: Value = self.safe_bool_k(position.clone(), "isolated", &[]);
let mut marginMode: Value = Value::Null;
if (isolated != Value::Null) {
marginMode = (if isolated.as_bool() == Some(true) { Value::Str("isolated".into()) } else { Value::Str("cross".into()) });
}
let mut timestamp: Value = self.safe_integer_k(position.clone(), "openTime", &[]);
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(), "positionId", &[]));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Str("-".into()), Value::Str("swap".into())]));
m.insert("notional".to_string(), self.safe_number_k(position.clone(), "positionValue", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("liquidationPrice".to_string(), self.safe_number_omit_zero(position.clone(), Value::Str("liquidationPrice".into()), &[]));
m.insert("entryPrice".to_string(), self.safe_number2(position.clone(), Value::Str("avgPrice".into()), Value::Str("entryPrice".into()), &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealizedProfit", &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realisedProfit", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "positionAmt", &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "markPrice", &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_lower_k(position.clone(), "positionSide", &[]));
m.insert("hedged".to_string(), Value::Null);
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("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.safe_number_k(position.clone(), "initialMargin", &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), self.safe_number_k(position, "leverage", &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name bingx#createMarketOrderWithCost
* @description create a spot or linear swap market order by providing the symbol, side and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} side 'buy' or 'sell'
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_order_with_cost(&mut self, mut symbol: Value, mut side: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), cost.clone()); }
return self.create_order(symbol, Value::Str("market".into()), side, cost, &[Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name bingx#createMarketBuyOrderWithCost
* @description create a spot or linear swap market buy order by providing the symbol and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), cost.clone()); }
return self.create_order(symbol, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name bingx#createMarketSellOrderWithCost
* @description create a spot or linear swap market sell order by providing the symbol and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_sell_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), cost.clone()); }
return self.create_order(symbol, Value::Str("market".into()), Value::Str("sell".into()), cost, &[Value::Null, params]).await;
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
/*
* @method
* @ignore
* @name bingx#createOrderRequest
* @description helper function to build request
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} request to be sent to the exchange
*/
let mut market: Value = self.market(symbol.clone());
let mut cost: Value = self.safe_string2(params.clone(), Value::Str("cost".into()), Value::Str("quoteOrderQty".into()), &[]);
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (cost != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() with cost or quoteOrderQty is not supported for inverse swap markets".into()))));
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("createOrder".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut typeValue: Value = to_upper(&type_var);
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("type".to_string(), typeValue.clone());
m.insert("side".to_string(), to_upper(&side));
m
});
let mut isMarketOrder: Value = Value::Bool(typeValue.as_str() == Some("MARKET"));
let mut isSpot: bool = marketType.as_str() == Some("spot");
let mut isTwapOrder: bool = typeValue.as_str() == Some("TWAP");
if isTwapOrder && isSpot {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" createOrder() twap order supports swap contracts only".into()))));
}
let mut stopLossPrice: Value = self.safe_string_k(paramsMarketType.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Value = self.safe_string_k(paramsMarketType.clone(), "takeProfitPrice", &[]);
let mut triggerPrice: Value = self.safe_string2(paramsMarketType.clone(), Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), &[]);
let mut isTriggerOrder: bool = triggerPrice != Value::Null;
let mut isStopLossPriceOrder: bool = stopLossPrice != Value::Null;
let mut isTakeProfitPriceOrder: bool = takeProfitPrice != Value::Null;
let mut exchangeClientOrderId: Value = Value::Str("clientOrderID".into());
if isSpot {
exchangeClientOrderId = Value::Str("newClientOrderId".into());
}
let mut clientOrderId: Value = self.safe_string2(paramsMarketType.clone(), exchangeClientOrderId.clone(), Value::Str("clientOrderId".into()), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&exchangeClientOrderId), clientOrderId); }
}
let mut timeInForce: Option<String> = self.safe_string_upper_k(paramsMarketType.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut postOnlyparamsPostOnlyVariable = self.handle_post_only(isMarketOrder.clone(), Value::Bool(timeInForce.as_deref() == Some("PostOnly")), &[paramsMarketType]);
let mut postOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (postOnly.as_bool() == Some(true)) || (timeInForce.as_deref() == Some("PostOnly")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), Value::Str("PostOnly".into())); }
} else if (timeInForce.as_deref() == Some("IOC")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), Value::Str("IOC".into())); }
} else if (timeInForce.as_deref() == Some("GTC")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), Value::Str("GTC".into())); }
}
let mut paramsOrder: Value = Value::Null;
if isSpot {
paramsOrder = self.omit(paramsPostOnly.clone(), Value::from(vec![Value::Str("cost".into()), Value::Str("quoteOrderQty".into())]), &[]);
if (cost != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), self.parse_to_numeric(self.cost_to_precision(symbol.clone(), cost.clone()))); }
} else {
if matches!(&isMarketOrder, Value::Bool(true)) && (price != Value::Null) {
// keep the legacy behavior, to avoid breaking the old spot-market-buying code
let mut calculatedCost: Value = crate::precise::Precise::stringMul(&self.number_to_string(amount.clone()), &self.number_to_string(price.clone()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), self.parse_to_numeric(calculatedCost)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), self.parse_to_numeric(self.amount_to_precision(symbol.clone(), amount.clone()))); }
}
}
if !(matches!(&isMarketOrder, Value::Bool(true))) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), price.clone()))); }
}
if (triggerPrice != Value::Null) {
if matches!(&isMarketOrder, Value::Bool(true)) && (side.as_str() == Some("buy")) && (self.safe_string_k(request.clone(), "quoteOrderQty", &[]) == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires the cost parameter (or the amount + price) for placing spot market-buy trigger orders".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.price_to_precision(symbol.clone(), triggerPrice.clone())); }
if (typeValue.as_str() == Some("LIMIT")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TRIGGER_LIMIT".into())); }
} else if (typeValue.as_str() == Some("MARKET")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TRIGGER_MARKET".into())); }
}
} else if (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null) {
let mut stopTakePrice: Value = takeProfitPrice.clone();
if (stopLossPrice != Value::Null) {
stopTakePrice = stopLossPrice.clone();
}
if (typeValue.as_str() == Some("LIMIT")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TAKE_STOP_LIMIT".into())); }
} else if (typeValue.as_str() == Some("MARKET")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TAKE_STOP_MARKET".into())); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), stopTakePrice))); }
}
} else {
if isTwapOrder {
let mut twapRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), match &request { Value::Dict(__m15) => __m15.get("symbol").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("side".to_string(), match &request { Value::Dict(__m15) => __m15.get("side").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("positionSide".to_string(), (if (side.as_str() == Some("buy")) { Value::Str("LONG".into()) } else { Value::Str("SHORT".into()) }));
m.insert("triggerPrice".to_string(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), triggerPrice.clone())));
m.insert("totalAmount".to_string(), self.parse_to_numeric(self.amount_to_precision(symbol.clone(), amount.clone())));
m
});
return self.extend(twapRequest, &[paramsPostOnly.clone()]);
}
if (timeInForce.as_deref() == Some("FOK")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), Value::Str("FOK".into())); }
}
let mut trailingAmount: Value = self.safe_string_k(paramsPostOnly.clone(), "trailingAmount", &[]);
let mut trailingPercent: Value = self.safe_string2(paramsPostOnly.clone(), Value::Str("trailingPercent".into()), Value::Str("priceRate".into()), &[]);
let mut trailingType: Value = self.safe_string_k(paramsPostOnly.clone(), "trailingType", &[Value::Str("TRAILING_STOP_MARKET".into())]);
let mut trailingTriggerPrice: Value = self.safe_string2(paramsPostOnly.clone(), Value::Str("trailingTriggerPrice".into()), Value::Str("activationPrice".into()), &[]);
let mut isTrailingAmountOrder: bool = trailingAmount != Value::Null;
let mut isTrailingPercentOrder: bool = trailingPercent != Value::Null;
let mut isTrailing: bool = isTrailingAmountOrder || isTrailingPercentOrder;
let mut stopLossDict: Value = self.safe_dict_k(paramsPostOnly.clone(), "stopLoss", &[]);
let mut takeProfitDict: Value = self.safe_dict_k(paramsPostOnly.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLossDict != Value::Null;
let mut hasTakeProfit: bool = takeProfitDict != Value::Null;
// only omit these keys if they are set ! https://github.com/ccxt/ccxt/pull/29185
let mut paramsStopLoss: Value = paramsPostOnly.clone();
if hasStopLoss {
paramsStopLoss = self.omit(paramsPostOnly, Value::Str("stopLoss".into()), &[]);
}
let mut paramsTakeProfit: Value = paramsStopLoss.clone();
if hasTakeProfit {
paramsTakeProfit = self.omit(paramsStopLoss, Value::Str("takeProfit".into()), &[]);
}
if ((typeValue.as_str() == Some("LIMIT")) || (typeValue.as_str() == Some("TRIGGER_LIMIT")) || (typeValue.as_str() == Some("STOP")) || (typeValue.as_str() == Some("TAKE_PROFIT"))) && !isTrailing {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), price))); }
}
let mut reduceOnly: Value = self.safe_bool_k(paramsTakeProfit.clone(), "reduceOnly", &[Value::Bool(false)]);
if isTriggerOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), triggerPrice))); }
if matches!(&isMarketOrder, Value::Bool(true)) || (typeValue.as_str() == Some("TRIGGER_MARKET")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TRIGGER_MARKET".into())); }
} else if (typeValue.as_str() == Some("LIMIT")) || (typeValue.as_str() == Some("TRIGGER_LIMIT")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TRIGGER_LIMIT".into())); }
}
} else if isStopLossPriceOrder || isTakeProfitPriceOrder {
// This can be used to set the stop loss and take profit, but the position needs to be opened first
reduceOnly = Value::Bool(true);
if isStopLossPriceOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), stopLossPrice))); }
if matches!(&isMarketOrder, Value::Bool(true)) || (typeValue.as_str() == Some("STOP_MARKET")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("STOP_MARKET".into())); }
} else if (typeValue.as_str() == Some("LIMIT")) || (typeValue.as_str() == Some("STOP")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("STOP".into())); }
}
} else if isTakeProfitPriceOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopPrice".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), takeProfitPrice))); }
if matches!(&isMarketOrder, Value::Bool(true)) || (typeValue.as_str() == Some("TAKE_PROFIT_MARKET")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TAKE_PROFIT_MARKET".into())); }
} else if (typeValue.as_str() == Some("LIMIT")) || (typeValue.as_str() == Some("TAKE_PROFIT")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("TAKE_PROFIT".into())); }
}
}
} else if isTrailing {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), trailingType); }
if isTrailingAmountOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.parse_to_numeric(trailingAmount)); }
} else if isTrailingPercentOrder {
let mut requestTrailingPercent: Value = crate::precise::Precise::stringDiv(&trailingPercent, &Value::Str("100".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("priceRate".into(), self.parse_to_numeric(requestTrailingPercent)); }
}
if (trailingTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("activationPrice".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), trailingTriggerPrice))); }
}
}
if hasStopLoss || hasTakeProfit {
if (cost != Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support attached stopLoss or takeProfit on a market order by cost".into()))));
}
let mut stringifiedAmount: Value = self.number_to_string(amount.clone());
if hasStopLoss {
let mut slTriggerPrice: Value = self.safe_string2(stopLossDict.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut slWorkingType: Value = self.safe_string_k(stopLossDict.clone(), "workingType", &[Value::Str("MARK_PRICE".into())]);
let mut slType: Value = self.safe_string_k(stopLossDict.clone(), "type", &[Value::Str("STOP_MARKET".into())]);
let mut slRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopPrice".to_string(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), slTriggerPrice)));
m.insert("workingType".to_string(), slWorkingType);
m.insert("type".to_string(), slType);
m
});
let mut slPrice: Value = self.safe_string_k(stopLossDict.clone(), "price", &[]);
if (slPrice != Value::Null) {
if let Value::Dict(__d) = &mut slRequest { std::sync::Arc::make_mut(__d).insert("price".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), slPrice.clone()))); }
}
let mut slQuantity: Value = self.safe_string_k(stopLossDict, "quantity", &[stringifiedAmount.clone()]);
let mut slQuantityRequest: Value = self.parse_to_numeric(slQuantity.clone());
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
slQuantityRequest = self.parse_to_numeric(self.amount_to_precision(symbol.clone(), slQuantity));
}
if let Value::Dict(__d) = &mut slRequest { std::sync::Arc::make_mut(__d).insert("quantity".into(), slQuantityRequest); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopLoss".into(), json_stringify(&slRequest)); }
}
if hasTakeProfit {
let mut tkTriggerPrice: Value = self.safe_string2(takeProfitDict.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut tkWorkingType: Value = self.safe_string_k(takeProfitDict.clone(), "workingType", &[Value::Str("MARK_PRICE".into())]);
let mut tpType: Value = self.safe_string_k(takeProfitDict.clone(), "type", &[Value::Str("TAKE_PROFIT_MARKET".into())]);
let mut tpRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopPrice".to_string(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), tkTriggerPrice)));
m.insert("workingType".to_string(), tkWorkingType);
m.insert("type".to_string(), tpType);
m
});
let mut slPrice: Value = self.safe_string_k(takeProfitDict.clone(), "price", &[]);
if (slPrice != Value::Null) {
if let Value::Dict(__d) = &mut tpRequest { std::sync::Arc::make_mut(__d).insert("price".into(), self.parse_to_numeric(self.price_to_precision(symbol.clone(), slPrice))); }
}
let mut tkQuantity: Value = self.safe_string_k(takeProfitDict, "quantity", &[stringifiedAmount]);
let mut tkQuantityRequest: Value = self.parse_to_numeric(tkQuantity.clone());
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
tkQuantityRequest = self.parse_to_numeric(self.amount_to_precision(symbol.clone(), tkQuantity));
}
if let Value::Dict(__d) = &mut tpRequest { std::sync::Arc::make_mut(__d).insert("quantity".into(), tkQuantityRequest); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("takeProfit".into(), json_stringify(&tpRequest)); }
}
}
let mut positionSide: Value = Value::Null;
let mut hedged: Value = self.safe_bool_k(paramsTakeProfit.clone(), "hedged", &[Value::Bool(false)]);
paramsOrder = (if (hedged.as_bool() == Some(true)) { self.omit(paramsTakeProfit.clone(), Value::Str("reduceOnly".into()), &[]) } else { paramsTakeProfit });
if (hedged.as_bool() == Some(true)) {
if (reduceOnly.as_bool() == Some(true)) {
positionSide = (if (side.as_str() == Some("buy")) { Value::Str("SHORT".into()) } else { Value::Str("LONG".into()) });
} else {
positionSide = (if (side.as_str() == Some("buy")) { Value::Str("LONG".into()) } else { Value::Str("SHORT".into()) });
}
} else {
positionSide = Value::Str("BOTH".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("positionSide".into(), positionSide); }
let mut closePosition: Value = self.safe_bool_k(paramsOrder.clone(), "closePosition", &[Value::Bool(false)]);
if (cost != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quoteOrderQty".into(), self.parse_to_numeric(self.cost_to_precision(symbol.clone(), cost))); }
} else if (closePosition.as_bool() != Some(true)) {
let mut amountReq: Value = amount.clone();
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
amountReq = self.parse_to_numeric(self.amount_to_precision(symbol, amount));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), amountReq); }; // precision not available for inverse contracts
}
}
let mut paramsRequest: Value = self.omit(paramsOrder, Value::from(vec![Value::Str("hedged".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("trailingAmount".into()), Value::Str("trailingPercent".into()), Value::Str("trailingType".into()), Value::Str("trailingTriggerPrice".into()), Value::Str("activationPrice".into()), Value::Str("clientOrderId".into()), Value::Str("cost".into()), Value::Str("quoteOrderQty".into())]), &[]);
return self.extend(request, &[paramsRequest]);
Value::Null
}
/*
* @method
* @name bingx#createOrder
* @description create a trade order
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Place%20order
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Place%20order
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Place%20TWAP%20Order
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Trade%20order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique id for the order
* @param {bool} [params.postOnly] true to place a post only order
* @param {string} [params.timeInForce] spot supports 'PO', 'GTC' and 'IOC', swap supports 'PO', 'GTC', 'IOC' and 'FOK'
* @param {bool} [params.reduceOnly] *swap only* true or false whether the order is reduce only
* @param {float} [params.triggerPrice] triggerPrice at which the attached take profit / stop loss order will be triggered
* @param {float} [params.stopLossPrice] stop loss trigger price, a spot order is placed as TAKE_STOP and parsed back with triggerPrice
* @param {float} [params.takeProfitPrice] take profit trigger price, a spot order is placed as TAKE_STOP and parsed back with triggerPrice
* @param {float} [params.cost] *spot and linear swap only* the quote quantity that can be used as an alternative for the amount
* @param {float} [params.quoteOrderQty] *spot and linear swap only* the quote quantity, an alternative to params.cost
* @param {float} [params.trailingAmount] *swap only* the quote amount to trail away from the current market price
* @param {float} [params.trailingPercent] *swap only* the percent to trail away from the current market price
* @param {float} [params.trailingTriggerPrice] *swap only* the price to activate a trailing order at
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {boolean} [params.test] *linear swap only* whether to use the test endpoint or not, default is false
* @param {string} [params.positionSide] *contracts only* "BOTH" for one way mode, "LONG" for buy side of hedged mode, "SHORT" for sell side of hedged mode
* @param {boolean} [params.hedged] *swap only* whether the order is in hedged mode or one way mode
* @param {bool} [params.closePosition] *swap only* true to close the entire position with a TP/SL order, in which case the quantity is not sent
* @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 test: Value = self.safe_bool_k(params.clone(), "test", &[Value::Bool(false)]);
if test.as_bool() == Some(true) && ((market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) || (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() only supports test orders for linear swap markets".into()))));
}
let mut paramsOmitted: Value = self.omit(params, Value::Str("test".into()), &[]);
let mut request: Value = self.create_order_request(symbol, type_var.clone(), side, amount, &[price, paramsOmitted]);
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (test.as_bool() == Some(true)) {
response = self.swap_v2_private_post_trade_order_test(&[request.clone()]).await;
} else if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
response = self.cswap_v1_private_post_trade_order(&[request.clone()]).await;
} else if (type_var.as_str() == Some("twap")) {
response = self.swap_v1_private_post_twap_order(&[request.clone()]).await;
} else {
response = self.swap_v2_private_post_trade_order(&[request.clone()]).await;
}
} else {
response = self.spot_v1_private_post_trade_order(&[request]).await;
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "transactTime": 1649822362855,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "BTC-USDT",
// "orderId": 1709036527545438208,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_LIMIT",
// "clientOrderID": "",
// "workingType": ""
// }
// }
// }
//
// inverse swap
//
// {
// "orderId": 1809841379603398656,
// "symbol": "SOL-USD",
// "positionSide": "LONG",
// "side": "BUY",
// "type": "LIMIT",
// "price": 100,
// "quantity": 1,
// "stopPrice": 0,
// "workingType": "",
// "timeInForce": ""
// }
//
// twap order
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1732693774386,
// "data": {
// "mainOrderId": "4633860139993029715"
// }
// }
//
if matches!(&response, Value::Str(_)) {
// broken api engine : order-ids are too long numbers (i.e. 1742930526912864656)
// and JSON.parse can not handle them in JS, so we have to use .parseJson
// however, when order has an attached SL/TP, their value types need extra parsing
response = self.fix_stringified_json_members(response.clone());
let mut parsedResponse: Value = self.parse_json_value(response.clone());
response = parsedResponse;
}
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
result = response;
} else {
result = self.safe_dict_k(data.clone(), "order", &[data.clone()]);
}
} else {
result = data;
}
// when the response arrives as an already-parsed dict, the attached SL/TP members are still stringified json
let mut stopLossDict: Value = self.safe_dict_k(result.clone(), "stopLoss", &[]);
let mut stopLoss: Value = self.safe_string_k(result.clone(), "stopLoss", &[]);
// for py fix, the SL is already parsed as object (instead of stringified, as it's provided)
// so we need trick to check if it's non-parsed string yet
if (stopLossDict == Value::Null) && (stopLoss != Value::Null) && (Value::Int(stopLoss.as_str().and_then(|__s| __s.find("{")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("stopLoss".into(), self.parse_json_value(stopLoss)); }
}
let mut takeProfit: Value = self.safe_string_k(result.clone(), "takeProfit", &[]);
if (takeProfit != Value::Null) && (Value::Int(takeProfit.as_str().and_then(|__s| __s.find("{")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("takeProfit".into(), self.parse_json_value(takeProfit)); }
}
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name bingx#createOrders
* @description create a list of trade orders
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Place%20multiple%20orders
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Place%20multiple%20orders
* @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, linear swap and spot only
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.sync] *spot only* if true, multiple orders are ordered serially and all orders do not require the same symbol/side/type
* @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
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
let mut marketIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_298: bool = true;
while { if !__for_first_298 { 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_298 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[Value::Str("".into())]);
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[]);
append_to_array(&mut marketIds, marketId.clone());
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(marketId, type_var, side, amount, &[price, orderParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut symbols: Value = self.market_symbols(&[marketIds, Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrders() is not supported for inverse swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if symbolsLength > ((5i64) as f64) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrders() can not create more than 5 orders at once for swap markets".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("batchOrders".into(), json_stringify(&ordersRequests)); }
response = self.swap_v2_private_post_trade_batch_orders(&[request.clone()]).await;
} else {
let mut sync: Value = (match params.get("sync") { Some(Value::Bool(__b)) => Value::Bool(*__b), _ => Value::Bool(false) });
if (sync.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("sync".into(), Value::Bool(true)); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("data".into(), json_stringify(&ordersRequests)); }
response = self.spot_v1_private_post_trade_batch_orders(&[request]).await;
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "orders": [
// {
// "symbol": "BTC-USDT",
// "orderId": 1720661389564968960,
// "transactTime": 1699072618272,
// "price": "25000",
// "origQty": "0.0002",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// },
// ]
// }
// }
//
// swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "BTC-USDT",
// "orderId": 1720657081994006528,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT",
// "clientOrderID": "",
// "workingType": ""
// },
// ]
// }
// }
//
if matches!(&response, Value::Str(_)) {
// broken api engine : order-ids are too long numbers (i.e. 1742930526912864656)
// and JSON.parse can not handle them in JS, so we have to use .parseJson
// however, when order has an attached SL/TP, their value types need extra parsing
response = self.fix_stringified_json_members(response.clone());
let mut parsedResponse: Value = self.parse_json_value(response.clone());
response = parsedResponse;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
return self.parse_orders(result, &[market]);
Value::Null
}
pub fn parse_order_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("buy".into()));
m.insert("SELL".to_string(), Value::Str("sell".into()));
m.insert("SHORT".to_string(), Value::Str("sell".into()));
m.insert("LONG".to_string(), Value::Str("buy".into()));
m.insert("ask".to_string(), Value::Str("sell".into()));
m.insert("bid".to_string(), Value::Str("buy".into()));
m
});
return self.safe_string(sides, side.clone(), &[side.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trigger_market".to_string(), Value::Str("market".into()));
m.insert("trigger_limit".to_string(), Value::Str("limit".into()));
m.insert("stop_limit".to_string(), Value::Str("limit".into()));
m.insert("stop_market".to_string(), Value::Str("market".into()));
m.insert("take_profit_market".to_string(), Value::Str("market".into()));
m.insert("take_profit".to_string(), Value::Str("limit".into()));
m.insert("stop".to_string(), Value::Str("limit".into()));
m.insert("take_stop_limit".to_string(), Value::Str("limit".into()));
m.insert("take_stop_market".to_string(), Value::Str("market".into()));
m.insert("trailing_stop_market".to_string(), Value::Str("market".into()));
m.insert("trailing_tp_sl".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot
// createOrder, createOrders, cancelOrder
//
// {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "transactTime": 1649822362855,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// }
//
// fetchOrder
//
// {
// "symbol": "ETH-USDT",
// "orderId": "1660602123001266176",
// "price": "1700",
// "origQty": "0.003",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": "1684753373276",
// "updateTime": "1684753373276",
// "origQuoteOrderQty": "0",
// "fee": "0",
// "feeAsset": "ETH"
// }
//
// fetchOpenOrders, fetchClosedOrders
//
// {
// "symbol": "XRP-USDT",
// "orderId": 1514073325788200960,
// "price": "0.5",
// "StopPrice": "0",
// "origQty": "20",
// "executedQty": "10",
// "cummulativeQuoteQty": "5",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1649818185647,
// "updateTime": 1649818185647,
// "origQuoteOrderQty": "0"
// "fee": "-0.01"
// }
//
//
// linear swap
// createOrder, createOrders
//
// {
// "symbol": "BTC-USDT",
// "orderId": 1590973236294713344,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT"
// }
//
// inverse swap createOrder
//
// {
// "orderId": 1809841379603398656,
// "symbol": "SOL-USD",
// "positionSide": "LONG",
// "side": "BUY",
// "type": "LIMIT",
// "price": 100,
// "quantity": 1,
// "stopPrice": 0,
// "workingType": "",
// "timeInForce": ""
// }
//
// fetchOrder, fetchOpenOrders, fetchClosedOrders
//
// {
// "symbol": "BTC-USDT",
// "orderId": 1709036527545438208,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_LIMIT",
// "origQty": "0.0010",
// "price": "22000.0",
// "executedQty": "0.0000",
// "avgPrice": "0.0",
// "cumQuote": "",
// "stopPrice": "23000.0",
// "profit": "",
// "commission": "",
// "status": "NEW",
// "time": 1696301035187,
// "updateTime": 1696301035187,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": "",
// "stopLoss": "",
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE"
// }
// with tp and sl
// {
// orderId: 1741440894764281900,
// symbol: 'LTC-USDT',
// positionSide: 'LONG',
// side: 'BUY',
// type: 'MARKET',
// price: 0,
// quantity: 1,
// stopPrice: 0,
// workingType: 'MARK_PRICE',
// clientOrderID: '',
// timeInForce: 'GTC',
// priceRate: 0,
// stopLoss: '{"stopPrice":50,"workingType":"MARK_PRICE","type":"STOP_MARKET","quantity":1}',
// takeProfit: '{"stopPrice":150,"workingType":"MARK_PRICE","type":"TAKE_PROFIT_MARKET","quantity":1}',
// reduceOnly: false
// }
//
// editOrder (swap)
//
// {
// cancelResult: 'true',
// cancelMsg: '',
// cancelResponse: {
// cancelClientOrderId: '',
// cancelOrderId: '1755336244265705472',
// symbol: 'SOL-USDT',
// orderId: '1755336244265705472',
// side: 'SELL',
// positionSide: 'SHORT',
// type: 'LIMIT',
// origQty: '1',
// price: '100.000',
// executedQty: '0',
// avgPrice: '0.000',
// cumQuote: '0',
// stopPrice: '',
// profit: '0.0000',
// commission: '0.000000',
// status: 'PENDING',
// time: '1707339747860',
// updateTime: '1707339747860',
// clientOrderId: '',
// leverage: '20X',
// workingType: 'MARK_PRICE',
// onlyOnePosition: false,
// reduceOnly: false
// },
// replaceResult: 'true',
// replaceMsg: '',
// newOrderResponse: {
// orderId: '1755338440612995072',
// symbol: 'SOL-USDT',
// positionSide: 'SHORT',
// side: 'SELL',
// type: 'LIMIT',
// price: '99',
// quantity: '2',
// stopPrice: '0',
// workingType: 'MARK_PRICE',
// clientOrderID: '',
// timeInForce: 'GTC',
// priceRate: '0',
// stopLoss: '',
// takeProfit: '',
// reduceOnly: false
// }
// }
//
// editOrder (spot)
//
// {
// cancelResult: { code: '0', msg: '', result: true },
// openResult: { code: '0', msg: '', result: true },
// orderOpenResponse: {
// symbol: 'SOL-USDT',
// orderId: '1755334007697866752',
// transactTime: '1707339214620',
// price: '99',
// stopPrice: '0',
// origQty: '0.2',
// executedQty: '0',
// cummulativeQuoteQty: '0',
// status: 'PENDING',
// type: 'LIMIT',
// side: 'SELL',
// clientOrderID: ''
// },
// orderCancelResponse: {
// symbol: 'SOL-USDT',
// orderId: '1755117055251480576',
// price: '100',
// stopPrice: '0',
// origQty: '0.2',
// executedQty: '0',
// cummulativeQuoteQty: '0',
// status: 'CANCELED',
// type: 'LIMIT',
// side: 'SELL'
// }
// }
//
// stop loss order
//
// {
// "symbol": "ETH-USDT",
// "orderId": "1792461744476422144",
// "price": "2775.65",
// "StopPrice": "2778.42",
// "origQty": "0.032359",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "NEW",
// "type": "TAKE_STOP_LIMIT",
// "side": "SELL",
// "time": "1716191156868",
// "updateTime": "1716191156868",
// "origQuoteOrderQty": "0",
// "fee": "0",
// "feeAsset": "USDT",
// "clientOrderID": ""
// }
//
// inverse swap cancelAllOrders, cancelOrder, fetchOrder, fetchOpenOrders, fetchClosedOrders, fetchCanceledOrders
//
// {
// "symbol": "SOL-USD",
// "orderId": "1809845251327672320",
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT",
// "quantity": 1,
// "origQty": "0",
// "price": "90",
// "executedQty": "0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1720335707872,
// "updateTime": 1720335707912,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": ""
// }
//
let mut info: Value = order.clone();
let mut newOrder: Value = self.safe_dict2(order.clone(), Value::Str("newOrderResponse".into()), Value::Str("orderOpenResponse".into()), &[]);
let mut orderData: Value = (if (newOrder != Value::Null) { newOrder } else { order });
let mut positionSide: Option<String> = self.safe_string2(orderData.clone(), Value::Str("positionSide".into()), Value::Str("ps".into()), &[]).as_str().map(str::to_owned);
let mut marketType: Value = Value::Str("swap".into());
if (positionSide.is_none()) {
marketType = Value::Str("spot".into());
}
let mut marketId: Value = self.safe_string2(orderData.clone(), Value::Str("symbol".into()), Value::Str("s".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[(if (market == Value::Null) { marketId.clone() } else { Value::Null }), market, Value::Null, marketType.clone()]);
let mut side: Value = self.safe_string_lower2(orderData.clone(), Value::Str("side".into()), Value::Str("S".into()), &[]);
let mut timestamp: Value = self.safe_integer_n(orderData.clone(), Value::from(vec![Value::Str("time".into()), Value::Str("transactTime".into()), Value::Str("E".into()), Value::Str("createdTime".into())]), &[]);
let mut transactTime: Value = self.safe_string_k(orderData.clone(), "transactTime", &[Value::Str("".into())]);
if (Value::Int(transactTime.len() as i64).as_f64() == Some(10.0)) {
// spot conditional orders are created with transactTime in seconds
timestamp = self.safe_timestamp_k(orderData.clone(), "transactTime", &[]);
}
let mut lastTradeTimestamp: Value = self.safe_integer2(orderData.clone(), Value::Str("updateTime".into()), Value::Str("T".into()), &[]);
let mut statusId: Value = self.safe_string_upper_n(orderData.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("X".into()), Value::Str("orderStatus".into())]), &[]);
let mut feeCurrencyCode: Value = self.safe_string2(orderData.clone(), Value::Str("feeAsset".into()), Value::Str("N".into()), &[]);
let mut feeCost: Value = self.safe_string_n(orderData.clone(), Value::from(vec![Value::Str("fee".into()), Value::Str("commission".into()), Value::Str("n".into())]), &[]);
if (feeCurrencyCode == Value::Null) {
if (marketResolved.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (side.as_str() == Some("buy")) {
feeCurrencyCode = marketResolved.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null);
} else {
feeCurrencyCode = marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null);
}
} else {
feeCurrencyCode = (if (marketResolved.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { marketResolved.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null) } else { marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null) });
}
}
let mut stopLoss: Value = self.safe_value_k(orderData.clone(), "stopLoss", &[]);
let mut stopLossPrice: Value = Value::Null;
if (stopLoss != Value::Null) && (stopLoss.as_str() != Some("")) {
stopLossPrice = self.omit_zero(self.safe_string_k(stopLoss.clone(), "stopLoss", &[]));
}
if (stopLoss != Value::Null) && (!matches!(&stopLoss, Value::Int(_) | Value::Float(_))) && (stopLoss.as_str() != Some("")) {
// stopLoss: '{"stopPrice":50,"workingType":"MARK_PRICE","type":"STOP_MARKET","quantity":1}',
if matches!(&stopLoss, Value::Str(_)) {
stopLoss = self.parse_json_value(stopLoss.clone());
}
stopLossPrice = self.omit_zero(self.safe_string_k(stopLoss.clone(), "stopPrice", &[]));
}
let mut takeProfit: Value = self.safe_value_k(orderData.clone(), "takeProfit", &[]);
let mut takeProfitPrice: Value = Value::Null;
if (takeProfit != Value::Null) && (takeProfit.as_str() != Some("")) {
takeProfitPrice = self.omit_zero(self.safe_string_k(takeProfit.clone(), "takeProfit", &[]));
}
if (takeProfit != Value::Null) && (!matches!(&takeProfit, Value::Int(_) | Value::Float(_))) && (takeProfit.as_str() != Some("")) {
// takeProfit: '{"stopPrice":150,"workingType":"MARK_PRICE","type":"TAKE_PROFIT_MARKET","quantity":1}',
if matches!(&takeProfit, Value::Str(_)) {
takeProfit = self.parse_json_value(takeProfit.clone());
}
takeProfitPrice = self.omit_zero(self.safe_string_k(takeProfit.clone(), "stopPrice", &[]));
}
let mut rawType: Value = self.safe_string_lower2(orderData.clone(), Value::Str("type".into()), Value::Str("o".into()), &[]);
let mut stopPrice: Value = self.omit_zero(self.safe_string2(orderData.clone(), Value::Str("StopPrice".into()), Value::Str("stopPrice".into()), &[]));
let mut triggerPrice: Value = stopPrice.clone();
// spot TAKE_STOP_* is a plain conditional order, the venue does not say whether it protects a position
let mut isTakeStop: bool = (rawType != Value::Null) && (Value::Int(rawType.as_str().and_then(|__s| __s.find("take_stop")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64));
if (stopPrice != Value::Null) && !isTakeStop {
if (Value::Int(rawType.as_str().and_then(|__s| __s.find("stop")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64)) && (stopLossPrice == Value::Null) {
stopLossPrice = stopPrice.clone();
triggerPrice = Value::Null;
}
if (Value::Int(rawType.as_str().and_then(|__s| __s.find("take")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64)) && (takeProfitPrice == Value::Null) {
takeProfitPrice = stopPrice;
triggerPrice = Value::Null;
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info);
m.insert("id".to_string(), self.safe_string_n(orderData.clone(), Value::from(vec![Value::Str("orderId".into()), Value::Str("i".into()), Value::Str("mainOrderId".into())]), &[]));
m.insert("clientOrderId".to_string(), self.safe_string_n(orderData.clone(), Value::from(vec![Value::Str("clientOrderID".into()), Value::Str("clientOrderId".into()), Value::Str("origClientOrderId".into()), Value::Str("c".into())]), &[]));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[marketResolved.clone(), Value::Str("-".into()), marketType]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(orderData.clone(), "updateTime", &[]));
m.insert("type".to_string(), self.parse_order_type(rawType));
m.insert("timeInForce".to_string(), self.safe_string_k(orderData.clone(), "timeInForce", &[]));
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.parse_order_side(side).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("price".to_string(), self.safe_string2(orderData.clone(), Value::Str("price".into()), Value::Str("p".into()), &[]));
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("average".to_string(), self.safe_string2(orderData.clone(), Value::Str("avgPrice".into()), Value::Str("ap".into()), &[]));
m.insert("cost".to_string(), self.safe_string2(orderData.clone(), Value::Str("cummulativeQuoteQty".into()), Value::Str("Z".into()), &[]));
m.insert("amount".to_string(), self.safe_string_n(orderData.clone(), Value::from(vec![Value::Str("origQty".into()), Value::Str("q".into()), Value::Str("quantity".into()), Value::Str("totalAmount".into())]), &[]));
m.insert("filled".to_string(), self.safe_string2(orderData.clone(), Value::Str("executedQty".into()), Value::Str("z".into()), &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_order_status(statusId));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), feeCurrencyCode);
m.insert("cost".to_string(), crate::precise::Precise::stringAbs(&feeCost));
m
}));
m.insert("trades".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), self.safe_bool2(orderData, Value::Str("reduceOnly".into()), Value::Str("ro".into()), &[]));
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("NEW".to_string(), Value::Str("open".into()));
m.insert("PENDING".to_string(), Value::Str("open".into()));
m.insert("PARTIALLY_FILLED".to_string(), Value::Str("open".into()));
m.insert("RUNNING".to_string(), Value::Str("open".into()));
m.insert("FILLED".to_string(), Value::Str("closed".into()));
m.insert("CANCELED".to_string(), Value::Str("canceled".into()));
m.insert("CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("FAILED".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
/*
* @method
* @name bingx#cancelOrder
* @description cancels an open order
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Cancel%20Order
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20Order
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20TWAP%20Order
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Cancel%20an%20Order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique id for the order
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut isTwapOrder: Value = self.safe_bool_k(params.clone(), "twap", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("twap".into()), &[]);
let mut response: Value = Value::Null;
let mut market: Value = Value::Null;
if (isTwapOrder.as_bool() == Some(true)) {
let mut twapRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mainOrderId".to_string(), id.clone());
m
});
let __ws_arg_23 = self.extend(twapRequest, &[paramsOmitted.clone()]);
response = self.swap_v1_private_post_twap_cancel_order(&[__ws_arg_23]).await;
} else {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
market = 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: Value = self.safe_string2(paramsOmitted.clone(), Value::Str("clientOrderId".into()), Value::Str("clientOrderID".into()), &[]);
let mut paramsOmitted2: Value = self.omit(paramsOmitted, Value::from(vec![Value::Str("clientOrderId".into())]), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientOrderID".into(), clientOrderId); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), id); }
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("cancelOrder".into()), &[market.clone(), paramsOmitted2]);
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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("cancelOrder".into()), &[market.clone(), paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() == Some("spot")) {
let __ws_arg_24 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.spot_v1_private_post_trade_cancel(&[__ws_arg_24]).await;
} else {
if (subType.as_str() == Some("inverse")) {
let __ws_arg_25 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_delete_trade_cancel_order(&[__ws_arg_25]).await;
} else {
let __ws_arg_26 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_delete_trade_order(&[__ws_arg_26]).await;
}
}
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "CANCELED",
// "type": "LIMIT",
// "side": "BUY"
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "SOL-USD",
// "orderId": "1816002957423951872",
// "side": "BUY",
// "positionSide": "Long",
// "type": "Pending",
// "quantity": 0,
// "origQty": "0",
// "price": "150",
// "executedQty": "0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1721803819410,
// "updateTime": 1721803819427,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": ""
// }
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "LINK-USDT",
// "orderId": 1597783850786750464,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_MARKET",
// "origQty": "5.0",
// "price": "5.0000",
// "executedQty": "0.0",
// "avgPrice": "0.0000",
// "cumQuote": "0",
// "stopPrice": "5.0000",
// "profit": "",
// "commission": "",
// "status": "CANCELLED",
// "time": 1669776330000,
// "updateTime": 1669776330000
// }
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_dict_k(data.clone(), "order", &[data.clone()]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name bingx#cancelAllOrders
* @description cancel all open orders
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Cancel%20all%20Open%20Orders%20on%20a%20Symbol
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20All%20Open%20Orders
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Cancel%20all%20orders
* @param {string} [symbol] unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap' (default is 'spot' if symbol is not provided)
* @param {string} [params.subType] 'linear' or 'inverse' for swap markets (default is 'linear' if symbol is not provided)
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
market = self.market(symbol);
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 marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("cancelAllOrders".into()), &[market.clone(), params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("cancelAllOrders".into()), &[market, paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
let __ws_arg_27 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.spot_v1_private_post_trade_cancel_open_orders(&[__ws_arg_27]).await;
} else if (marketType.as_str() == Some("swap")) {
if (subType.as_str() == Some("inverse")) {
let __ws_arg_28 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_delete_trade_all_open_orders(&[__ws_arg_28]).await;
} else {
let __ws_arg_29 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_delete_trade_all_open_orders(&[__ws_arg_29]).await;
}
} else {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrders is only supported for spot and swap markets.".into()))));
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list2(data, Value::Str("success".into()), Value::Str("orders".into()), &[Value::from(vec![])]);
return self.parse_orders(orders, &[]);
Value::Null
}
/*
* @method
* @name bingx#cancelOrders
* @description cancel multiple orders
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Cancel%20multiple%20orders
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20multiple%20orders
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol, inverse (Coin-M) markets are not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string[]} [params.clientOrderIds] client order ids
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() is not supported for inverse swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut clientOrderIds: Value = self.safe_list_k(params.clone(), "clientOrderIds", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("clientOrderIds".into()), &[]);
let mut idsToParse: Value = ids;
let mut areClientOrderIds: bool = clientOrderIds != Value::Null;
if areClientOrderIds {
idsToParse = clientOrderIds;
}
let mut parsedIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_299: bool = true;
while { if !__for_first_299 { 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_299 = false; i.as_f64().unwrap_or(f64::NAN) < ((idsToParse.len() as i64) as f64) } {
let mut id: Value = idsToParse.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut stringId: Value = to_string_val(&id);
append_to_array(&mut parsedIds, stringId);
}
}
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut spotReqKey: Value = Value::Str("orderIds".into());
if areClientOrderIds {
spotReqKey = Value::Str("clientOrderIDs".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&spotReqKey), join(&parsedIds, &Value::Str(",".into()))); }
let __ws_arg_30 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.spot_v1_private_post_trade_cancel_orders(&[__ws_arg_30]).await;
} else {
if areClientOrderIds {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientOrderIDList".into(), json_stringify(&parsedIds)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderIdList".into(), parsedIds); }
}
let __ws_arg_31 = self.extend(request, &[paramsOmitted]);
response = self.swap_v2_private_delete_trade_batch_orders(&[__ws_arg_31]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut success: Value = self.safe_list2(data, Value::Str("success".into()), Value::Str("orders".into()), &[Value::from(vec![])]);
return self.parse_orders(success, &[]);
Value::Null
}
/*
* @method
* @name bingx#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Cancel%20All%20After
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20All%20After
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] spot or swap market
* @param {string} [params.subType] 'linear' or 'inverse' (default is 'linear'), 'inverse' is not supported
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: 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 isActive: bool = timeout.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), (if (isActive) { Value::Str("ACTIVATE".into()) } else { Value::Str("CLOSE".into()) }));
m.insert("timeOut".to_string(), (if (isActive) { (self.parse_to_int((match ((timeout).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))) } else { Value::Int(0) }));
m
});
let mut response: Value = Value::Null;
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("cancelAllOrdersAfter".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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("cancelAllOrdersAfter".into()), &[Value::Null, paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() == Some("swap")) && (subType.as_str() == Some("inverse")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() is not supported for inverse swap markets".into()))));
}
if (type_var.as_str() == Some("spot")) {
let __ws_arg_32 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.spot_v1_private_post_trade_cancel_all_after(&[__ws_arg_32]).await;
} else if (type_var.as_str() == Some("swap")) {
let __ws_arg_33 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_post_trade_cancel_all_after(&[__ws_arg_33]).await;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() is not supported for ".into())).into()), type_var).into()), Value::Str(" markets".into()))));
}
return response;
Value::Null
}
/*
* @method
* @name bingx#fetchOrder
* @description fetches information on an order made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20Order%20details
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Order%20details
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/TWAP%20Order%20Details
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Order
* @param {string} id the order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.twap] if fetching twap order
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut isTwapOrder: Value = self.safe_bool_k(params.clone(), "twap", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("twap".into()), &[]);
let mut response: Value = Value::Null;
let mut market: Value = Value::Null;
if (isTwapOrder.as_bool() == Some(true)) {
let mut twapRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mainOrderId".to_string(), id.clone());
m
});
let __ws_arg_34 = self.extend(twapRequest, &[paramsOmitted.clone()]);
response = self.swap_v1_private_get_twap_order_detail(&[__ws_arg_34]).await;
} else {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires a symbol argument".into()))));
}
market = 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.insert("orderId".to_string(), id);
m
});
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOrder".into()), &[market.clone(), paramsOmitted]);
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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchOrder".into()), &[market.clone(), paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() == Some("spot")) {
let __ws_arg_35 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.spot_v1_private_get_trade_query(&[__ws_arg_35]).await;
} else {
if (subType.as_str() == Some("inverse")) {
let __ws_arg_36 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_get_trade_order_detail(&[__ws_arg_36]).await;
} else {
let __ws_arg_37 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_get_trade_order(&[__ws_arg_37]).await;
}
}
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.safe_dict_k(data.clone(), "order", &[data.clone()]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/All%20Orders
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Order%20history (returns less fields than above)
* @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 {int} [params.until] the latest time in ms to fetch entries for
* @param {int} [params.orderId] Only return subsequent orders, and return the latest order by default
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOrders".into()), &[market.clone(), 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);
if (type_var.as_str() != Some("swap")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders() is only supported for swap markets".into()))));
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, paramsMarketType, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_38 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.swap_v1_private_get_trade_full_order(&[__ws_arg_38]).await;
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "PYTH-USDT",
// "orderId": 1736007506620112100,
// "side": "SELL",
// "positionSide": "SHORT",
// "type": "LIMIT",
// "origQty": "33",
// "price": "0.3916",
// "executedQty": "33",
// "avgPrice": "0.3916",
// "cumQuote": "13",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "-0.002585",
// "status": "FILLED",
// "time": 1702731418000,
// "updateTime": 1702731470000,
// "clientOrderId": "",
// "leverage": "15X",
// "takeProfit": {
// "type": "TAKE_PROFIT",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": ""
// },
// "stopLoss": {
// "type": "STOP",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE",
// "stopGuaranteed": false,
// "triggerOrderId": 1736012449498123500
// }
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name bingx#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Current%20Open%20Orders
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Current%20All%20Open%20Orders
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20all%20current%20pending%20orders
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20TWAP%20Entrusted%20Order
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.twap] if fetching twap open orders
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
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 response: Value = Value::Null;
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOpenOrders".into()), &[market.clone(), 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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchOpenOrders".into()), &[market.clone(), paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() == Some("spot")) {
let __ws_arg_39 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.spot_v1_private_get_trade_open_orders(&[__ws_arg_39]).await;
} else {
let mut isTwapOrder: Value = self.safe_bool_k(paramsSubType.clone(), "twap", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(paramsSubType, Value::Str("twap".into()), &[]);
if (isTwapOrder.as_bool() == Some(true)) {
let __ws_arg_40 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.swap_v1_private_get_twap_open_orders(&[__ws_arg_40]).await;
} else if (subType.as_str() == Some("inverse")) {
let __ws_arg_41 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.cswap_v1_private_get_trade_open_orders(&[__ws_arg_41]).await;
} else {
let __ws_arg_42 = self.extend(request, &[paramsOmitted]);
response = self.swap_v2_private_get_trade_open_orders(&[__ws_arg_42]).await;
}
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "XRP-USDT",
// "orderId": 1514073325788200960,
// "price": "0.5",
// "origQty": "20",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1649818185647,
// "updateTime": 1649818185647,
// "origQuoteOrderQty": "0"
// }
// ]
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "SOL-USD",
// "orderId": "1816013900044320768",
// "side": "BUY",
// "positionSide": "Long",
// "type": "LIMIT",
// "quantity": 1,
// "origQty": "",
// "price": "150",
// "executedQty": "0",
// "avgPrice": "0.000",
// "cumQuote": "",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.0000",
// "status": "Pending",
// "time": 1721806428334,
// "updateTime": 1721806428352,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "TAKE_PROFIT",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "MARK_PRICE",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "STOP",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "MARK_PRICE",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE"
// }
// ]
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "LINK-USDT",
// "orderId": 1585839271162413056,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_MARKET",
// "origQty": "5.0",
// "price": "9",
// "executedQty": "0.0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "5",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1667631605000,
// "updateTime": 1667631605000
// },
// ]
// }
// }
//
// twap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1702731661854,
// "data": {
// "list": [
// {
// "symbol": "BNB-USDT",
// "side": "BUY",
// "positionSide": "LONG",
// "priceType": "constant",
// "priceVariance": "2000",
// "triggerPrice": "68000",
// "interval": 8,
// "amountPerOrder": "0.111",
// "totalAmount": "0.511",
// "orderStatus": "Running",
// "executedQty": "0.1",
// "duration": 800,
// "maxDuration": 9000,
// "createdTime": 1702731661854,
// "updateTime": 1702731661854
// }
// ],
// "total": 1
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list2(data, Value::Str("orders".into()), Value::Str("list".into()), &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name bingx#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @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] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_canceled_and_closed_orders(&[symbol, since, limit, params]).await;
return self.filter_by(orders, Value::Str("status".into()), Value::Str("closed".into()), &[]);
Value::Null
}
/*
* @method
* @name bingx#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @param {string} [symbol] unified market symbol of the canceled orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the max number of canceled orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @returns {object} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_canceled_and_closed_orders(&[symbol, since, limit, params]).await;
return self.filter_by(orders, Value::Str("status".into()), Value::Str("canceled".into()), &[]);
Value::Null
}
/*
* @method
* @name bingx#fetchCanceledAndClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Order%20history
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20TWAP%20Historical%20Orders
* @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 {int} [params.until] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @param {boolean} [params.twap] if fetching twap orders
* @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 market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
market = self.market(symbol);
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 response: Value = Value::Null;
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchCanceledAndClosedOrders".into()), &[market.clone(), 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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchCanceledAndClosedOrders".into()), &[market.clone(), paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut standardparamsStandardVariable = self.handle_option_bool_and_params(paramsSubType, Value::Str("fetchCanceledAndClosedOrders".into()), Value::Str("standard".into()), &[Value::Bool(false)]);
let mut standard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsStandard: Value = standardparamsStandardVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&standard) {
let __ws_arg_43 = self.extend(request.clone(), &[paramsStandard.clone()]);
response = self.contract_v1_private_get_all_orders(&[__ws_arg_43]).await;
} else if (type_var.as_str() == Some("spot")) {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut until: Value = self.safe_integer2(paramsStandard.clone(), Value::Str("until".into()), Value::Str("till".into()), &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until.clone()); }
}
let mut paramsSpot: Value = self.omit(paramsStandard.clone(), Value::from(vec![Value::Str("until".into()), Value::Str("till".into())]), &[]);
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("pageSize".into(), limit.clone()); }
}
let __ws_arg_44 = self.extend(request.clone(), &[paramsSpot]);
response = self.spot_v1_private_get_trade_history_orders(&[__ws_arg_44]).await;
} else {
let mut isTwapOrder: Value = self.safe_bool_k(paramsStandard.clone(), "twap", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(paramsStandard, Value::Str("twap".into()), &[]);
if (isTwapOrder.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("pageIndex".into(), Value::Int(1)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("pageSize".into(), (if (limit == Value::Null) { Value::Int(100) } else { limit.clone() })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), (if (since == Value::Null) { Value::Int(1) } else { since.clone() })); }
let mut until: Value = self.safe_integer_k(paramsOmitted.clone(), "until", &[self.milliseconds()]);
let mut paramsUntil: Value = self.omit(paramsOmitted.clone(), Value::Str("until".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
let __ws_arg_45 = self.extend(request.clone(), &[paramsUntil]);
response = self.swap_v1_private_get_twap_history_orders(&[__ws_arg_45]).await;
} else if (subType.as_str() == Some("inverse")) {
let __ws_arg_46 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.cswap_v1_private_get_trade_order_history(&[__ws_arg_46]).await;
} else {
let __ws_arg_47 = self.extend(request, &[paramsOmitted]);
response = self.swap_v2_private_get_trade_all_orders(&[__ws_arg_47]).await;
}
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = self.safe_list2(data, Value::Str("orders".into()), Value::Str("list".into()), &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name bingx#transfer
* @description transfer currency internally between wallets on the same account
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Fund%20Account/Asset%20Transfer%20New
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from (spot, swap, futures, or funding)
* @param {string} toAccount account to transfer to (spot, swap (linear or inverse), future, or funding)
* @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 subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("transfer".into()), &[Value::Null, params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
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()]);
if (fromAccount.as_str() == Some("swap")) {
if (subType.as_str() == Some("inverse")) {
fromId = Value::Str("coinMPerp".into());
} else {
fromId = Value::Str("USDTMPerp".into());
}
}
if (toAccount.as_str() == Some("swap")) {
if (subType.as_str() == Some("inverse")) {
toId = Value::Str("coinMPerp".into());
} else {
toId = Value::Str("USDTMPerp".into());
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fromAccount".to_string(), fromId);
m.insert("toAccount".to_string(), toId);
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
});
let __ws_arg_48 = self.extend(request, &[paramsSubType]);
let mut response: Value = self.api_asset_v1_private_post_transfer(&[__ws_arg_48]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("id".to_string(), self.safe_string2(data, Value::Str("transferId".into()), Value::Str("tranId".into()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), amount);
m.insert("fromAccount".to_string(), fromAccount);
m.insert("toAccount".to_string(), toAccount);
m.insert("status".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Fund%20Account/Asset%20transfer%20records%20new
* @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, max 100)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.fromAccount] transfer from (spot, swap (linear or inverse), future, or funding), required unless transferId is provided
* @param {string} [params.toAccount] transfer to (spot, swap(linear or inverse), future, or funding), required unless transferId is provided
* @param {string} [params.transferId] the transfer ID, either transferId or both fromAccount and toAccount are required
* @param {int} [params.until] the latest time in ms to fetch transfers for
* @param {boolean} [params.paginate] whether to paginate the results (default false)
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code.clone());
}
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromAccount: Value = self.safe_string_k(params.clone(), "fromAccount", &[]);
let mut toAccount: Value = self.safe_string_k(params.clone(), "toAccount", &[]);
let mut transferId: Option<String> = self.safe_string_k(params.clone(), "transferId", &[]).as_str().map(str::to_owned);
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()]);
if (transferId.is_none()) && ((fromId == Value::Null) || (toId == Value::Null)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTransfers() requires params[\"transferId\"] or both params[\"fromAccount\"] and params[\"toAccount\"]".into()))));
}
if (fromAccount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("fromAccount".into(), fromId); }
}
if (toAccount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("toAccount".into(), toId); }
}
let mut maxLimit: Value = Value::Int(100);
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchTransfers".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_dynamic(Value::Str("fetchTransfers".into()), &[code, since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit.clone()]).await;
}
let mut paramsOmitted: Value = self.omit(paramsPaginate, Value::from(vec![Value::Str("fromAccount".into()), Value::Str("toAccount".into())]), &[]);
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("pageSize".into(), crate::runtime::Math::min(&limit, &maxLimit)); }
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, paramsOmitted, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_49 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.api_v3_private_get_asset_transfer_record(&[__ws_arg_49]).await;
//
// {
// "total": 2,
// "rows": [
// {
// "asset": "LTC",
// "amount": "0.05000000000000000000",
// "status": "CONFIRMED",
// "transferId": "1051461075661819338791",
// "timestamp": 1752202092000,
// "fromAccount": "spot",
// "toAccount": "USDTMPerp"
// }
// ]
// }
//
let mut rows: Value = self.safe_list_k(response, "rows", &[Value::from(vec![])]);
return self.parse_transfers(rows, &[currency, since, 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);
let mut tranId: Value = self.safe_string_k(transfer.clone(), "transferId", &[]);
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "timestamp", &[]);
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "asset", &[]);
let mut currencyCode: Value = self.safe_currency_code(currencyId, &[currency]);
let mut status: Value = self.safe_string_k(transfer.clone(), "status", &[]);
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_k(transfer.clone(), "fromAccount", &[]);
let mut toId: Value = self.safe_string_k(transfer.clone(), "toAccount", &[]);
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()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), tranId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), currencyCode);
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.parse_transfer_status(status).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parse_transfer_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CONFIRMED".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name bingx#fetchDepositAddressesByNetwork
* @description fetch the deposit addresses for a currency associated with this account
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Wallet%20Deposits%20and%20Withdrawals/Main%20Account%20Deposit%20Address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary [address structures]{@link https://docs.ccxt.com/?id=address-structure}, indexed by the network
*/
pub async fn fetch_deposit_addresses_by_network(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut defaultRecvWindow: Value = self.safe_integer_k(self.options.clone(), "recvWindow", &[]);
let mut recvWindow: Value = self.safe_integer_k(params.clone(), "recvWindow", &[defaultRecvWindow]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("coin".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("offset".to_string(), Value::Int(0));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("recvWindow".to_string(), recvWindow);
m
});
let __ws_arg_50 = self.extend(request, &[params]);
let mut response: Value = self.wallets_v1_private_get_capital_deposit_address(&[__ws_arg_50]).await;
//
// {
// "code": "0",
// "timestamp": "1695200226859",
// "data": {
// "data": [
// {
// "coinId": "799",
// "coin": "USDT",
// "network": "BEP20",
// "address": "6a7eda2817462dabb6493277a2cfe0f5c3f2550b",
// "tag": ''
// }
// ],
// "total": "1"
// }
// }
//
let mut data: Value = self.safe_list(self.safe_dict_k(response, "data", &[]), Value::Str("data".into()), &[]);
let mut parsed: Value = self.parse_deposit_addresses(data, &[Value::from(vec![currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null)]), Value::Bool(false)]);
return self.index_by(parsed, Value::Str("network".into()));
Value::Null
}
/*
* @method
* @name bingx#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Wallet%20Deposits%20and%20Withdrawals/Main%20Account%20Deposit%20Address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] The chain of currency. This only apply for multi-chain currency, and there is no need for single chain currency
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut network: Value = self.safe_string_k(params.clone(), "network", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("network".into())]), &[]);
let mut addressStructures: Value = self.fetch_deposit_addresses_by_network(code.clone(), &[paramsOmitted]).await;
if (network != Value::Null) {
return self.safe_dict(addressStructures.clone(), network, &[]);
} else {
let mut options: Value = self.safe_dict_k(self.options.clone(), "defaultNetworks", &[]);
let mut defaultNetworkForCurrency: Value = self.safe_string(options, code, &[]);
if (defaultNetworkForCurrency != Value::Null) {
return self.safe_dict(addressStructures.clone(), defaultNetworkForCurrency, &[]);
} else {
let mut keys: Value = object_keys(&addressStructures);
let mut key: Value = self.safe_string(keys, Value::Int(0), &[]);
return self.safe_dict(addressStructures, key, &[]);
}
}
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "coinId":"4",
// "coin":"USDT",
// "network":"OMNI",
// "address":"1HXyx8HVQRY7Nhqz63nwnRB7SpS9xQPzLN",
// "addressWithPrefix":"1HXyx8HVQRY7Nhqz63nwnRB7SpS9xQPzLN"
// }
//
let mut tag: Value = self.safe_string_k(depositAddress.clone(), "tag", &[]);
let mut currencyId: Value = self.safe_string_k(depositAddress.clone(), "coin", &[]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut code: Value = currencyResolved.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null);
let mut address: Value = self.safe_string2(depositAddress.clone(), Value::Str("addressWithPrefix".into()), Value::Str("address".into()), &[]);
let mut networkId: Value = self.safe_string_k(depositAddress.clone(), "network", &[]);
let mut networkCode: Value = self.network_id_to_code(&[networkId, code.clone()]);
// despite its name the addressWithPrefix field sometimes arrives without
// the 0x prefix on the evm networks, see https://github.com/ccxt/ccxt/issues/24331
if (address != Value::Null) {
let mut isPrefixed: bool = (starts_with(&address, &Value::Str("0x".into()))) || (starts_with(&address, &Value::Str("0X".into())));
let mut evmNetworks: Value = Value::from(vec![Value::Str("BEP20".into()), Value::Str("BSC".into()), Value::Str("ERC20".into()), Value::Str("ETH".into()), Value::Str("HECO".into()), Value::Str("MATIC".into()), Value::Str("POLYGON".into()), Value::Str("ARBITRUM".into()), Value::Str("ARB".into()), Value::Str("OPTIMISM".into()), Value::Str("AVAXC".into()), Value::Str("BASE".into()), Value::Str("FTM".into()), Value::Str("LINEA".into()), Value::Str("ZKSYNC".into()), Value::Str("OPBNB".into())]);
if !isPrefixed && self.in_array(networkCode.clone(), evmNetworks).as_bool() == Some(true) {
address = Value::Str(format!("{}{}", Value::Str("0x".into()), address).into());
}
}
self.check_address(&[address.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), code);
m.insert("network".to_string(), networkCode);
m.insert("address".to_string(), address);
m.insert("tag".to_string(), tag);
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchDeposits
* @description fetch all deposits made to an account
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Wallet%20deposits%20and%20withdrawals/Deposit%20records
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch deposits for
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
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(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_51 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.spot_v3_private_get_capital_deposit_hisrec(&[__ws_arg_51]).await;
return self.parse_transactions(response, &[currency, since, limit]);
Value::Null
}
/*
* @method
* @name bingx#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Wallet%20deposits%20and%20withdrawals/Withdraw%20records
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch withdrawals for
* @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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
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(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_52 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.spot_v3_private_get_capital_withdraw_history(&[__ws_arg_52]).await;
return self.parse_transactions(response, &[currency, since, limit]);
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
//
// {
// "amount":"0.00999800",
// "coin":"PAXG",
// "network":"ETH",
// "status":1,
// "address":"0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
// "addressTag":"",
// "txId":"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",
// "insertTime":1599621997000,
// "transferType":0,
// "unlockConfirm":"12/12", // confirm times for unlocking
// "confirmTimes":"12/12"
// }
//
// fetchWithdrawals
//
// {
// "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
// "amount": "8.91000000",
// "applyTime": "2019-10-12 11:12:02",
// "coin": "USDT",
// "id": "b6ae22b3aa844210a7041aee7589627c",
// "withdrawOrderId": "WITHDRAWtest123",
// "network": "ETH",
// "transferType": 0
// "status": 6,
// "transactionFee": "0.004",
// "confirmNo":3,
// "info": "The address is not valid. Please confirm with the recipient",
// "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"
// }
//
// withdraw
//
// {
// "code":0,
// "timestamp":1705274263621,
// "data":{
// "id":"1264246141278773252"
// }
// }
//
// parse withdraw-type output first...
//
let mut data: Value = self.safe_dict_k(transaction.clone(), "data", &[]);
let mut dataId: Value = (if (data == Value::Null) { Value::Null } else { self.safe_string_k(data, "id", &[]) });
let mut id: Value = self.safe_string_k(transaction.clone(), "id", &[dataId]);
let mut address: Value = self.safe_string_k(transaction.clone(), "address", &[]);
let mut tag: Value = self.safe_string_k(transaction.clone(), "addressTag", &[]);
let mut timestamp: Value = self.safe_integer2(transaction.clone(), Value::Str("insertTime".into()), Value::Str("timestamp".into()), &[]);
let mut datetime: Value = self.iso8601(timestamp.clone());
if (timestamp == Value::Null) {
timestamp = self.parse8601(self.safe_string_k(transaction.clone(), "applyTime", &[]));
datetime = self.iso8601(timestamp.clone());
}
let mut network: Value = self.safe_string_k(transaction.clone(), "network", &[]);
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "coin", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
if (code != Value::Null) && (network != Value::Null) && (code.as_str() != network.as_str()) && get_index_of(&code, &network).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if (network != Value::Null) {
code = replace_str(&code, &network, &Value::Str("".into()));
}
}
// deposit records carry insertTime and no transferType, withdrawal records say 1 (on-chain) or 2 (internal)
let mut rawType: Option<String> = self.safe_string_k(transaction.clone(), "transferType", &[]).as_str().map(str::to_owned);
let mut type_var: Value = Value::Str("withdrawal".into());
if (rawType.as_deref() == Some("0")) || (matches!(&transaction, Value::Dict(__d) if __d.contains_key("insertTime"))) {
type_var = Value::Str("deposit".into());
}
let mut internal: Value = Value::Null;
if (rawType.is_some()) {
internal = (Value::Bool(rawType.as_deref() == Some("2")));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), id);
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "txId", &[]));
m.insert("type".to_string(), type_var.clone());
m.insert("currency".to_string(), code.clone());
m.insert("network".to_string(), self.network_id_to_code(&[network, code.clone()]));
m.insert("amount".to_string(), self.safe_number_k(transaction.clone(), "amount", &[]));
m.insert("status".to_string(), self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]), &[type_var]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("address".to_string(), address.clone());
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), address);
m.insert("tag".to_string(), tag.clone());
m.insert("tagFrom".to_string(), tag);
m.insert("tagTo".to_string(), Value::Null);
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), self.safe_string_k(transaction.clone(), "info", &[]));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code);
m.insert("cost".to_string(), self.safe_number_k(transaction, "transactionFee", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m.insert("internal".to_string(), internal);
m
});
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value, optional_args: &[Value]) -> Value {
let mut type_var = get_arg(optional_args, 0, Value::Null);
let mut statusesByType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("pending".into()));
m.insert("6".to_string(), Value::Str("pending".into()));
m.insert("1".to_string(), Value::Str("ok".into()));
m
}));
m.insert("withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("4".to_string(), Value::Str("pending".into()));
m.insert("5".to_string(), Value::Str("failed".into()));
m.insert("6".to_string(), Value::Str("ok".into()));
m
}));
m
});
let mut directional: Value = self.safe_dict(statusesByType, type_var, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("pending".into()));
m.insert("1".to_string(), Value::Str("ok".into()));
m.insert("10".to_string(), Value::Str("pending".into()));
m.insert("20".to_string(), Value::Str("rejected".into()));
m.insert("30".to_string(), Value::Str("ok".into()));
m.insert("40".to_string(), Value::Str("rejected".into()));
m.insert("50".to_string(), Value::Str("ok".into()));
m.insert("60".to_string(), Value::Str("pending".into()));
m.insert("70".to_string(), Value::Str("rejected".into()));
m.insert("2".to_string(), Value::Str("pending".into()));
m.insert("3".to_string(), Value::Str("rejected".into()));
m.insert("4".to_string(), Value::Str("pending".into()));
m.insert("5".to_string(), Value::Str("rejected".into()));
m.insert("6".to_string(), Value::Str("ok".into()));
m
});
let mut fallback: Value = self.safe_string(statuses, status.clone(), &[status.clone()]);
return self.safe_string(directional, status, &[fallback]);
Value::Null
}
/*
* @method
* @name bingx#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Change%20Margin%20Type
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Set%20Margin%20Type
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() != Some("swap")) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() supports swap contracts only".into()))));
}
let mut marginModeUpper: Value = to_upper(&marginMode);
let mut marginModeValue: Value = (if (marginModeUpper.as_str() == Some("CROSS")) { Value::Str("CROSSED".into()) } else { marginModeUpper });
if (marginModeValue.as_str() != Some("ISOLATED")) && (marginModeValue.as_str() != Some("CROSSED")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() marginMode argument should be isolated or cross".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("marginType".to_string(), marginModeValue);
m
});
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("setMarginMode".into()), &[market, params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) {
let __ws_arg_53 = self.extend(request.clone(), &[paramsSubType.clone()]);
return self.cswap_v1_private_post_trade_margin_type(&[__ws_arg_53]).await;
} else {
let __ws_arg_54 = self.extend(request, &[paramsSubType]);
return self.swap_v2_private_post_trade_margin_type(&[__ws_arg_54]).await;
}
Value::Null
}
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Int(1));
m
});
let __ws_arg_55 = self.extend(request, &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_55]).await;
Value::Null
}
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Int(2));
m
});
let __ws_arg_56 = self.extend(request, &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_56]).await;
Value::Null
}
/*
* @method
* @name bingx#setMargin
* @description Either adds or reduces margin in an isolated position in order to set the margin to a specific value
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Modify%20Isolated%20Position%20Margin
* @param {string} symbol unified market symbol of the market to set margin in
* @param {float} amount the amount to set the margin to
* @param {object} [params] parameters specific to the exchange API endpoint
* @returns {object} A [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn set_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut type_var: Value = self.safe_integer_k(params.clone(), "type", &[]); // 1 increase margin 2 decrease margin
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a type parameter either 1 (increase margin) or 2 (decrease margin)".into()))));
}
if !(self.in_array(type_var.clone(), Value::from(vec![Value::Int(1), Value::Int(2)])).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a type parameter either 1 (increase margin) or 2 (decrease margin)".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.insert("amount".to_string(), self.amount_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), amount));
m.insert("type".to_string(), type_var);
m
});
let __ws_arg_57 = self.extend(request, &[params]);
let mut response: Value = self.swap_v2_private_post_trade_position_margin(&[__ws_arg_57]).await;
return self.parse_margin_modification(response, &[market]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "code": 0,
// "msg": "",
// "amount": 1,
// "type": 1
// }
//
let mut type_var: Option<String> = self.safe_string_k(data.clone(), "type", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("type".to_string(), (if (type_var.as_deref() == Some("1")) { Value::Str("add".into()) } else { Value::Str("reduce".into()) }));
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), self.safe_number_k(data.clone(), "amount", &[]));
m.insert("total".to_string(), self.safe_number_k(data, "margin", &[]));
m.insert("code".to_string(), self.safe_string_k(market, "settle", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchLeverage
* @description fetch the set leverage for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Leverage%20and%20Available%20Positions
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverage(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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 response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_58 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_private_get_trade_leverage(&[__ws_arg_58]).await;
} else {
let __ws_arg_59 = self.extend(request, &[params]);
response = self.swap_v2_private_get_trade_leverage(&[__ws_arg_59]).await;
}
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);
//
// linear swap
//
// {
// "longLeverage": 5,
// "shortLeverage": 5,
// "maxLongLeverage": 125,
// "maxShortLeverage": 125,
// "availableLongVol": "0.0000",
// "availableShortVol": "0.0000",
// "availableLongVal": "0.0",
// "availableShortVal": "0.0",
// "maxPositionLongVal": "0.0",
// "maxPositionShortVal": "0.0"
// }
//
// inverse swap
//
// {
// "symbol": "SOL-USD",
// "longLeverage": 5,
// "shortLeverage": 5,
// "maxLongLeverage": 50,
// "maxShortLeverage": 50,
// "availableLongVol": "4000000",
// "availableShortVol": "4000000"
// }
//
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(), "longLeverage", &[]));
m.insert("shortLeverage".to_string(), self.safe_integer_k(leverage, "shortLeverage", &[]));
m
});
Value::Null
}
/*
* @method
* @name bingx#setLeverage
* @description set the level of leverage for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Set%20Leverage
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Modify%20Leverage
* @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.side] hedged: ['long' or 'short']. one way: ['both']
* @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()))));
}
let mut side: Value = self.safe_string_upper_k(params.clone(), "side", &[]);
self.check_required_argument(Value::Str("setLeverage".into()), side.clone(), Value::Str("side".into()), &[Value::from(vec![Value::Str("LONG".into()), Value::Str("SHORT".into()), Value::Str("BOTH".into())])]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("side".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.insert("side".to_string(), side);
m.insert("leverage".to_string(), leverage);
m
});
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_60 = self.extend(request.clone(), &[paramsOmitted.clone()]);
return self.cswap_v1_private_post_trade_leverage(&[__ws_arg_60]).await;
} else {
let __ws_arg_61 = self.extend(request, &[paramsOmitted]);
return self.swap_v2_private_post_trade_leverage(&[__ws_arg_61]).await;
}
Value::Null
}
/*
* @method
* @name bingx#fetchMyTrades
* @description fetch all trades made by the user
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20transaction%20details
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20historical%20transaction%20orders
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Order%20Trade%20Detail
* @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] timestamp in ms for the ending date filter, default is undefined
* @param {string} params.trandingUnit COIN (directly represent assets such as BTC and ETH) or CONT (represents the number of contract sheets)
* @param {string} params.orderId the order id required for inverse swap
* @returns {object[]} 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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() 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
});
let mut fills: Value = Value::Null;
let mut response: Value = Value::Null;
let mut paramsTrades: Value = Value::Null;
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchMyTrades".into()), &[market.clone(), params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) {
paramsTrades = self.omit(paramsSubType.clone(), Value::Str("orderId".into()), &[]);
let mut orderId: Option<String> = self.safe_string_k(paramsSubType.clone(), "orderId", &[]).as_str().map(str::to_owned);
if (orderId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() requires an orderId argument for inverse swap trades".into()))));
}
let __ws_arg_62 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_get_trade_all_fill_orders(&[__ws_arg_62]).await;
fills = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
let mut now: Value = self.milliseconds();
if (since != Value::Null) {
let mut startTimeReq: Value = Value::Str("startTs".into());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
startTimeReq = Value::Str("startTime".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&startTimeReq), since.clone()); }
} else if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTs".into(), (match (&(now), &((match (&((match (&((match (&((match (&(Value::Int(30)), &(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 }))) { (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 })); }; // 30 days for swap
}
let mut until: Value = self.safe_integer_k(paramsSubType.clone(), "until", &[]);
let mut paramsUntil: Value = self.omit(paramsSubType, Value::Str("until".into()), &[]);
if (until != Value::Null) {
let mut endTimeReq: Value = Value::Str("endTs".into());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
endTimeReq = Value::Str("endTime".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&endTimeReq), until); }
} else if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTs".into(), now); }
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 500, maximum 1000
}
paramsTrades = paramsUntil.clone();
let __ws_arg_63 = self.extend(request.clone(), &[paramsUntil.clone()]);
response = self.spot_v1_private_get_trade_my_trades(&[__ws_arg_63]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
fills = self.safe_list_k(data.clone(), "fills", &[Value::from(vec![])]);
} else {
let mut tradingUnit: Value = self.safe_string_upper_k(paramsUntil.clone(), "tradingUnit", &[Value::Str("CONT".into())]);
paramsTrades = self.omit(paramsUntil, Value::Str("tradingUnit".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tradingUnit".into(), tradingUnit); }
let __ws_arg_64 = self.extend(request, &[paramsTrades.clone()]);
response = self.swap_v2_private_get_trade_all_fill_orders(&[__ws_arg_64]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
fills = self.safe_list_k(data, "fill_orders", &[Value::from(vec![])]);
}
}
return self.parse_trades(fills, &[market, since, limit, paramsTrades]);
Value::Null
}
pub fn parse_deposit_withdraw_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// currencie structure
//
let mut networks: Value = self.safe_dict_k(fee, "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networkCodes: Value = object_keys(&networks);
let mut networksLength: f64 = ((networkCodes.len() as i64) as f64);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), networks.clone());
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
});
if (networksLength != 0.0) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_300: bool = true;
while { if !__for_first_300 { 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_300 = false; i.as_f64().unwrap_or(f64::NAN) < networksLength } {
let mut networkCode: Value = networkCodes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut network: Value = self.safe_dict(networks.clone(), networkCode.clone(), &[]);
add_element_to_object(get_value_mut(&mut result, &Value::Str("networks".into())), &networkCode, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), self.safe_number_k(network.clone(), "fee", &[]));
m.insert("percentage".to_string(), Value::Bool(false));
m
}));
m
}));
if (networksLength == 1.0) {
add_element_to_object(get_value_mut(&mut result, &Value::Str("withdraw".into())), &Value::Str("fee".into()), self.safe_number_k(network, "withdrawFee", &[]));
add_element_to_object(get_value_mut(&mut result, &Value::Str("withdraw".into())), &Value::Str("percentage".into()), Value::Bool(false));
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name bingx#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Wallet%20Deposits%20and%20Withdrawals/Query%20currency%20deposit%20and%20withdrawal%20data
* @param {string[]|undefined} codes list of unified currency codes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_deposit_withdraw_fees(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.fetch_currencies(&[params]).await;
let mut depositWithdrawFees: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut responseCodes: Value = object_keys(&response);
{
let mut i: Value = Value::Int(0);
let mut __for_first_301: bool = true;
while { if !__for_first_301 { 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_301 = false; i.as_f64().unwrap_or(f64::NAN) < ((responseCodes.len() as i64) as f64) } {
let mut code: Value = responseCodes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (codes == Value::Null) || self.in_array(code.clone(), codes.clone()).as_bool() == Some(true) {
let mut entry: Value = self.safe_dict(response.clone(), code.clone(), &[]);
if let Value::Dict(__d) = &mut depositWithdrawFees { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.parse_deposit_withdraw_fee(entry, &[])); }
}
}
}
return depositWithdrawFees;
Value::Null
}
/*
* @method
* @name bingx#withdraw
* @description make a withdrawal
* @see https://bingx-api.github.io/docs-v3/#/en/Account%20and%20Wallet/Wallet%20Deposits%20and%20Withdrawals/Withdraw
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @param {int} [params.walletType] 1 fund (funding) account, 2 standard account, 3 perpetual account, 15 spot account
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut tagWithdrawTagparamsWithdrawTagVariable = self.handle_param_string(params, Value::Str("tag".into()), &[]);
let mut tagWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
self.check_address(&[address.clone(), code.clone(), tagWithdrawTag.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut defaultWalletType: Value = Value::Int(15); // spot
let mut walletTypeOptionparamsWalletTypeVariable = self.handle_option_and_params2(paramsWithdrawTag, Value::Str("withdraw".into()), Value::Str("type".into()), Value::Str("walletType".into()), &[defaultWalletType.clone()]);
let mut walletTypeOption: Value = walletTypeOptionparamsWalletTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWalletType: Value = walletTypeOptionparamsWalletTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut walletTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funding".to_string(), Value::Int(1));
m.insert("fund".to_string(), Value::Int(1));
m.insert("standard".to_string(), Value::Int(2));
m.insert("perpetual".to_string(), Value::Int(3));
m.insert("spot".to_string(), Value::Int(15));
m
});
let mut walletType: Value = self.safe_integer(walletTypes, walletTypeOption, &[defaultWalletType]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("coin".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("address".to_string(), address);
m.insert("amount".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("walletType".to_string(), walletType);
m
});
let mut network: Value = self.safe_string_upper_k(paramsWalletType.clone(), "network", &[]);
if (network != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("network".into(), self.network_code_to_id(network, &[self.safe_string_k(currency, "code", &[])])); }
}
if (tagWithdrawTag != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("addressTag".into(), tagWithdrawTag); }
}
let mut paramsOmitted: Value = self.omit(paramsWalletType, Value::from(vec![Value::Str("walletType".into()), Value::Str("network".into())]), &[]);
let __ws_arg_65 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.wallets_v1_private_post_capital_withdraw_apply(&[__ws_arg_65]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[]);
return self.parse_transaction(data, &[]);
Value::Null
}
pub fn parse_params(&self, mut params: Value) -> Value {
// const sortedParams = this.keysort (params);
let mut copied: Value = self.clone_value(params.clone());
let mut rawKeys: Value = object_keys(¶ms);
let mut keys: Value = self.sort(rawKeys, &[]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_303: bool = true;
while { if !__for_first_303 { 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_303 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&keys).as_f64().unwrap_or(f64::NAN) } {
let mut key: Value = get_value(&keys, &i);
let mut key: Value = get_value(&keys, &i);
let mut value: Value = get_value(¶ms, &key);
let mut value: Value = get_value(¶ms, &key);
if (matches!(&value, Value::Arr(_))) {
let mut arrStr: Value = Value::Str("[".into());
{
let mut j: Value = Value::Int(0);
let mut __for_first_302: bool = true;
while { if !__for_first_302 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_302 = false; j.as_f64().unwrap_or(f64::NAN) < ((value.len() as i64) as f64) } {
let mut arrayElement: Value = value.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if j.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
arrStr = Value::Str(format!("{}{}", arrStr, Value::Str(",".into())).into());
}
arrStr = add(&arrStr, &to_string_val(&arrayElement));
}
}
arrStr = Value::Str(format!("{}{}", arrStr, Value::Str("]".into())).into());
add_element_to_object(&mut copied, &key, arrStr);
}
}
}
return copied;
Value::Null
}
/*
* @method
* @name bingx#fetchMyLiquidations
* @description retrieves the users liquidated positions
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/User's%20Force%20Orders
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20force%20orders
* @param {string} [symbol] unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve (max 100)
* @param {object} [params] exchange specific parameters for the bingx api endpoint
* @param {int} [params.until] timestamp in ms of the latest liquidation
* @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/?id=liquidation-structure}
*/
pub async fn fetch_my_liquidations(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("autoCloseType".to_string(), Value::Str("LIQUIDATION".into()));
m
});
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
add_element_to_object(&mut requestUntil, &Value::Str("symbol".into()), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
if (since != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("startTime".into()), since.clone());
}
if (limit != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("limit".into()), crate::runtime::Math::min(&limit, &Value::Int(100))); // api maximum 100
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchMyLiquidations".into()), &[market.clone(), paramsUntil]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
let mut liquidations: Value = Value::Null;
if (subType.as_str() == Some("inverse")) {
let __ws_arg_66 = self.extend(requestUntil.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_get_trade_force_orders(&[__ws_arg_66]).await;
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721280071678,
// "data": [
// {
// "orderId": "string",
// "symbol": "string",
// "type": "string",
// "side": "string",
// "positionSide": "string",
// "price": "string",
// "quantity": "float64",
// "stopPrice": "string",
// "workingType": "string",
// "status": "string",
// "time": "int64",
// "avgPrice": "string",
// "executedQty": "string",
// "profit": "string",
// "commission": "string",
// "updateTime": "string"
// }
// ]
// }
//
liquidations = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
} else {
let __ws_arg_67 = self.extend(requestUntil, &[paramsSubType]);
response = self.swap_v2_private_get_trade_force_orders(&[__ws_arg_67]).await;
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "time": "int64",
// "symbol": "string",
// "side": "string",
// "type": "string",
// "positionSide": "string",
// "cumQuote": "string",
// "status": "string",
// "stopPrice": "string",
// "price": "string",
// "origQty": "string",
// "avgPrice": "string",
// "executedQty": "string",
// "orderId": "int64",
// "profit": "string",
// "commission": "string",
// "workingType": "string",
// "updateTime": "int64"
// },
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
liquidations = self.safe_list_k(data, "orders", &[Value::from(vec![])]);
}
return self.parse_liquidations(liquidations, &[market, since, limit]);
Value::Null
}
pub fn parse_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "time": "int64",
// "symbol": "string",
// "side": "string",
// "type": "string",
// "positionSide": "string",
// "cumQuote": "string",
// "status": "string",
// "stopPrice": "string",
// "price": "string",
// "origQty": "string",
// "avgPrice": "string",
// "executedQty": "string",
// "orderId": "int64",
// "profit": "string",
// "commission": "string",
// "workingType": "string",
// "updateTime": "int64"
// }
//
let mut marketId: Value = self.safe_string_k(liquidation.clone(), "symbol", &[]);
let mut timestamp: Value = self.safe_integer_k(liquidation.clone(), "time", &[]);
let mut contractsString: Value = self.safe_string_k(liquidation.clone(), "executedQty", &[]);
let mut contractSizeString: Value = self.safe_string_k(market.clone(), "contractSize", &[]);
let mut priceString: Value = self.safe_string_k(liquidation.clone(), "avgPrice", &[]);
let mut baseValueString: Value = crate::precise::Precise::stringMul(&contractsString, &contractSizeString);
let mut quoteValueString: Value = crate::precise::Precise::stringMul(&baseValueString, &priceString);
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation);
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("contracts".to_string(), self.parse_number(contractsString, &[]));
m.insert("contractSize".to_string(), self.parse_number(contractSizeString, &[]));
m.insert("price".to_string(), self.parse_number(priceString, &[]));
m.insert("baseValue".to_string(), self.parse_number(baseValueString, &[]));
m.insert("quoteValue".to_string(), self.parse_number(quoteValueString, &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}), &[]);
Value::Null
}
/*
* @method
* @name bingx#closePosition
* @description closes open positions for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Close%20All%20Positions
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Close%20position%20by%20position%20ID
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Close%20all%20positions%20in%20bulk
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] not used by bingx
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string|undefined} [params.positionId] the id of the position you would like to close, only supported for linear swap
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn close_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut side = 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 positionId: Option<String> = self.safe_string_k(params.clone(), "positionId", &[]).as_str().map(str::to_owned);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (positionId.is_some()) {
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) || (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" closePosition() with a positionId is only supported for linear swap markets".into()))));
}
let __ws_arg_68 = self.extend(request.clone(), &[params.clone()]);
response = self.swap_v1_private_post_trade_close_position(&[__ws_arg_68]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_69 = self.extend(request.clone(), &[params.clone()]);
response = self.cswap_v1_private_post_trade_close_all_positions(&[__ws_arg_69]).await;
} else {
let __ws_arg_70 = self.extend(request, &[params]);
response = self.swap_v2_private_post_trade_close_all_positions(&[__ws_arg_70]).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, &[market]);
Value::Null
}
/*
* @method
* @name bitget#closePositions
* @description closes open positions for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Close%20All%20Positions
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Close%20all%20positions%20in%20bulk
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.recvWindow] request valid time window value
* @returns {object[]} [a list of position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn close_all_positions(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut defaultRecvWindow: Value = self.safe_integer_k(self.options.clone(), "recvWindow", &[]);
let mut recvWindow: Value = self.safe_integer_k(params.clone(), "recvWindow", &[defaultRecvWindow]);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("closeAllPositions".into()), &[Value::Null, params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("closeAllPositions".into()), &[Value::Null, paramsMarketType]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marketType.as_str() == Some("margin")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" closePositions () cannot be used for ".into())).into()), marketType).into()), Value::Str(" markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("recvWindow".to_string(), recvWindow);
m
});
let mut response: Value = Value::Null;
if (subType.as_str() == Some("inverse")) {
let __ws_arg_71 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_post_trade_close_all_positions(&[__ws_arg_71]).await;
} else {
let __ws_arg_72 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_post_trade_close_all_positions(&[__ws_arg_72]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut success: Value = self.safe_list_k(data, "success", &[Value::from(vec![])]);
let mut positions: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_304: bool = true;
while { if !__for_first_304 { 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_304 = false; i.as_f64().unwrap_or(f64::NAN) < ((success.len() as i64) as f64) } {
let mut position: Value = self.parse_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("positionId".to_string(), success.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
m
}), &[]);
append_to_array(&mut positions, position);
}
}
return positions;
Value::Null
}
/*
* @method
* @name bingx#fetchPositionMode
* @description fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20position%20mode
* @param {string} symbol unified market symbol, inverse (Coin-M) markets are not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
self.load_markets(&[]).await;
market = self.market(symbol);
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchPositionMode".into()), &[market.clone(), params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) || ((market != Value::Null) && (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchPositionMode() is not supported for inverse swap markets".into()))));
}
let mut response: Value = self.swap_v1_private_get_position_side_dual(&[paramsSubType]).await;
//
// {
// "code": "0",
// "msg": "",
// "timeStamp": "1709002057516",
// "data": {
// "dualSidePosition": "false"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dualSidePosition: Option<String> = self.safe_string_k(data, "dualSidePosition", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("hedged".to_string(), (Value::Bool(dualSidePosition.as_deref() == Some("true"))));
m
});
Value::Null
}
/*
* @method
* @name bingx#setPositionMode
* @description set hedged to true or false for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Set%20Position%20Mode
* @param {bool} hedged set to true to use dualSidePosition
* @param {string} symbol unified market symbol, inverse (Coin-M) markets are not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
self.load_markets(&[]).await;
market = self.market(symbol);
}
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("setPositionMode".into()), &[market.clone(), params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) || ((market != Value::Null) && (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" setPositionMode() is not supported for inverse swap markets".into()))));
}
let mut dualSidePosition: Value = Value::Null;
if is_true(&hedged) {
dualSidePosition = Value::Str("true".into());
} else {
dualSidePosition = Value::Str("false".into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("dualSidePosition".to_string(), dualSidePosition);
m
});
let __ws_arg_73 = self.extend(request, &[paramsSubType]);
return self.swap_v1_private_post_position_side_dual(&[__ws_arg_73]).await;
Value::Null
}
/*
* @method
* @name bingx#editOrder
* @description cancels an order and places a new order
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Cancel%20an%20Existing%20Order%20and%20Send%20a%20New%20Order // spot
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Cancel%20an%20Existing%20Order%20and%20Send%20a%20New%20Orde // swap
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in, inverse (Coin-M) markets are not supported
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.triggerPrice] Trigger price used for TAKE_STOP_LIMIT, TAKE_STOP_MARKET, TRIGGER_LIMIT, TRIGGER_MARKET order types.
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {string} [params.cancelClientOrderID] the user-defined id of the order to be canceled, 1-40 characters, different orders cannot use the same clientOrderID, only supports a query range of 2 hours
* @param {string} [params.cancelRestrictions] cancel orders with specified status, NEW: New order, PENDING: Pending order, PARTIALLY_FILLED: Partially filled
* @param {string} [params.cancelReplaceMode] STOP_ON_FAILURE - if the cancel order fails, it will not continue to place a new order, ALLOW_FAILURE - regardless of whether the cancel order succeeds or fails, it will continue to place a new order
* @param {float} [params.quoteOrderQty] order amount
* @param {string} [params.newClientOrderId] custom order id consisting of letters, numbers, and _, 1-40 characters, different orders cannot use the same newClientOrderId.
* @param {string} [params.positionSide] *contract only* position direction, required for single position as BOTH, for both long and short positions only LONG or SHORT can be chosen, defaults to LONG if empty
* @param {string} [params.reduceOnly] *contract only* true or false, default=false for single position mode. this parameter is not accepted for both long and short positions mode
* @param {float} [params.priceRate] *contract only* for type TRAILING_STOP_Market or TRAILING_TP_SL, Max = 1
* @param {string} [params.workingType] *contract only* StopPrice trigger price types, MARK_PRICE (default), CONTRACT_PRICE, or INDEX_PRICE
* @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 market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" editOrder() is not supported for inverse swap markets".into()))));
}
let mut request: Value = self.create_order_request(symbol, type_var, side, amount, &[price, params.clone()]);
add_element_to_object(&mut request, &Value::Str("cancelOrderId".into()), id);
add_element_to_object(&mut request, &Value::Str("cancelReplaceMode".into()), self.safe_string_k(params, "cancelReplaceMode", &[Value::Str("STOP_ON_FAILURE".into())]));
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
response = self.swap_v1_private_post_trade_cancel_replace(&[request.clone()]).await;
} else {
response = self.spot_v1_private_post_trade_order_cancel_replace(&[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, &[market]);
Value::Null
}
/*
* @method
* @name bingx#fetchMarginMode
* @description fetches the margin mode of the trading pair
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Query%20Margin%20Type
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Margin%20Type
* @param {string} symbol unified symbol of the market to fetch the margin mode for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/?id=margin-mode-structure}
*/
pub async fn fetch_margin_mode(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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 response: Value = Value::Null;
let mut subTypeparamsSubTypeVariable = self.handle_sub_type_and_params(Value::Str("fetchMarginMode".into()), &[market.clone(), params]);
let mut subType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSubType: Value = subTypeparamsSubTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (subType.as_str() == Some("inverse")) {
let __ws_arg_74 = self.extend(request.clone(), &[paramsSubType.clone()]);
response = self.cswap_v1_private_get_trade_margin_type(&[__ws_arg_74]).await;
} else {
let __ws_arg_75 = self.extend(request, &[paramsSubType]);
response = self.swap_v2_private_get_trade_margin_type(&[__ws_arg_75]).await;
}
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", &[]);
let mut marginType: Value = self.safe_string_lower_k(marginMode.clone(), "marginType", &[]);
if (marginType.as_str() == Some("crossed")) {
marginType = Value::Str("cross".into());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), marginMode);
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Str("-".into()), Value::Str("swap".into())]));
m.insert("marginMode".to_string(), marginType);
m
});
Value::Null
}
/*
* @method
* @name bingx#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://bingx-api.github.io/docs-v3/#/en/Spot/Trades%20Endpoints/Query%20Trading%20Commission%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Account%20Endpoints/Query%20Trading%20Commission%20Rate
* @see https://bingx-api.github.io/docs-v3/#/en/Coin-M%20Futures/Trades%20Endpoints/Query%20Trade%20Commission%20Rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
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 response: Value = Value::Null;
let mut commission: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_76 = self.extend(request, &[params.clone()]);
response = self.spot_v1_private_get_user_commission_rate(&[__ws_arg_76]).await;
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "takerCommissionRate": 0.001,
// "makerCommissionRate": 0.001
// }
// }
//
commission = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
response = self.cswap_v1_private_get_user_commission_rate(&[params.clone()]).await;
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721365261438,
// "data": {
// "takerCommissionRate": "0.0005",
// "makerCommissionRate": "0.0002"
// }
// }
//
commission = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
response = self.swap_v2_private_get_user_commission_rate(&[params]).await;
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "commission": {
// "takerCommissionRate": 0.0005,
// "makerCommissionRate": 0.0002
// }
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
commission = self.safe_dict_k(data, "commission", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
}
return self.parse_trading_fee(commission, &[market]);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "takerCommissionRate": 0.001,
// "makerCommissionRate": 0.001
// }
//
let mut symbol: Value = (if (market != Value::Null) { market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null) } else { Value::Null });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), symbol);
m.insert("maker".to_string(), self.safe_number_k(fee.clone(), "makerCommissionRate", &[]));
m.insert("taker".to_string(), self.safe_number_k(fee, "takerCommissionRate", &[]));
m.insert("percentage".to_string(), Value::Bool(false));
m.insert("tierBased".to_string(), Value::Bool(false));
m
});
Value::Null
}
pub fn custom_encode(&self, mut params: Value) -> Option<String> {
// const sortedParams = this.keysort (params);
let mut rawKeys: Value = object_keys(¶ms);
let mut keys: Value = self.sort(rawKeys, &[]);
let mut adjustedValue: Value = Value::Null;
let mut result: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_306: bool = true;
while { if !__for_first_306 { 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_306 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&keys).as_f64().unwrap_or(f64::NAN) } {
let mut key: Value = get_value(&keys, &i);
let mut key: Value = get_value(&keys, &i);
let mut value: Value = get_value(¶ms, &key);
let mut value: Value = get_value(¶ms, &key);
if (matches!(&value, Value::Arr(_))) {
let mut arrStr: Value = Value::Null;
{
let mut j: Value = Value::Int(0);
let mut __for_first_305: bool = true;
while { if !__for_first_305 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_305 = false; j.as_f64().unwrap_or(f64::NAN) < ((value.len() as i64) as f64) } {
let mut arrayElement: Value = value.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut isString: bool = matches!(&arrayElement, Value::Str(_));
if isString {
if j.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
arrStr = Value::Str(format!("{}{}", arrStr, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(",".into()), Value::Str("\"".into())).into()), to_string_val(&arrayElement)).into()), Value::Str("\"".into())).into())).into());
} else {
arrStr = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("\"".into()), to_string_val(&arrayElement)).into()), Value::Str("\"".into())).into());
}
} else {
if j.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
arrStr = Value::Str(format!("{}{}", arrStr, add(&Value::Str(",".into()), &to_string_val(&arrayElement))).into());
} else {
arrStr = to_string_val(&arrayElement);
}
}
}
}
adjustedValue = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("[".into()), arrStr).into()), Value::Str("]".into())).into());
value = adjustedValue.clone();
}
if (i.as_f64() == Some(0.0)) {
result = add(&add(&key, &Value::Str("=".into())), &value);
} else {
result = Value::Str(format!("{}{}", result, add(&Value::Str(format!("{}{}", add(&Value::Str("&".into()), &key), Value::Str("=".into())).into()), &value)).into());
}
}
}
return result.as_str().map(str::to_owned);
}
/*
* @method
* @name bingx#fetchMarketLeverageTiers
* @description retrieve information on the maximum leverage, for different trade sizes for a single market
* @see https://bingx-api.github.io/docs-v3/#/en/Swap/Trades%20Endpoints/Position%20and%20Maintenance%20Margin%20Ratio
* @param {string} symbol unified market symbol, inverse (Coin-M) markets are not supported
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage tiers structure]{@link https://docs.ccxt.com/?id=leverage-tiers-structure}
*/
pub async fn fetch_market_leverage_tiers(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchMarketLeverageTiers() supports swap markets only".into()))));
}
if (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchMarketLeverageTiers() is not supported for inverse swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_77 = self.extend(request, &[params]);
let mut response: Value = self.swap_v1_private_get_maint_margin_ratio(&[__ws_arg_77]).await;
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1767789967284,
// "data": [
// {
// "tier": "Tier 1",
// "symbol": "ETH-USDT",
// "minPositionVal": "0",
// "maxPositionVal": "900000",
// "maintMarginRatio": "0.003300",
// "maintAmount": "0.000000"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_market_leverage_tiers(data, &[market]);
Value::Null
}
pub fn parse_market_leverage_tiers(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// {
// "tier": "Tier 1",
// "symbol": "ETH-USDT",
// "minPositionVal": "0",
// "maxPositionVal": "900000",
// "maintMarginRatio": "0.003300",
// "maintAmount": "0.000000"
// }
// ]
//
let mut tiers: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_307: bool = true;
while { if !__for_first_307 { 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_307 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&info).as_f64().unwrap_or(f64::NAN) } {
let mut tier: Value = self.safe_dict(info.clone(), i.clone(), &[]);
let mut tierString: Value = self.safe_string_k(tier.clone(), "tier", &[]);
let mut tierParts: Value = split(&tierString, &Value::Str(" ".into()));
let mut marketId: Value = self.safe_string_k(tier.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market.clone(), Value::Null, Value::Str("swap".into())]);
append_to_array(&mut tiers, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tier".to_string(), self.safe_number(tierParts, Value::Int(1), &[]));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[marketResolved.clone()]));
m.insert("currency".to_string(), self.safe_string_k(marketResolved, "settle", &[]));
m.insert("minNotional".to_string(), self.safe_number_k(tier.clone(), "minPositionVal", &[]));
m.insert("maxNotional".to_string(), self.safe_number_k(tier.clone(), "maxPositionVal", &[]));
m.insert("maintenanceMarginRate".to_string(), self.safe_number_k(tier.clone(), "maintMarginRatio", &[]));
m.insert("maxLeverage".to_string(), Value::Null);
m.insert("info".to_string(), tier);
m
}));
}
}
return tiers;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut section = get_arg(optional_args, 0, 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 mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut type_var: Value = get_value(§ion, &Value::Int(0));
let mut version: Value = get_value(§ion, &Value::Int(1));
let mut access: Value = get_value(§ion, &Value::Int(2));
let mut isSandbox: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut url: Value = self.implode_hostname(get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), &type_var));
if (isSandbox.as_bool() == Some(true)) && (url == Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" does not have a testnet/sandbox URL for ".into())).into()), type_var).into()), Value::Str(" endpoints".into()))));
}
let mut pathValue: Value = self.implode_params(path, params.clone());
let mut versionIsTransfer: bool = version.as_str() == Some("transfer");
let mut versionIsAsset: bool = version.as_str() == Some("asset");
if versionIsTransfer || versionIsAsset {
if versionIsTransfer {
type_var = Value::Str("account/transfer".into());
} else {
type_var = Value::Str("api/asset".into());
}
version = get_value(§ion, &Value::Int(2));
access = get_value(§ion, &Value::Int(3));
}
let mut flatAccountPaths: Value = Value::from(vec![Value::Str("account/apiPermissions".into()), Value::Str("account/apiRestrictions".into())]);
if !(self.in_array(pathValue.clone(), flatAccountPaths).as_bool() == Some(true)) {
if (type_var.as_str() == Some("spot")) && (version.as_str() == Some("v3")) {
url = Value::Str(format!("{}{}", url, Value::Str("/api".into())).into());
} else {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("/".into()), type_var).into())).into());
}
}
url = Value::Str(format!("{}{}", url, add(&Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/".into()), version).into()), Value::Str("/".into())).into()), &pathValue)).into());
let mut requestHeaders: Value = Value::Null;
let mut requestBody: Value = Value::Null;
let mut paramsOmitted: Value = self.omit(params, self.extract_params(pathValue), &[]);
add_element_to_object(&mut paramsOmitted, &Value::Str("timestamp".into()), self.nonce());
let mut paramsSorted: Value = self.keysort(paramsOmitted, &[]);
if (access.as_str() == Some("public")) {
if ((object_keys(¶msSorted).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(paramsSorted.clone(), &[])).into())).into());
}
} else if (access.as_str() == Some("private")) {
self.check_required_credentials(&[]);
let mut isJsonContentType: bool = ((type_var.as_str() == Some("subAccount")) || (type_var.as_str() == Some("account/transfer"))) && (method.as_str() == Some("POST"));
let mut parsedParams: Value = Value::Null;
let mut encodeRequest: Value = Value::Null;
if isJsonContentType {
encodeRequest = self.custom_encode(paramsSorted.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
} else {
parsedParams = self.parse_params(paramsSorted.clone());
encodeRequest = self.rawencode(parsedParams.clone(), &[Value::Bool(true)]);
}
let mut encodeRequestSafe: Value = (if (encodeRequest == Value::Null) { Value::Str("".into()) } else { encodeRequest });
let mut signature: Value = self.hmac(self.encode(encodeRequestSafe), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-BX-APIKEY".to_string(), self.apiKey.clone());
m.insert("X-SOURCE-KEY".to_string(), self.safe_string_k(self.options.clone(), "broker", &[Value::Str("CCXT".into())]));
m
});
if isJsonContentType {
add_element_to_object(&mut requestHeaders, &Value::Str("Content-Type".into()), Value::Str("application/json".into()));
add_element_to_object(&mut paramsSorted, &Value::Str("signature".into()), signature.clone());
requestBody = json_stringify(¶msSorted);
} else {
let mut query: Value = self.urlencode(parsedParams, &[Value::Bool(true)]);
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("?".into()), query).into()), Value::Str("&".into())).into()), Value::Str("signature=".into())).into()), signature).into())).into());
}
}
let mut bodyResult: Value = (if (requestBody != Value::Null) { requestBody } else { body });
let mut headersResult: Value = (if (requestHeaders != Value::Null) { requestHeaders } else { headers });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyResult);
m.insert("headers".to_string(), headersResult);
m
});
Value::Null
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enable); }
}
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": 80014,
// "msg": "Invalid parameters, err:Key: 'GetTickerRequest.Symbol' Error:Field validation for "Symbol" failed on the "len=0|endswith=-USDT" tag",
// "data": {
// }
// }
//
let mut code: Value = self.safe_string_k(response.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(response.clone(), "msg", &[]);
let mut transferErrorMsg: Value = self.safe_string_k(response, "transferErrorMsg", &[]); // handling with errors from transfer endpoint
if (transferErrorMsg != Value::Null) || ((code != Value::Null) && (code.as_str() != Some("0"))) {
if (transferErrorMsg != Value::Null) {
message = transferErrorMsg;
}
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_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, 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());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}