// 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 WeexCore {
pub exchange: crate::exchange::Exchange,
}
impl WeexCore {
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 = WeexCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for WeexCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_funding_rate(self, rate, &[market])
}
fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_last_price(self, entry, &[market])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::parse_open_interest(self, interest, &[market])
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::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 WeexCore.
WeexCore::parse_margin_modification(self, data, &[market])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::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 WeexCore.
WeexCore::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 WeexCore.
WeexCore::parse_leverage(self, leverage, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on WeexCore.
WeexCore::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 WeexCore.
WeexCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for WeexCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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_contract_order" => self.create_contract_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_contract_order_request" => self.create_contract_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_spot_order" => self.create_spot_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_spot_order_request" => self.create_spot_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())..]),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_bids_asks" => self.fetch_bids_asks(&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_contract_ohlcv" => self.fetch_contract_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_last_prices" => self.fetch_last_prices(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_leverages" => self.fetch_leverages(&args[..]).await,
"fetch_margin_mode" => self.fetch_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_margin_modes" => self.fetch_margin_modes(&args[..]).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_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_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_order_trades" => self.fetch_order_trades(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_mode" => self.fetch_position_mode(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_for_symbol" => self.fetch_positions_for_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_spot_ohlcv" => self.fetch_spot_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_status" => self.fetch_status(&args[..]).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,
"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)),
"modify_margin_helper" => self.modify_margin_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"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_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_last_price" => self.parse_last_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_mode" => self.parse_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_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_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_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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())..]),
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for WeexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for WeexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl WeexCore {
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("weex".into()));
m.insert("name".to_string(), Value::Str("Weex".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("SG".into())]));
m.insert("rateLimit".to_string(), Value::Int(20));
m.insert("version".to_string(), Value::Str("v3".into()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(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("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelOrdersWithClientOrderId".to_string(), Value::Bool(true));
m.insert("cancelOrderWithClientOrderId".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(true));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createLimitBuyOrder".to_string(), Value::Bool(true));
m.insert("createLimitOrder".to_string(), Value::Bool(true));
m.insert("createLimitSellOrder".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrder".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrder".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrder".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(false));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(false));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLimitOrder".to_string(), Value::Bool(false));
m.insert("createStopLossOrder".to_string(), Value::Bool(true));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(true));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(false));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(false));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(false));
m.insert("editOrders".to_string(), Value::Bool(false));
m.insert("editOrderWithClientOrderId".to_string(), Value::Bool(false));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchADLRank".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".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("fetchClosedOrder".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchConvertCurrencies".to_string(), Value::Bool(false));
m.insert("fetchConvertQuote".to_string(), Value::Bool(false));
m.insert("fetchConvertTrade".to_string(), Value::Bool(false));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDeposit".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(false));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingInterval".to_string(), Value::Bool(false));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(true));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchIsolatedPositions".to_string(), Value::Bool(false));
m.insert("fetchL2OrderBook".to_string(), Value::Bool(false));
m.insert("fetchL3OrderBook".to_string(), Value::Bool(false));
m.insert("fetchLastPrices".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLedgerEntry".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverages".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatio".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatioHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(true));
m.insert("fetchMarginModes".to_string(), Value::Bool(true));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMarkPrice".to_string(), Value::Bool(true));
m.insert("fetchMarkPrices".to_string(), Value::Bool(true));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrder".to_string(), Value::Bool(false));
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("fetchOrderBooks".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchOrdersByStatus".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(true));
m.insert("fetchOrderWithClientOrderId".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionADLRank".to_string(), Value::Bool(false));
m.insert("fetchPositionHistory".to_string(), Value::Bool(false));
m.insert("fetchPositionMode".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsADLRank".to_string(), Value::Bool(false));
m.insert("fetchPositionsForSymbol".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(false));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTradingLimits".to_string(), Value::Bool(false));
m.insert("fetchTransactionFee".to_string(), Value::Bool(false));
m.insert("fetchTransactionFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchUnderlyingAssets".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawAddresses".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchWithdrawalWhitelist".to_string(), Value::Bool(false));
m.insert("privateAPI".to_string(), Value::Bool(false));
m.insert("publicAPI".to_string(), Value::Bool(false));
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(false));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(true));
m.insert("signIn".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(false));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/bc67b9f2-75d2-4b8d-963a-18f2fcd9d13c".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api-spot.weex.com".into()));
m.insert("private".to_string(), Value::Str("https://api-spot.weex.com".into()));
m.insert("contract".to_string(), Value::Str("https://api-contract.weex.com".into()));
m.insert("contractPrivate".to_string(), Value::Str("https://api-contract.weex.com".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api-spot.weex.com".into()));
m.insert("private".to_string(), Value::Str("https://api-spot.weex.com".into()));
m.insert("contract".to_string(), Value::Str("https://api-contract.weex.com".into()));
m.insert("contractPrivate".to_string(), Value::Str("https://api-contract.weex.com".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.weex.com".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://www.weex.com/api-doc".into())]));
m.insert("referral".to_string(), Value::Str("https://www.weex.com/register?vipCode=qfyh".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v3/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/coins".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("api/v3/exchangeInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(100));
m
}));
m.insert("api/v3/ping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/apiTradingSymbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("api/v3/market/ticker/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/market/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("api/v3/market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(125));
m
}));
m.insert("api/v3/market/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("api/v3/market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("api/v3/market/ticker/bookTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
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("api/v3/account/".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/account/transferRecords".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("api/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("api/v3/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("api/v3/allOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("api/v3/myTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/rebate/affiliate/getAffiliateUIDs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/rebate/affiliate/getChannelUserTradeAndAsset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/rebate/affiliate/getAffiliateCommission".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/rebate/affiliate/getInternalWithdrawalStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(100));
m
}));
m.insert("api/v3/rebate/affiliate/querySubChannelTransactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("api/v3/agency/verifyReferrals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/agency/getAssert".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/agency/getDealData".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("api/v3/apiReferral/checkUserEligibility".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/apiReferral/rebate/recentRecord".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/apiReferral/rebateRatio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/content/articles/detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v3/content/articles/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v3/content/articles/listByCoin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v3/content/banners/latest".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("api/v3/account/bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/account/fundingBills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api/v3/order/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("api/v3/rebate/affiliate/internalWithdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(100));
m
}));
m.insert("api/v3/tax/income".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v3/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v3/order/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
m
}));
m.insert("contract".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("capi/v3/market/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/exchangeInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(200));
m
}));
m.insert("capi/v3/market/ticker/bookTicker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("capi/v3/market/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/indexPriceKlines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/markPriceKlines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/historyKlines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("capi/v3/market/symbolPrice".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/openInterest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/market/premiumIndex".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/market/fundingRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("capi/v3/market/apiTradingSymbols".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m
}));
m
}));
m.insert("contractPrivate".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("capi/v3/account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/account/commissionRate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/account/accountConfig".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/account/symbolConfig".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/account/position/allPosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(15));
m
}));
m.insert("capi/v3/account/position/singlePosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("capi/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("capi/v3/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/userTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/openAlgoOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("capi/v3/allAlgoOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/sim/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/sim/position/allPosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(15));
m
}));
m.insert("capi/v3/sim/order/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/follower/historyOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/follower/myTraders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/follower/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/follower/settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/trader/historyOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/trader/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/trader/pairs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capi/v3/trailing/openOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("capi/v3/trailing/historyOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("capi/v3/account/income".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/account/marginType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("capi/v3/account/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("capi/v3/account/positionMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(30));
m
}));
m.insert("capi/v3/account/modifyAutoAppendMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(30));
m
}));
m.insert("capi/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/batchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/closePositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("capi/v3/algoOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/placeTpSlOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/modifyTpSlOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/sim/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("capi/v3/copy/follower/closePos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("capi/v3/copy/follower/settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/copy/follower/stopCopy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("capi/v3/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("capi/v3/batchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/allOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("capi/v3/algoOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("capi/v3/algoOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m
}));
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.insert("password".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".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("8h".to_string(), Value::Str("8h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".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("-1000".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("-1054".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("-1040".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1041".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1042".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1043".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1044".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1045".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1046".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1047".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1049".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("-1050".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1051".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1052".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1053".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1055".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1056".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1057".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1058".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-1115".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-1116".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-1117".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-1121".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("-1128".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1135".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1140".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1141".to_string(), Value::Str("ArgumentsRequired".into()).clone());
m.insert("-1142".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1150".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1160".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1170".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1171".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("-1180".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-1190".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-2007".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("-2200".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("-3006".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-3007".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-3200".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-3235".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-3236".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("-3313".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("-3613".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("FAILED_ORDER_NOT_FOUND".to_string(), Value::Str("OrderNotFound".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount not enough".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("INVALID_ARGUMENT".to_string(), Value::Str("BadRequest".into()).clone());
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.1".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.1".into()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.1".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.09".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.08".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2000000".into()), &[]), self.parse_number(Value::Str("0.06".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.05".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.04".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.03".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.1".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.08".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.07".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2000000".into()), &[]), self.parse_number(Value::Str("0.05".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.04".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.03".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.01".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0".into()), &[])])]));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.1".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.1".into()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.1".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.09".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.08".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2000000".into()), &[]), self.parse_number(Value::Str("0.06".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.05".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.04".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.03".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.1".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.08".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.07".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2000000".into()), &[]), self.parse_number(Value::Str("0.05".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.04".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.03".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.01".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0".into()), &[])])]));
m
}));
m
}));
m.insert("contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("feeSide".to_string(), Value::Str("quote".into()));
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.08".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.02".into()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.08".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.075".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.06".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.055".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("30000000".into()), &[]), self.parse_number(Value::Str("0.05".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.048".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0.045".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("300000000".into()), &[]), self.parse_number(Value::Str("0.042".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000000".into()), &[]), self.parse_number(Value::Str("0.04".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.02".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.018".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.018".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("30000000".into()), &[]), self.parse_number(Value::Str("0.016".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.016".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0.014".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("300000000".into()), &[]), self.parse_number(Value::Str("0.012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000000".into()), &[]), self.parse_number(Value::Str("0.01".into()), &[])])]));
m
}));
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("XBT".to_string(), Value::Str("XBT".into()));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("partner".to_string(), Value::Str("b-WEEX111125".into()));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".into()));
m.insert("trading".to_string(), Value::Str("spot".into()));
m.insert("fund".to_string(), Value::Str("funding".into()));
m.insert("funding".to_string(), Value::Str("funding".into()));
m.insert("swap".to_string(), Value::Str("contract".into()));
m.insert("contract".to_string(), Value::Str("contract".into()));
m.insert("futures".to_string(), Value::Str("contract".into()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BEP20".to_string(), Value::Str("BEP20(BSC)".into()));
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("POLYGON".to_string(), Value::Str("POLYGON(MATIC)".into()));
m.insert("MATIC".to_string(), Value::Str("POLYGON(MATIC)".into()));
m.insert("ARBITRUM".to_string(), Value::Str("ARBITRUM(ARB)".into()));
m.insert("SOL".to_string(), Value::Str("SOLANA(SOL)".into()));
m.insert("OP".to_string(), Value::Str("OPTIMISM(OP)".into()));
m.insert("OPTIMISM".to_string(), Value::Str("OPTIMISM(OP)".into()));
m.insert("AVAXC".to_string(), Value::Str("AVALANCHE_C(AVAX_C)".into()));
m
}));
m.insert("networksById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BEP20(BSC)".to_string(), Value::Str("BEP20".into()));
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("POLYGON(MATIC)".to_string(), Value::Str("MATIC".into()));
m.insert("ARBITRUM(ARB)".to_string(), Value::Str("ARBITRUM".into()));
m.insert("SOLANA(SOL)".to_string(), Value::Str("SOL".into()));
m.insert("OPTIMISM(OP)".to_string(), Value::Str("OP".into()));
m.insert("AVALANCHE_C(AVAX_C)".to_string(), Value::Str("AVAXC".into()));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".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("8h".to_string(), Value::Str("8h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m
}));
m.insert("contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".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("4h".to_string(), Value::Str("4h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m
}));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("test".to_string(), Value::Bool(false));
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(false));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("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(10));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
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(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.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(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(300));
m
}));
m
}));
m.insert("forDerivs".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(true));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
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(false));
m
}));
m.insert("price".to_string(), Value::Bool(false));
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(false));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("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(10));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
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("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
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("forDerivs".into()));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m
})]);
Value::Null
}
pub fn nonce(&self) -> Value {
return (match (&(self.milliseconds()), &(self.safe_integer_k(self.options.clone(), "timeDifference", &[Value::Int(0)]))) { (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::Null
}
/*
* @method
* @name weex#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://www.weex.com/api-doc/spot/ConfigAPI/Ping
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_api_v3_ping(&[params]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name weex#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://www.weex.com/api-doc/spot/ConfigAPI/GetServerTime
* @see https://www.weex.com/api-doc/contract/Market_API/GetServerTime
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', default is 'spot'
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTime".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 response: Value = Value::Null;
if (type_var.as_str() != Some("spot")) {
response = self.contract_get_capi_v3_market_time(&[paramsMarketType.clone()]).await;
} else {
response = self.public_get_api_v3_time(&[paramsMarketType]).await;
}
return self.safe_integer_k(response, "serverTime", &[]);
Value::Null
}
/*
* @method
* @name weex#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://www.weex.com/api-doc/spot/ConfigAPI/CurrencyInfo
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_api_v3_coins(&[params]).await;
return self.parse_currencies(response);
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 networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut chains: Value = self.safe_list_k(rawCurrency.clone(), "networkList", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1136: bool = true;
while { if !__for_first_1136 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1136 = false; j.as_f64().unwrap_or(f64::NAN) < ((chains.len() as i64) as f64) } {
let mut chain: Value = self.safe_dict(chains.clone(), j.clone(), &[]);
let mut networkId: Value = self.safe_string_k(chain.clone(), "network", &[]);
let mut networkCode: Value = self.network_id_to_code(&[networkId.clone(), code.clone()]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkCode), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), chain.clone());
m.insert("id".to_string(), networkId);
m.insert("network".to_string(), networkCode.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), self.safe_bool_k(chain.clone(), "depositEnable", &[]));
m.insert("withdraw".to_string(), self.safe_bool_k(chain.clone(), "withdrawEnable", &[]));
m.insert("fee".to_string(), self.safe_number_k(chain.clone(), "withdrawFee", &[]));
m.insert("precision".to_string(), self.safe_number_k(chain.clone(), "withdrawIntegerMultiple", &[]));
m.insert("isDefault".to_string(), self.safe_bool_k(chain.clone(), "isDefault", &[Value::Bool(false)]));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(chain.clone(), "withdrawMin", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(chain, "depositDust", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m
})); }
}
}
}
let mut networkKeys: Value = Value::Array(networks.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
let mut networksLength: f64 = ((networkKeys.len() as i64) as f64);
let mut emptyChains: bool = networksLength == 0.0; // non-functional coins
let mut valueForEmpty: Value = (if emptyChains { Value::Bool(false) } else { Value::Null });
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("type".to_string(), Value::Str("crypto".into()));
m.insert("name".to_string(), name);
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), valueForEmpty.clone());
m.insert("withdraw".to_string(), valueForEmpty);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("networks".to_string(), networks);
m
}));
Value::Null
}
/*
* @method
* @name weex#fetchMarkets
* @description retrieves data on all markets for exchagne
* @see https://www.weex.com/api-doc/spot/ConfigAPI/GetProductInfo // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetContractInfo // contract
* @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
}));
if matches!(self.safe_bool_k(self.options.clone(), "adjustForTimeDifference", &[Value::Bool(false)]), Value::Bool(true)) {
self.load_time_difference(&[]).await;
}
let mut promises: Value = Value::from(vec![self.public_get_api_v3_exchange_info(&[params.clone()]).await, self.contract_get_capi_v3_market_exchange_info(&[params]).await]);
let mut spotResponsecontractResponseVariable = promise_all(&promises).await;
let mut spotResponse: Value = spotResponsecontractResponseVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut contractResponse: Value = spotResponsecontractResponseVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut spotArray: Value = self.safe_list_k(spotResponse, "symbols", &[Value::from(vec![])]);
let mut contractArray: Value = self.safe_list_k(contractResponse, "symbols", &[Value::from(vec![])]);
let mut result: Value = self.array_concat(spotArray, contractArray);
return self.parse_markets(result);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
//
// spot
// {
// "symbol": "ETHUSDT",
// "status": "TRADING",
// "baseAsset": "ETH",
// "baseAssetPrecision": "8",
// "quoteAsset": "USDT",
// "quoteAssetPrecision": "8",
// "tickSize": "0.01",
// "stepSize": "0.00001",
// "minTradeAmount": "0.0001",
// "maxTradeAmount": "99999",
// "takerFeeRate": "0.001",
// "makerFeeRate": "0.001",
// "buyLimitPriceRatio": "0.1",
// "sellLimitPriceRatio": "0.1",
// "marketBuyLimitSize": "99999",
// "marketSellLimitSize": "99999",
// "marketFallbackPriceRatio": "0",
// "enableTrade": true,
// "enableDisplay": true,
// "displayDigitMerge": "0.01,0.1,0.5,1,5",
// "displayNew": false,
// "displayHot": false
// }
//
// contract
// {
// "symbol": "ETHUSDT",
// "baseAsset": "ETH",
// "quoteAsset": "USDT",
// "marginAsset": "USDT",
// "pricePrecision": "2",
// "quantityPrecision": "3",
// "baseAssetPrecision": "2",
// "quotePrecision": "8",
// "contractVal": "0.001",
// "delivery": [
// "00:00:00",
// "08:00:00",
// "16:00:00"
// ],
// "forwardContractFlag": true,
// "minLeverage": "1",
// "maxLeverage": "400",
// "buyLimitPriceRatio": "0.01",
// "sellLimitPriceRatio": "0.01",
// "makerFeeRate": "0.0002",
// "takerFeeRate": "0.0008",
// "minOrderSize": "0.001",
// "maxOrderSize": "1000000",
// "maxPositionSize": "5000000",
// "marketOpenLimitSize": "2300"
// }
//
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "baseAsset", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteAsset", &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "marginAsset", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut active: Value = Value::Bool(true);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut isSpot: Value = Value::Bool(true);
let mut isLinear: Value = Value::Null;
let mut isInverse: Value = Value::Null;
if (settle != Value::Null) {
symbol = Value::Str(format!("{}{}", symbol, Value::Str(format!("{}{}", Value::Str(":".into()), settle).into())).into());
isSpot = Value::Bool(false);
if (settle.as_str() == quote.as_str()) {
isLinear = Value::Bool(true);
isInverse = Value::Bool(false);
} else if (settle.as_str() == base.as_str()) {
isLinear = Value::Bool(false);
isInverse = Value::Bool(true);
}
} else {
active = self.safe_bool_k(market.clone(), "enableTrade", &[Value::Bool(false)]);
}
let mut amountPrecision: Value = self.safe_number_k(market.clone(), "stepSize", &[]);
let mut pricePrecision: Value = self.safe_number_k(market.clone(), "tickSize", &[]);
if (amountPrecision == Value::Null) {
let mut amountPrecisionString: Value = self.parse_precision(&[self.safe_string_k(market.clone(), "quantityPrecision", &[])]);
let mut pricePrecisionString: Value = self.parse_precision(&[self.safe_string_k(market.clone(), "pricePrecision", &[])]);
amountPrecision = self.parse_number(amountPrecisionString, &[]);
pricePrecision = self.parse_number(pricePrecisionString, &[]);
}
let mut fees: Value = self.safe_dict(self.fees.clone(), (if isSpot.as_bool() == Some(true) { Value::Str("spot".into()) } else { Value::Str("contract".into()) }), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" method() missing id".into()))));
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("lowercaseId".to_string(), id.as_str().map(|__s| Value::Str(__s.to_lowercase().into())).unwrap_or(Value::Null));
m.insert("numericId".to_string(), self.safe_integer_k(market.clone(), "contractId", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), (if isSpot.as_bool() == Some(true) { Value::Str("spot".into()) } else { Value::Str("swap".into()) }));
m.insert("spot".to_string(), isSpot.clone());
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(!(isSpot.as_bool() == Some(true))));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active);
m.insert("contract".to_string(), Value::Bool(!(isSpot.as_bool() == Some(true))));
m.insert("linear".to_string(), isLinear);
m.insert("inverse".to_string(), isInverse);
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "takerFeeRate", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "makerFeeRate", &[]));
m.insert("feeSide".to_string(), fees.as_map().and_then(|__m| __m.get("feeSide")).cloned().unwrap_or(Value::Null));
m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contractVal", &[]));
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(), amountPrecision);
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(), self.safe_number_k(market.clone(), "minLeverage", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "maxLeverage", &[]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number2(market.clone(), Value::Str("minTradeAmount".into()), Value::Str("minOrderSize".into()), &[]));
m.insert("max".to_string(), self.safe_number2(market.clone(), Value::Str("maxTradeAmount".into()), Value::Str("maxOrderSize".into()), &[]));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("percentage".to_string(), fees.as_map().and_then(|__m| __m.get("percentage")).cloned().unwrap_or(Value::Null));
m.insert("tierBased".to_string(), fees.as_map().and_then(|__m| __m.get("tierBased")).cloned().unwrap_or(Value::Null));
m.insert("tiers".to_string(), fees.as_map().and_then(|__m| __m.get("tiers")).cloned().unwrap_or(Value::Null));
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
/*
* @method
* @name weex#fetchTickers
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetAllTickerInfo // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetTicker24h // contract
* @param {string} symbols unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', default is 'spot' (used if symbols are not provided)
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTickers".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 symbolsLength: Value = Value::Int(0);
if (symbolsNormalized != Value::Null) {
symbolsLength = Value::Int(symbolsNormalized.len() as i64);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbolsLength.as_f64() == Some(1.0)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), self.safe_string_k(market, "id", &[])); }
}
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
//
// [
// {
// "symbol": "ETHUSDT",
// "priceChange": "-72.98",
// "priceChangePercent": "-0.033811",
// "lastPrice": "2085.46",
// "bidPrice": "2085.44",
// "bidQty": "1.53848",
// "askPrice": "2085.47",
// "askQty": "1.87504",
// "openPrice": "2158.44",
// "highPrice": "2168.40",
// "lowPrice": "2061.12",
// "volume": "157359.56105",
// "quoteVolume": "331284305.7193626",
// "openTime": 1775493000000,
// "closeTime": 1775579400000,
// "count": 59727
// }
// ]
//
let __ws_arg_0 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.public_get_api_v3_market_ticker24hr(&[__ws_arg_0]).await;
} else {
//
// [
// {
// "symbol": "ETHUSDT",
// "priceChange": "-75.49",
// "priceChangePercent": "-0.034992",
// "lastPrice": "2081.80",
// "openPrice": "2157.29",
// "highPrice": "2167.51",
// "lowPrice": "2059.17",
// "volume": "623160.426",
// "quoteVolume": "1310647345.19346",
// "openTime": 1775493000000,
// "closeTime": 1775579400000,
// "markPrice": "2081.8",
// "indexPrice": "2082.75"
// }
// ]
//
let __ws_arg_1 = self.extend(request, &[paramsMarketType]);
response = self.contract_get_capi_v3_market_ticker24hr(&[__ws_arg_1]).await;
}
if !(matches!(&response, Value::Arr(_))) {
response = Value::from(vec![response.clone()]);
}
return self.parse_tickers(response, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name weex#fetchBidsAsks
* @description fetches the bid and ask price and volume for multiple markets
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetBookTicker // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetBookTicker // contract
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', default is 'spot' (used if symbols are not provided)
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_bids_asks(&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::Null, Value::Bool(true), Value::Bool(true)]);
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchBidsAsks".into()), &[market, 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 response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
response = self.public_get_api_v3_market_ticker_book_ticker(&[paramsMarketType.clone()]).await;
} else {
response = self.contract_get_capi_v3_market_ticker_book_ticker(&[paramsMarketType]).await;
}
if !(matches!(&response, Value::Arr(_))) {
response = Value::from(vec![response.clone()]);
}
let mut results: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1137: bool = true;
while { if !__for_first_1137 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1137 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
let mut rawTicker: Value = response.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
// book tickers have no markPrice, so resolve the market from the endpoint type to disambiguate the spot/swap market id in parseTicker
let mut marketId: Value = self.safe_string_k(rawTicker.clone(), "symbol", &[]);
let mut tickerMarket: Value = self.safe_market(&[marketId, Value::Null, Value::Null, marketType.clone()]);
results.push(self.parse_ticker(rawTicker, &[tickerMarket]));
}
}
return self.filter_by_array_tickers(Value::from(results), Value::Str("symbol".into()), &[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);
//
// spot
// {
// "symbol": "ETHUSDT",
// "priceChange": "-72.98",
// "priceChangePercent": "-0.033811",
// "lastPrice": "2085.46",
// "bidPrice": "2085.44",
// "bidQty": "1.53848",
// "askPrice": "2085.47",
// "askQty": "1.87504",
// "openPrice": "2158.44",
// "highPrice": "2168.40",
// "lowPrice": "2061.12",
// "volume": "157359.56105",
// "quoteVolume": "331284305.7193626",
// "openTime": 1775493000000,
// "closeTime": 1775579400000,
// "count": 59727
// }
//
// swap
// {
// "symbol": "ETHUSDT",
// "priceChange": "-75.49",
// "priceChangePercent": "-0.034992",
// "lastPrice": "2081.80",
// "openPrice": "2157.29",
// "highPrice": "2167.51",
// "lowPrice": "2059.17",
// "volume": "623160.426",
// "quoteVolume": "1310647345.19346",
// "openTime": 1775493000000,
// "closeTime": 1775579400000,
// "markPrice": "2081.8",
// "indexPrice": "2082.75"
// }
//
// fetchMarkPrice (markPrice or indexPrice is copied from the raw 'price' field by fetchMarkPrice before parsing, depending on the requested priceType)
// {
// "symbol": "ETHUSDT",
// "price": "1929.18",
// "markPrice": "1929.18",
// "time": 1786347445044
// }
//
// fetchMarkPrices
// {
// "symbol": "ETHUSDT",
// "markPrice": "1929.88",
// "indexPrice": "1930.15",
// "forecastFundingRate": "0.00003489",
// "lastFundingRate": "0.00004879",
// "interestRate": "0.001",
// "nextFundingTime": 1786348800000,
// "time": 1786347284100,
// "collectCycle": 480
// }
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
let mut markPrice: Value = self.safe_string_k(ticker.clone(), "markPrice", &[]);
let mut marketType: Value = Value::Str("spot".into());
if (markPrice != Value::Null) || ((market != Value::Null) && (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) {
// 24hr swap tickers carry markPrice, but book tickers do not, so also honor the market resolved by the caller
marketType = Value::Str("swap".into());
}
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, marketType]);
let mut timestamp: Value = self.safe_integer2(ticker.clone(), Value::Str("closeTime".into()), Value::Str("time".into()), &[]);
let mut percentage: Value = crate::precise::Precise::stringMul(&self.safe_string_k(ticker.clone(), "priceChangePercent", &[]), &Value::Str("100".into()));
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), self.safe_string_k(ticker.clone(), "highPrice", &[]));
m.insert("low".to_string(), self.safe_string_k(ticker.clone(), "lowPrice", &[]));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bidPrice", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "bidQty", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "askPrice", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "askQty", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), self.safe_string_k(ticker.clone(), "lastPrice", &[]));
m.insert("last".to_string(), self.safe_string_k(ticker.clone(), "lastPrice", &[]));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), self.safe_string_k(ticker.clone(), "priceChange", &[]));
m.insert("percentage".to_string(), percentage);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string_k(ticker.clone(), "volume", &[]));
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "quoteVolume", &[]));
m.insert("markPrice".to_string(), 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 weex#fetchLastPrices
* @description fetches the last price for multiple markets
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetTickerInfo
* @param {string[]} [symbols] unified symbols of the markets to fetch the last prices for, all spot markets are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of lastprice structures
*/
pub async fn fetch_last_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 symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchLastPrices".into()), &[market, params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() != Some("spot")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchLastPrices() supports spot markets only, use fetchMarkPrices() or fetchTickers() for contract markets".into()))));
}
let mut response: Value = self.public_get_api_v3_market_ticker_price(&[paramsMarketType]).await;
return self.parse_last_prices(response, &[symbolsNormalized]);
Value::Null
}
pub fn parse_last_price(&self, mut entry: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "symbol": "ETHUSDT",
// "price": "1929.67"
// }
//
let mut marketId: Value = self.safe_string_k(entry.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, Value::Str("spot".into())]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("price".to_string(), self.safe_number_omit_zero(entry.clone(), Value::Str("price".into()), &[]));
m.insert("side".to_string(), Value::Null);
m.insert("info".to_string(), entry);
m
});
Value::Null
}
/*
* @method
* @name weex#fetchMarkPrice
* @description fetches mark price for the market
* @see https://www.weex.com/api-doc/contract/Market_API/GetSymbolPrice
* @param {string} symbol unified symbol of the market to fetch the mark price for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.priceType] "MARK" (default) or "INDEX", with "INDEX" the price is returned as the indexPrice of the ticker
* @returns {object} a [ticker structure]{@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);
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchMarkPrice() supports contract markets only".into()))));
}
let mut priceTypeparamsPriceTypeVariable = self.handle_option_string_and_params(params, Value::Str("fetchMarkPrice".into()), Value::Str("priceType".into()), &[Value::Str("MARK".into())]);
let mut priceType: Value = priceTypeparamsPriceTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPriceType: Value = priceTypeparamsPriceTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); // the endpoint defaults to INDEX
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("priceType".to_string(), priceType.clone());
m
});
let __ws_arg_2 = self.extend(request, &[paramsPriceType]);
let mut response: Value = self.contract_get_capi_v3_market_symbol_price(&[__ws_arg_2]).await;
//
// {
// "symbol": "ETHUSDT",
// "price": "1929.18",
// "time": 1786347445044
// }
//
// normalize here instead of falling back to 'price' in parseTicker, so a bare 'price' field in other payloads can never silently become the mark price
let mut ticker: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[response]);
if (priceType.as_str() == Some("INDEX")) {
{ let __be_tmp = self.safe_string_k(ticker.clone(), "price", &[]); if let Value::Dict(__d) = &mut ticker { std::sync::Arc::make_mut(__d).insert("indexPrice".into(), __be_tmp); } }
} else {
{ let __be_tmp = self.safe_string_k(ticker.clone(), "price", &[]); if let Value::Dict(__d) = &mut ticker { std::sync::Arc::make_mut(__d).insert("markPrice".into(), __be_tmp); } }
}
return self.parse_ticker(ticker, &[market]);
Value::Null
}
/*
* @method
* @name weex#fetchMarkPrices
* @description fetches mark prices for multiple markets
* @see https://www.weex.com/api-doc/contract/Market_API/GetCurrentFundingRate
* @param {string[]} [symbols] unified symbols of the markets to fetch the mark prices for, all contract markets 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 symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Str("swap".into())]); // reject non-contract symbols instead of silently filtering the result to an empty dict
let mut response: Value = self.contract_get_capi_v3_market_premium_index(&[params]).await;
return self.parse_tickers(response, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name weex#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetDepthData // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetDepthData // contract
* @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 (default 15, max 200)
* @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.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) && (limit.as_f64().unwrap_or(f64::NAN) > ((15i64) as f64)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Int(200)); }; // default is 15, max is 200
}
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_3 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_api_v3_market_depth(&[__ws_arg_3]).await;
} else {
let __ws_arg_4 = self.extend(request, &[params]);
response = self.contract_get_capi_v3_market_depth(&[__ws_arg_4]).await;
}
//
// {
// "asks": [
// [
// "2096.77",
// "45.592"
// ]
// ],
// "bids": [
// [
// "2096.76",
// "49.162"
// ]
// ],
// "lastUpdateId": 14138610208
// }
//
let mut orderbook: Value = self.parse_order_book(response.clone(), symbol, &[]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer_k(response, "lastUpdateId", &[]));
return orderbook;
Value::Null
}
/*
* @method
* @name weex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetKLineData // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetKlines // contract last price
* @see https://www.weex.com/api-doc/contract/Market_API/GetIndexPriceKlines // contract index price
* @see https://www.weex.com/api-doc/contract/Market_API/GetMarkPriceKlines // contract mark price
* @see https://www.weex.com/api-doc/contract/Market_API/GetHistoryKlines // contract historical klines
* @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 (default 100, max 300)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* Check fetchSpotOHLCV() and fetchContractOHLCV() for more details on the extra parameters that can be used in 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());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
return self.fetch_spot_ohlcv(symbol.clone(), &[timeframe.clone(), since.clone(), limit.clone(), params.clone()]).await;
} else {
return self.fetch_contract_ohlcv(symbol, &[timeframe, since, limit, params]).await;
}
Value::Null
}
/*
* @method
* @ignore
* @name weex#fetchSpotOHLCV
* @description helper method for fetchOHLCV
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetKLineData
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_spot_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v3_market_klines(&[__ws_arg_5]).await;
return self.parse_ohlc_vs(self.to_array(response), &[market, timeframe, since, limit]);
Value::Null
}
/*
* @method
* @ignore
* @name weex#fetchContractOHLCV
* @description helper method for fetchOHLCV
* @see https://www.weex.com/api-doc/contract/Market_API/GetKlines // contract last price
* @see https://www.weex.com/api-doc/contract/Market_API/GetIndexPriceKlines // contract index price
* @see https://www.weex.com/api-doc/contract/Market_API/GetMarkPriceKlines // contract mark price
* @see https://www.weex.com/api-doc/contract/Market_API/GetHistoryKlines // contract historical klines
* @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 (default 100, max 100 for historical klines, max 1000 for other contract klines)
* @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] whether to automatically paginate requests until the required number of candles is returned
* @param {boolean} [params.historical] whether to fetch historical klines (default is false, forced to true when since or until is set because the recent klines endpoints ignore time filters). If false, will fetch last price klines
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_contract_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 maxHistoricalLimit: Value = Value::Int(100);
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 paginate.as_bool() == Some(true) {
let mut paramsExtended: Value = self.extend(paramsPaginate.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("historical".to_string(), Value::Bool(true));
m
})]);
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), paramsExtended, maxHistoricalLimit.clone()]).await;
}
let mut until: Value = self.safe_integer_k(paramsPaginate.clone(), "until", &[]);
let mut historicalparamsHistoricalVariable = self.handle_option_bool_and_params(paramsPaginate, Value::Str("fetchOHLCV".into()), Value::Str("historical".into()), &[Value::Bool(false)]);
let mut historical: Value = historicalparamsHistoricalVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsHistorical: Value = historicalparamsHistoricalVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut timeframeOption: Value = self.safe_dict_k(self.options.clone(), "timeframes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut contractTimeframes: Value = self.safe_dict_k(timeframeOption, "contract", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
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("interval".to_string(), self.safe_string(contractTimeframes, timeframe.clone(), &[timeframe.clone()]));
m
});
let mut priceType: Value = self.safe_string_upper_k(paramsHistorical.clone(), "price", &[]);
let mut paramsOmitted: Value = self.omit(paramsHistorical, Value::from(vec![Value::Str("historical".into()), Value::Str("until".into()), Value::Str("price".into())]), &[]);
let mut response: Value = Value::Null;
// hardcap threshold
let mut limitResolved: Value = (if (limit == Value::Null) { Value::Null } else { crate::runtime::Math::min(&limit, &Value::Int(1000)) });
// the recent-klines endpoints ignore startTime and endTime and only ever return the
// latest candles, so a request bounded by since or until has to go through the history
// endpoint, which honours both (endTime = since + limit * timeframe when until is absent)
let mut useHistory: bool = historical.as_bool() == Some(true) || (since != Value::Null) || (until != Value::Null);
if useHistory {
if (priceType != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("priceType".into(), priceType.clone()); }
}
let mut startTime: Value = since.clone();
let mut endTime: Value = until.clone();
let mut now: Value = self.milliseconds();
if (since == Value::Null) || (until == 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 });
// the history endpoint returns at most maxHistoricalLimit candles and serves the
// newest ones inside the window, so a wider window would silently drop the candles
// right after since, keep the window at what one call can return
let mut historyLimit: Value = maxHistoricalLimit.clone();
if (limit != Value::Null) && (limit != Value::Null) && (limit.as_f64() != Some(0.0)) {
historyLimit = crate::runtime::Math::min(&limit, &maxHistoricalLimit);
}
let mut timeDelta: Value = (match (&(historyLimit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
if (since == Value::Null) && (until == Value::Null) {
endTime = now.clone();
startTime = (match (&(now), &(timeDelta)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
} else if (since == Value::Null) {
if (until == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() requires a since or until argument".into()))));
}
startTime = (match (&(until), &(timeDelta)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
} else {
// this.sum, a bare + is string concatenation in the php port
endTime = self.sum(&[since.clone(), timeDelta]);
}
}
// the endpoint rejects an endTime in the future (-1142), which a recent since would produce
if (endTime != Value::Null) && (endTime.as_f64().unwrap_or(f64::NAN) > now.as_f64().unwrap_or(f64::NAN)) {
endTime = now;
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), startTime); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), endTime); }
let __ws_arg_6 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.contract_get_capi_v3_market_history_klines(&[__ws_arg_6]).await;
} else {
if (limitResolved != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limitResolved.clone()); }
}
if (priceType.as_str() == Some("MARK")) {
let __ws_arg_7 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.contract_get_capi_v3_market_mark_price_klines(&[__ws_arg_7]).await;
} else if (priceType.as_str() == Some("INDEX")) {
let __ws_arg_8 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.contract_get_capi_v3_market_index_price_klines(&[__ws_arg_8]).await;
} else {
let __ws_arg_9 = self.extend(request, &[paramsOmitted]);
response = self.contract_get_capi_v3_market_klines(&[__ws_arg_9]).await;
}
}
return self.parse_ohlc_vs(self.to_array(response), &[market, timeframe, since, limitResolved]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer(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, Value::Int(5), &[])]);
Value::Null
}
/*
* @method
* @name weex#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.weex.com/api-doc/spot/MarketDataAPI/GetTradeData // spot
* @see https://www.weex.com/api-doc/contract/Market_API/GetRecentTrades // contract
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch (default 100, max 1000)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }
}
let 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_10 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_api_v3_market_trades(&[__ws_arg_10]).await;
} else {
let __ws_arg_11 = self.extend(request, &[params]);
response = self.contract_get_capi_v3_market_trades(&[__ws_arg_11]).await;
}
//
// [
// {
// "id": "875fba11-f8a1-42ad-915d-012ccb375e8a",
// "price": "2114.77",
// "qty": "0.01000",
// "quoteQty": "21.1477000",
// "time": 1775594995485,
// "isBuyerMaker": false,
// "isBestMatch": true
// }
// ]
//
let mut responseList: Value = Value::from(vec![]);
if (response != Value::Null) {
responseList = self.to_array(response);
}
return self.parse_trades(responseList, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades
// {
// "id": "875fba11-f8a1-42ad-915d-012ccb375e8a",
// "price": "2114.77",
// "qty": "0.01000",
// "quoteQty": "21.1477000",
// "time": 1775594995485,
// "isBuyerMaker": false,
// "isBestMatch": true
// }
//
// fetchMyTrades (spot)
// {
// "symbol": "DOGEUSDT",
// "id": 736825748291060702,
// "orderId": 736825748215563230,
// "price": "0.09349",
// "qty": "250.0",
// "quoteQty": "23.3725",
// "commission": "0.0233725",
// "time": 1775672947953,
// "isBuyer": false
// }
//
// fetchMyTrades (contract)
// {
// "id": 737074389731770728,
// "orderId": 737074043320009064,
// "symbol": "DOGEUSDT",
// "buyer": true,
// "commission": "0.00183500",
// "commissionAsset": "USDT",
// "maker": true,
// "price": "0.09175",
// "qty": "100",
// "quoteQty": "9.17500",
// "realizedPnl": "0",
// "side": "BUY",
// "positionSide": "LONG",
// "time": 1775732228692
// }
//
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "time", &[]);
let mut isBuyer: Value = self.safe_bool_k(trade.clone(), "isBuyer", &[]);
let mut side: Value = self.safe_string_lower_k(trade.clone(), "side", &[]);
let mut isBuyerMaker: Value = self.safe_bool_k(trade.clone(), "isBuyerMaker", &[]);
if (isBuyer != Value::Null) {
side = (if isBuyer.as_bool() == Some(true) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
} else if (isBuyerMaker != Value::Null) {
side = (if isBuyerMaker.as_bool() == Some(true) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut tradeMarketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut realizedPnl: Option<String> = self.safe_string_k(trade.clone(), "realizedPnl", &[]).as_str().map(str::to_owned);
let mut tradeMarketType: Value = Value::Str("spot".into());
if (realizedPnl.is_some()) {
tradeMarketType = Value::Str("swap".into());
}
let mut marketResolved: Value = self.safe_market(&[(if (market == Value::Null) { tradeMarketId } else { Value::Null }), market.clone(), Value::Null, tradeMarketType.clone()]);
let mut isSpot: Value = Value::Null;
if (market == Value::Null) {
isSpot = Value::Bool(tradeMarketType.as_str() == Some("spot"));
} else {
isSpot = market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null);
}
let mut fee: Value = Value::Null;
let mut commission: Value = self.safe_string_k(trade.clone(), "commission", &[]);
if (commission != Value::Null) {
let mut commissionAsset: Value = self.safe_string_k(trade.clone(), "commissionAsset", &[]);
let mut feeCurrency: Value = self.safe_currency_code(commissionAsset, &[]);
if (isSpot.as_bool() == Some(true)) {
if (side.as_str() == Some("buy")) {
feeCurrency = self.safe_string_k(marketResolved.clone(), "base", &[]);
} else {
feeCurrency = self.safe_string_k(marketResolved.clone(), "quote", &[]);
}
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), commission);
m.insert("currency".to_string(), feeCurrency);
m
});
}
let mut isMaker: Value = self.safe_bool_k(trade.clone(), "maker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (isMaker != Value::Null) {
takerOrMaker = (if isMaker.as_bool() == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
} else if (isBuyerMaker != Value::Null) {
takerOrMaker = Value::Str("taker".into());
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "id", &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "orderId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_string_k(trade.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade.clone(), "qty", &[]));
m.insert("cost".to_string(), self.safe_string_k(trade, "quoteQty", &[]));
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name weex#fetchOpenInterest
* @description retrieves the open interest of a contract trading pair
* @see https://www.weex.com/api-doc/contract/Market_API/GetOpenInterest
* @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 __ws_arg_12 = self.extend(request, &[params]);
let mut response: Value = self.contract_get_capi_v3_market_open_interest(&[__ws_arg_12]).await;
return self.parse_open_interest(response, &[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);
//
// {
// "symbol": "ETHUSDT",
// "openInterest": "1772356.352",
// "time": 1775595582598
// }
//
let mut marketId: Value = self.safe_string_k(interest.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone(), Value::Null, Value::Str("swap".into())]);
let mut timestamp: Value = self.safe_integer_k(interest.clone(), "time", &[]);
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("openInterestAmount".to_string(), self.safe_string_k(interest.clone(), "openInterest", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
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 weex#fetchFundingRates
* @description fetch the funding rate for multiple markets
* @see https://www.weex.com/api-doc/contract/Market_API/GetCurrentFundingRate
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subType] "linear" or "inverse"
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rates-structure}, indexed by market symbols
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut symbolsLength: Value = Value::Int(0);
if (symbolsNormalized != Value::Null) {
symbolsLength = Value::Int(symbolsNormalized.len() as i64);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbolsLength.as_f64() == Some(1.0)) {
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), self.safe_string_k(market, "id", &[])); }
}
let __ws_arg_13 = self.extend(request, &[params]);
let mut response: Value = self.contract_get_capi_v3_market_premium_index(&[__ws_arg_13]).await;
return self.parse_funding_rates(response, &[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);
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market, Value::Null, Value::Str("swap".into())]);
let mut timestamp: Value = self.safe_integer_k(contract.clone(), "time", &[]);
let mut nextFundingTimestamp: Value = self.safe_integer_k(contract.clone(), "nextFundingTime", &[]);
let mut interval: Value = Value::Null;
let mut collectCycle: Value = self.safe_string_k(contract.clone(), "collectCycle", &[]);
if (collectCycle != Value::Null) {
interval = crate::precise::Precise::stringDiv(&collectCycle, &Value::Str("60".into()));
interval = 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(), symbol);
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(), self.safe_number_k(contract.clone(), "interestRate", &[]));
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("fundingRate".to_string(), self.safe_number_k(contract.clone(), "lastFundingRate", &[]));
m.insert("fundingTimestamp".to_string(), timestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(timestamp));
m.insert("nextFundingRate".to_string(), self.safe_number_k(contract, "forecastFundingRate", &[]));
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(), interval);
m
});
Value::Null
}
/*
* @method
* @name weex#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://www.weex.com/api-doc/contract/Market_API/GetFundingRateHistory
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of funding rate records to fetch (default 100, 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
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut 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_14 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.contract_get_capi_v3_market_funding_rate(&[__ws_arg_14]).await;
return self.parse_funding_rate_histories(response, &[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": "ETHUSDT",
// "fundingRate": "0.00001031",
// "fundingTime": 1775577600000,
// "markPrice": "2079.26"
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market, Value::Null, Value::Str("swap".into())]);
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(), symbol);
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 weex#fetchBalance
* @see https://www.weex.com/api-doc/spot/AccountAPI/GetAccountBalance // spot
* @see https://www.weex.com/api-doc/contract/Account_API/GetAccountBalance // contract
* @see https://www.weex.com/api-doc/contract/demo/GetAccountBalance // contract in sandbox mode
* @description query for balance and get the amount of funds available for trading or funds locked in positions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap' (default is 'spot', in sandbox mode only 'swap' is available and is used by default)
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut requestedType: Option<String> = self.safe_string_k(params.clone(), "type", &[]).as_str().map(str::to_owned);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchBalance".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 sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
// the demo trading API only provides the swap account, don't let the default spot type break a bare fetchBalance() call
let mut type_var: Value = marketType;
if sandboxMode.as_bool() == Some(true) && (requestedType.is_none()) {
type_var = Value::Str("swap".into());
}
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
if sandboxMode.as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance() only supports the swap account in sandbox mode, use params[\"type\"] = \"swap\"".into()))));
}
//
// {
// "makerCommission": 0,
// "takerCommission": 0,
// "commissionRates": {
// "maker": "0.00000000",
// "taker": "0.00000000"
// },
// "canTrade": true,
// "canWithdraw": true,
// "canDeposit": true,
// "updateTime": 1775601317093,
// "accountType": "SPOT",
// "balances": [
// {
// "asset": "USDT",
// "free": "20.00000000",
// "locked": "0"
// }
// ],
// "permissions": [
// "SPOT"
// ],
// "uid": 8886281669
// }
//
response = self.private_get_api_v3_account(&[paramsMarketType.clone()]).await;
} else {
//
// [
// {
// "asset": "USDT", // SUSDT in sandbox mode
// "balance": "20.00000000",
// "availableBalance": "20.00000000",
// "frozen": "0",
// "unrealizePnl": "0"
// }
// ]
//
if sandboxMode.as_bool() == Some(true) {
response = self.contract_private_get_capi_v3_sim_balance(&[paramsMarketType.clone()]).await;
} else {
response = self.contract_private_get_capi_v3_account_balance(&[paramsMarketType]).await;
}
}
return self.parse_balance(response);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut balances: Value = self.safe_list_k(response.clone(), "balances", &[response.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1138: bool = true;
while { if !__for_first_1138 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1138 = false; i.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut entry: Value = self.safe_dict(balances.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(entry.clone(), "asset", &[]);
if sandboxMode.as_bool() == Some(true) && (currencyId.as_str() == Some("SUSDT")) {
currencyId = Value::Str("USDT".into()); // demo trading balances are denominated in the demo asset SUSDT
}
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string2(entry.clone(), Value::Str("availableBalance".into()), Value::Str("free".into()), &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string2(entry.clone(), Value::Str("frozen".into()), Value::Str("locked".into()), &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(entry, "balance", &[])); }
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 weex#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://www.weex.com/api-doc/spot/AccountAPI/TransferRecords
* @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 {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 {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 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 paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchTransfers".into()), &[code, since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit]).await;
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".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 requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("before".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_15 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.private_get_api_v3_account_transfer_records(&[__ws_arg_15]).await;
return self.parse_transfers(response, &[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 timestamp: Value = self.safe_integer_k(transfer.clone(), "tradeTime", &[]);
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "coinName", &[]);
let mut currencyCode: Value = self.safe_currency_code(currencyId, &[currency]);
let mut status: Value = self.safe_string_k(transfer.clone(), "status", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), Value::Null);
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.clone(), "amount", &[]));
m.insert("fromAccount".to_string(), self.safe_string_lower_k(transfer.clone(), "fromType", &[]));
m.insert("toAccount".to_string(), self.safe_string_lower_k(transfer, "toType", &[]));
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("Successful".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name weex#createOrder
* @description Create an order on the exchange
* @see https://www.weex.com/api-doc/spot/orderApi/PlaceOrder // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceOrder // contract
* @see https://www.weex.com/api-doc/contract/Transaction_API/PlacePendingOrder // contract trigger
* @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceTpSlOrder // contract take profit / stop loss
* @see https://www.weex.com/api-doc/contract/demo/PlaceOrder // contract in sandbox mode
* @param {string} symbol Unified CCXT market symbol
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount the amount of currency to trade
* @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
* Check createSpotOrder() and createContractOrder() for more details on the extra parameters that can be used in params
* @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());
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
return self.create_contract_order(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]).await;
} else {
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if sandboxMode.as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() only supports swap markets in sandbox mode".into()))));
}
return self.create_spot_order(symbol, type_var, side, amount, &[price, params]).await;
}
Value::Null
}
/*
* @method
* @name weex#createSpotOrder
* @description helper method for creating spot orders
* @see https://www.weex.com/api-doc/spot/orderApi/PlaceOrder
* @param {string} symbol Unified CCXT market symbol
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount the amount of currency to trade
* @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] client order id
* @param {string} [params.timeInForce] 'GTC', 'IOC', or 'FOK'
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_spot_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 request: Value = self.create_spot_order_request(symbol, type_var, side, amount, &[price, params]);
let mut response: Value = self.private_post_api_v3_order(&[request]).await;
//
// {
// "symbol": "DOGEUSDT",
// "orderId": 736557215397183592,
// "clientOrderId": "c4551206d34641efbeb64abaa066946d",
// "transactTime": 1775608924724
// }
//
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" parseOrder() returned empty response".into()))));
}
return self.parse_order(response, &[market]);
Value::Null
}
pub fn create_spot_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createSpotOrderRequest() requires a side argument".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), side.as_str().map(|__s| Value::Str(__s.to_uppercase().into())).unwrap_or(Value::Null));
m.insert("type".to_string(), type_var.as_str().map(|__s| Value::Str(__s.to_uppercase().into())).unwrap_or(Value::Null));
m.insert("quantity".to_string(), self.amount_to_precision(symbol.clone(), amount));
m
});
if (type_var.as_str() == Some("limit")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol, price)); }
}
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("clientOrderId".into()), &[]);
if (clientOrderId == Value::Null) {
let mut partner: Value = self.safe_string_k(paramsOmitted.clone(), "partner", &[Value::Str("b-WEEX111125".into())]);
clientOrderId = Value::Str(format!("{}{}", Value::Str(format!("{}{}", partner, Value::Str("-".into())).into()), self.uuid22(&[])).into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newClientOrderId".into(), clientOrderId); }
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name weex#createContractOrder
* @description helper method for creating contract orders
* @see https://www.weex.com/api-doc/contract/Transaction_API/PlaceOrder
* @see https://www.weex.com/api-doc/contract/Transaction_API/PlacePendingOrder
* @see https://www.weex.com/api-doc/contract/demo/PlaceOrder // sandbox mode
* @param {string} symbol Unified CCXT market symbol
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount the amount of currency to trade
* @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] client order id
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered and the triggerPriceType
* @param {float} [params.takeProfit.triggerPrice] The price at which the take profit order will be triggered, takeProfit.stopPrice is supported as an alias
* @param {string} [params.takeProfit.triggerPriceType] The type of the trigger price for the take profit order, either 'last' or 'mark' (default is 'last')
* @param {float} [params.takeProfit.price] not supported, the attached take profit always executes at market price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered and the triggerPriceType
* @param {float} [params.stopLoss.triggerPrice] The price at which the stop loss order will be triggered, stopLoss.stopPrice is supported as an alias
* @param {string} [params.stopLoss.triggerPriceType] The type of the trigger price for the stop loss order, either 'last' or 'mark' (default is 'last')
* @param {float} [params.stopLoss.price] not supported, the attached stop loss always executes at market price
* @param {float} [params.stopLossPrice] price to trigger a standalone stop-loss order on an open position, the price argument is used as its execution price for limit orders
* @param {string} [params.stopLossPriceType] The type of the trigger price for the stop loss order, either 'last' or 'mark' (default is 'last')
* @param {float} [params.takeProfitPrice] price to trigger a standalone take-profit order on an open position, the price argument is used as its execution price for limit orders
* @param {string} [params.takeProfitPriceType] The type of the trigger price for the take profit order, either 'last' or 'mark' (default is 'last')
* @param {float} [params.triggerPrice] the price at which a trigger (entry conditional) order is triggered, cannot be used together with stopLossPrice or takeProfitPrice
* @param {bool} [params.reduceOnly] A mark to reduce the position size only. Set to false by default. Need to set the position size when reduceOnly is true.
* @param {string} [params.timeInForce] GTC, IOC, or FOK (default is GTC for limit orders, not supported for trigger orders)
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_contract_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 request: Value = self.create_contract_order_request(symbol, type_var, side, amount, &[price, params]);
let mut triggerPrice: Option<String> = self.safe_string_k(request.clone(), "triggerPrice", &[]).as_str().map(str::to_owned);
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if (triggerPrice.is_some()) {
if sandboxMode.as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support stopLossPrice or takeProfitPrice orders in sandbox mode".into()))));
}
response = self.contract_private_post_capi_v3_algo_order(&[request.clone()]).await;
} else if sandboxMode.as_bool() == Some(true) {
response = self.contract_private_post_capi_v3_sim_order(&[request.clone()]).await;
} else {
response = self.contract_private_post_capi_v3_order(&[request]).await;
}
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" createOrder() returned empty response".into()))));
}
return self.parse_order(response, &[market]);
Value::Null
}
pub fn create_contract_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createContractOrderRequest() requires a side argument".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.to_sandbox_market_id(market).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("side".to_string(), side.as_str().map(|__s| Value::Str(__s.to_uppercase().into())).unwrap_or(Value::Null));
m.insert("quantity".to_string(), self.amount_to_precision(symbol.clone(), amount));
m.insert("type".to_string(), type_var.as_str().map(|__s| Value::Str(__s.to_uppercase().into())).unwrap_or(Value::Null));
m
});
let mut isMarketOrder: bool = type_var.as_str() == Some("market");
if !isMarketOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price)); }
}
let mut triggerPricestopLossPricetakeProfitPricequeryVariable = self.handle_trigger_prices_and_params(symbol.clone(), params.clone(), &[]);
let mut triggerPrice: Value = triggerPricestopLossPricetakeProfitPricequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut stopLossPrice: Value = triggerPricestopLossPricetakeProfitPricequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut takeProfitPrice: Value = triggerPricestopLossPricetakeProfitPricequeryVariable.as_array().and_then(|__arr| __arr.get(2)).cloned().unwrap_or(Value::Null);
let mut query: Value = triggerPricestopLossPricetakeProfitPricequeryVariable.as_array().and_then(|__arr| __arr.get(3)).cloned().unwrap_or(Value::Null);
let mut isTrigger: bool = triggerPrice != Value::Null;
let mut isStopLoss: bool = stopLossPrice != Value::Null;
let mut isTakeProfit: bool = takeProfitPrice != Value::Null;
if isTrigger && (isStopLoss || isTakeProfit) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() cannot use the triggerPrice parameter together with the stopLossPrice or takeProfitPrice parameters".into()))));
}
let mut reduceOnly: Value = self.safe_bool_k(query, "reduceOnly", &[]);
let mut isReduceOnly: bool = isStopLoss || isTakeProfit || (reduceOnly.as_bool() == Some(true));
let mut positionSide: Value = Value::Str("LONG".into());
if isReduceOnly {
if (side.as_str() == Some("buy")) {
positionSide = Value::Str("SHORT".into());
}
} else if (side.as_str() == Some("sell")) {
positionSide = Value::Str("SHORT".into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("positionSide".into(), positionSide); }
let mut takeProfit: Value = self.safe_dict_k(params.clone(), "takeProfit", &[]);
let mut hasTakeProfit: bool = takeProfit != Value::Null;
let mut stopLoss: Value = self.safe_dict_k(params.clone(), "stopLoss", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
// the exchange accepts but silently ignores execution prices for attached take profit / stop loss, they always execute at market price
if hasTakeProfit && (self.safe_number_k(takeProfit.clone(), "price", &[]) != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support the price field inside the takeProfit params, the attached take profit executes at market price".into()))));
}
if hasStopLoss && (self.safe_number_k(stopLoss.clone(), "price", &[]) != Value::Null) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support the price field inside the stopLoss params, the attached stop loss executes at market price".into()))));
}
let mut timeInForce: Option<String> = self.safe_string_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
if (clientOrderId == Value::Null) {
let mut partner: Value = self.safe_string_k(params.clone(), "partner", &[Value::Str("b-WEEX111125".into())]);
clientOrderId = Value::Str(format!("{}{}", Value::Str(format!("{}{}", partner, Value::Str("-".into())).into()), self.uuid22(&[])).into());
}
let mut callerMethodName: Option<String> = self.safe_string_k(params.clone(), "callerMethodName", &[]).as_str().map(str::to_owned);
if isTrigger {
// entry conditional order, triggers a regular order when the trigger price is reached
if (callerMethodName.as_deref() == Some("createOrders")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrders() does not support trigger orders".into()))));
}
if (timeInForce.is_some()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() cannot use the timeInForce parameter with trigger orders".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientAlgoId".into(), clientOrderId.clone()); }
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), self.price_to_precision(symbol.clone(), triggerPrice)); }
if isMarketOrder {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("STOP_MARKET".into())); }
} else {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("STOP".into())); }
}
// conditional orders attach take profit / stop loss through the preset* fields instead of tpTriggerPrice/slTriggerPrice
if hasStopLoss {
let mut stopLossTriggerPrice: Value = self.safe_number2(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("presetStopLossPrice".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice.clone())); }
let mut stopLossPriceType: Value = self.safe_string_k(stopLoss.clone(), "triggerPriceType", &[]);
if (stopLossPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("SlWorkingType".into(), self.encode_trigger_price_type(stopLossPriceType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
}
if hasTakeProfit {
let mut takeProfitTriggerPrice: Value = self.safe_number2(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("presetTakeProfitPrice".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice.clone())); }
let mut takeProfitPriceType: Value = self.safe_string_k(takeProfit.clone(), "triggerPriceType", &[]);
if (takeProfitPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("TpWorkingType".into(), self.encode_trigger_price_type(takeProfitPriceType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
}
} else if isStopLoss || isTakeProfit {
if (callerMethodName.as_deref() == Some("createOrders")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrders() does not support stop loss and take profit orders".into()))));
}
if (timeInForce.is_some()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() cannot use timeInForce parameter with stopLoss and takeProfit orders".into()))));
}
if hasStopLoss || hasTakeProfit {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() cannot use both stopLossPrice/takeProfitPrice parameters and stopLoss/takeProfit objects in params at the same time".into()))));
}
if isStopLoss && isTakeProfit {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrder() cannot use both stopLossPrice and takeProfitPrice parameters at the same time".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientAlgoId".into(), clientOrderId.clone()); }
let mut orderType: Value = Value::Null;
if isStopLoss {
let mut stopLossPriceType: Value = self.safe_string2(params.clone(), Value::Str("stopLossPriceType".into()), Value::Str("triggerPriceType".into()), &[]);
if (stopLossPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("SlWorkingType".into(), self.encode_trigger_price_type(stopLossPriceType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), self.price_to_precision(symbol.clone(), stopLossPrice)); }
if isMarketOrder {
orderType = Value::Str("STOP_MARKET".into());
} else {
orderType = Value::Str("STOP".into());
}
} else if isTakeProfit {
let mut takeProfitPriceType: Value = self.safe_string2(params.clone(), Value::Str("takeProfitPriceType".into()), Value::Str("triggerPriceType".into()), &[]);
if (takeProfitPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("TpWorkingType".into(), self.encode_trigger_price_type(takeProfitPriceType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), self.price_to_precision(symbol.clone(), takeProfitPrice)); }
if isMarketOrder {
orderType = Value::Str("TAKE_PROFIT_MARKET".into());
} else {
orderType = Value::Str("TAKE_PROFIT".into());
}
}
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("type".into(), orderType); }
} else {
if !isMarketOrder && (timeInForce.is_none()) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeInForce".into(), Value::Str("GTC".into())); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newClientOrderId".into(), clientOrderId); }
if hasStopLoss {
let mut stopLossTriggerPrice: Value = self.safe_number2(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slTriggerPrice".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice)); }
let mut stopLossPriceType: Value = self.safe_string_k(stopLoss, "triggerPriceType", &[]);
if (stopLossPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("SlWorkingType".into(), self.encode_trigger_price_type(stopLossPriceType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
}
if hasTakeProfit {
let mut takeProfitTriggerPrice: Value = self.safe_number2(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpTriggerPrice".into(), self.price_to_precision(symbol, takeProfitTriggerPrice)); }
let mut takeProfitPriceType: Value = self.safe_string_k(takeProfit, "triggerPriceType", &[]);
if (takeProfitPriceType != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("TpWorkingType".into(), self.encode_trigger_price_type(takeProfitPriceType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("takeProfit".into()), Value::Str("stopLoss".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("triggerPriceType".into()), Value::Str("stopLossPriceType".into()), Value::Str("takeProfitPriceType".into()), Value::Str("clientOrderId".into()), Value::Str("callerMethodName".into())]), &[]);
return self.extend(request, &[paramsOmitted]);
Value::Null
}
pub fn encode_trigger_price_type(&self, mut triggerPriceType: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mark".to_string(), Value::Str("MARK_PRICE".into()));
m.insert("last".to_string(), Value::Str("CONTRACT_PRICE".into()));
m
});
return self.safe_string(types, triggerPriceType.clone(), &[triggerPriceType.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name weex#cancelOrder
* @description cancels an open order
* @see https://www.weex.com/api-doc/spot/orderApi/CancelOrder // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/CancelOrder // contract
* @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.type] 'spot' or 'swap' (default is 'spot')
* @param {boolean} [params.trigger] *contract orders only* whether the order to cancel is a trigger order
* @param {string} [params.clientOrderId] *non-trigger orders only* 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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("cancelOrder".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 trigger: Value = self.safe_bool_k(paramsMarketType.clone(), "trigger", &[Value::Bool(false)]);
if trigger.as_bool() == Some(true) && (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires an id argument for trigger orders".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut clientOrderId: Value = self.safe_string_k(paramsMarketType.clone(), "clientOrderId", &[]);
let mut paramsOmitted: Value = self.omit(paramsMarketType, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("trigger".into())]), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("origClientOrderId".into(), clientOrderId); }
} else if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires an id argument or clientOrderId parameter".into()))));
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), id.clone()); }
}
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
// by orderId
// {
// "orderId": 736775987680772200,
// "status": "CANCELED"
// }
//
// by clientOrderId
// {
// "origClientOrderId": "test_cancel_order",
// "status": "CANCELED"
// }
//
let __ws_arg_16 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_delete_api_v3_order(&[__ws_arg_16]).await;
} else if trigger.as_bool() == Some(true) {
let __ws_arg_17 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.contract_private_delete_capi_v3_algo_order(&[__ws_arg_17]).await;
} else {
let __ws_arg_18 = self.extend(request, &[paramsOmitted]);
response = self.contract_private_delete_capi_v3_order(&[__ws_arg_18]).await;
}
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" parseOrder() returned empty response".into()))));
}
let mut order: Value = self.parse_order(response, &[market]);
add_element_to_object(&mut order, &Value::Str("status".into()), Value::Str("canceled".into()));
return order;
Value::Null
}
/*
* @method
* @name weex#cancelAllOrders
* @description cancel all open orders
* @see https://www.weex.com/api-doc/spot/orderApi/Cancel-Symbol-Orders // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/CancelAllOrders // contract
* @see https://www.weex.com/api-doc/contract/Transaction_API/CancelAllPendingOrders // contract trigger
* @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', used if symbol is not provided (default is 'spot')
* @param {boolean} [params.trigger] *swap only* true for cancelling trigger orders (default is false)
* @returns Response from the exchange
*/
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 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.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
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 trigger: Value = self.safe_bool_k(paramsMarketType.clone(), "trigger", &[Value::Bool(false)]);
let mut paramsOmitted: Value = self.omit(paramsMarketType, Value::Str("trigger".into()), &[]);
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrders() requires a symbol argument for spot markets".into()))));
}
let __ws_arg_19 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_delete_api_v3_open_orders(&[__ws_arg_19]).await;
} else if trigger.as_bool() == Some(true) {
let __ws_arg_20 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.contract_private_delete_capi_v3_algo_open_orders(&[__ws_arg_20]).await;
} else {
let __ws_arg_21 = self.extend(request, &[paramsOmitted]);
response = self.contract_private_delete_capi_v3_all_open_orders(&[__ws_arg_21]).await;
}
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("canceled".into()));
m
});
return self.parse_orders(response, &[market, Value::Null, Value::Null, extendedParams]);
Value::Null
}
/*
* @method
* @name weex#cancelOrders
* @description cancel multiple orders
* @see https://www.weex.com/api-doc/spot/orderApi/BulkCancel // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/CancelOrdersBatch // contract
* @param {string[]} ids order ids
* @param {string} [symbol] unified market symbol, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string[]} [params.clientOrderIds] client order ids (could be an alternative to ids)
* @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut 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);
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("cancelOrders".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 isSpot: bool = marketType.as_str() == Some("spot");
let mut clientOrderIds: Value = self.safe_list_k(paramsMarketType.clone(), "clientOrderIds", &[]);
let mut paramsOmitted: Value = self.omit(paramsMarketType, Value::Str("clientOrderIds".into()), &[]);
if (clientOrderIds != Value::Null) {
if isSpot {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("origClientOrderIds".into(), clientOrderIds.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("origClientOrderIdList".into(), clientOrderIds); }
}
} else if (ids != Value::Null) {
if isSpot {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderIds".into(), ids.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderIdList".into(), ids); }
}
} else {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires an ids argument or clientOrderIds parameter".into()))));
}
let mut response: Value = Value::Null;
if isSpot {
let __ws_arg_22 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_delete_api_v3_order_batch(&[__ws_arg_22]).await;
} else {
let __ws_arg_23 = self.extend(request, &[paramsOmitted]);
response = self.contract_private_delete_capi_v3_batch_orders(&[__ws_arg_23]).await;
}
let mut ordersResponse: Value = self.safe_list_k(response, "orderList", &[Value::from(vec![])]);
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("canceled".into()));
m
});
return self.parse_orders(ordersResponse, &[market, Value::Null, Value::Null, extendedParams]);
Value::Null
}
/*
* @method
* @name weex#fetchOrder
* @description fetches information on an order made by the user
* @see https://www.weex.com/api-doc/spot/orderApi/OrderDetails // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetSingleOrderInfo // contract
* @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.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @param {string} [params.clientOrderId] *spot only* a unique id for the order, used if id is not provided
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOrder".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 isSpot: bool = marketType.as_str() == Some("spot");
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (id == Value::Null) && !isSpot {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires an id argument for non-spot markets".into()))));
}
let mut clientOrderId: Value = self.safe_string_k(paramsMarketType.clone(), "clientOrderId", &[]);
let mut paramsOmitted: Value = self.omit(paramsMarketType, Value::Str("clientOrderId".into()), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("origClientOrderId".into(), clientOrderId); }
} else if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires an id argument or clientOrderId parameter for spot markets".into()))));
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), id.clone()); }
}
let mut response: Value = Value::Null;
if isSpot {
//
// {
// "symbol": "DOGEUSDT",
// "orderId": 736800333186991070,
// "clientOrderId": "082007092f624a18bb7af2ab42e7c8e8",
// "price": "0.08500",
// "origQty": "300.0",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "NEW",
// "timeInForce": "GTC",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1775666888520,
// "updateTime": 1775666888536,
// "isWorking": true
// }
//
let __ws_arg_24 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_get_api_v3_order(&[__ws_arg_24]).await;
} else {
let __ws_arg_25 = self.extend(request, &[paramsOmitted]);
response = self.contract_private_get_capi_v3_order(&[__ws_arg_25]).await;
}
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" parseOrder() returned empty response".into()))));
}
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name weex#fetchOpenOrders
* @see https://www.weex.com/api-doc/spot/orderApi/UnfinishedOrders // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetCurrentOrderStatus // contract
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetCurrentPendingOrders // contract trigger
* @description fetch all unfilled currently open orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @param {boolean} [params.trigger] *swap only* whether to fetch trigger orders (default is false)
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOpenOrders".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 isSpot: bool = marketType.as_str() == Some("spot");
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(paramsMarketType, Value::Str("fetchOpenOrders".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);
let mut maxLimit: Value = Value::Int(100);
if paginate.as_bool() == Some(true) {
if isSpot {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() pagination is not supported for spot markets".into()))));
}
return self.fetch_paginated_call_dynamic(Value::Str("fetchOpenOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), self.safe_string_k(market.clone(), "id", &[])); }
}
let mut response: Value = Value::Null;
if isSpot {
//
// [
// {
// "symbol": "DOGEUSDT",
// "orderId": 736807745679786974,
// "clientOrderId": "e6dc41082bf342f580a19264d82dab31",
// "price": "0.12000",
// "origQty": "299.0",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "NEW",
// "timeInForce": "GTC",
// "type": "LIMIT",
// "side": "SELL",
// "time": 1775668655796,
// "updateTime": 1775668655810,
// "isWorking": true
// }
// ]
//
let __ws_arg_26 = self.extend(request.clone(), &[paramsPaginate.clone()]);
response = self.private_get_api_v3_open_orders(&[__ws_arg_26]).await;
} else {
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 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 mut trigger: Value = self.safe_bool_k(paramsUntil.clone(), "trigger", &[Value::Bool(false)]);
if trigger.as_bool() == Some(true) {
let mut paramsOmitted: Value = self.omit(paramsUntil.clone(), Value::Str("trigger".into()), &[]);
//
// [
// {
// "algoId": 737074389748547944,
// "clientAlgoId": "d574f517-cea5-433e-b029-415590d3bb80",
// "algoType": "CONDITIONAL",
// "orderType": "STOP_MARKET",
// "symbol": "DOGEUSDT",
// "side": "SELL",
// "positionSide": "LONG",
// "timeInForce": "IOC",
// "quantity": "100",
// "algoStatus": "UNTRIGGERED",
// "actualOrderId": 737074043320009064,
// "actualPrice": "0.00000",
// "triggerPrice": "0.02000",
// "price": "0.00000",
// "tpTriggerPrice": null,
// "tpPrice": null,
// "slTriggerPrice": null,
// "slPrice": null,
// "tpOrderType": null,
// "workingType": "CONTRACT_PRICE",
// "closePosition": false,
// "reduceOnly": true,
// "createTime": 1775732228695,
// "updateTime": 1775732228695,
// "triggerTime": 0
// }
// ]
//
let __ws_arg_27 = self.extend(requestUntil.clone(), &[paramsOmitted]);
response = self.contract_private_get_capi_v3_open_algo_orders(&[__ws_arg_27]).await;
} else {
//
// [
// {
// "avgPrice": "0.00000",
// "clientOrderId": "857e1482-3225-44ce-bc0a-947714c5cabc",
// "cumQuote": "0",
// "executedQty": "0",
// "orderId": 737185556881998184,
// "origQty": "1400",
// "price": "0.05000",
// "reduceOnly": false,
// "side": "BUY",
// "positionSide": "LONG",
// "status": "NEW",
// "stopPrice": "0",
// "symbol": "DOGEUSDT",
// "time": 1775758733006,
// "timeInForce": "GTC",
// "type": "LIMIT",
// "updateTime": 1775758733006,
// "workingType": "UNKNOWN_PRICE_TYPE"
// }
// ]
//
let __ws_arg_28 = self.extend(requestUntil, &[paramsUntil]);
response = self.contract_private_get_capi_v3_open_orders(&[__ws_arg_28]).await;
}
}
let mut extendedParams: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("open".into()));
m
});
return self.parse_orders(response, &[market, since, limit, extendedParams]);
Value::Null
}
/*
* @method
* @name weex#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
* @see https://www.weex.com/api-doc/contract/demo/GetOrderHistory // contract in sandbox mode
* @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 {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchClosedOrders".into()), &[market, 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 orders: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchClosedOrders() requires a symbol argument for spot markets".into()))));
}
orders = self.fetch_orders(&[symbol.clone(), since.clone(), Value::Null, paramsMarketType.clone()]).await;
} else {
orders = self.fetch_canceled_and_closed_orders(&[symbol, since, limit, paramsMarketType]).await;
}
return self.filter_by(orders, Value::Str("status".into()), Value::Str("closed".into()), &[]);
Value::Null
}
/*
* @method
* @name weex#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
* @see https://www.weex.com/api-doc/contract/demo/GetOrderHistory // contract in sandbox mode
* @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 {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @returns {Order[]} 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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchCanceledOrders".into()), &[market, 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 orders: Value = Value::Null;
if (marketType.as_str() == Some("spot")) {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchCanceledOrders() requires a symbol argument for spot markets".into()))));
}
orders = self.fetch_orders(&[symbol.clone(), since.clone(), Value::Null, paramsMarketType.clone()]).await;
} else {
orders = self.fetch_canceled_and_closed_orders(&[symbol, since, limit, paramsMarketType]).await;
}
return self.filter_by(orders, Value::Str("status".into()), Value::Str("canceled".into()), &[]);
Value::Null
}
/*
* @method
* @name weex#fetchOrders
* @description fetches information on multiple spot orders made by the user
* @see https://www.weex.com/api-doc/spot/orderApi/HistoryOrders // spot
* @param {string} symbol unified market symbol of the market orders were made in (required for spot orders)
* @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 {object} [params.until] end time, ms
* @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 {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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders() 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("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOrders() supports spot markets only".into()))));
}
let mut maxLimit: Value = Value::Int(1000);
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOrders".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 paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchOrders".into()), &[symbol, since.clone(), limit.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 (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, &maxLimit)); }
}
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_29 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.private_get_api_v3_all_orders(&[__ws_arg_29]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name weex#fetchCanceledAndClosedOrders
* @description fetches information on multiple closed and canceled orders made by the user
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetOrderHistory // contract
* @see https://www.weex.com/api-doc/contract/demo/GetOrderHistory // contract in sandbox mode
* @param {string} [symbol] unified market symbol of the market orders were made in (required for spot orders)
* @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 {object} [params.until] end time, ms
* @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @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 {Order[]} 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;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchCanceledAndClosedOrders".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 (marketType.as_str() == Some("spot")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchCanceledAndClosedOrders() does not support spot markets. Use fetchOrders() instead and filter by status \"canceled\" or \"closed\"".into()))));
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(paramsMarketType, Value::Str("fetchCanceledAndClosedOrders".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);
let mut maxLimit: Value = Value::Int(1000);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchCanceledAndClosedOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), self.to_sandbox_market_id(market.clone()).map(|__s| Value::Str(__s.into())).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 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 mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if sandboxMode.as_bool() == Some(true) {
let __ws_arg_30 = self.extend(requestUntil.clone(), &[paramsUntil.clone()]);
response = self.contract_private_get_capi_v3_sim_order_history(&[__ws_arg_30]).await;
} else {
let __ws_arg_31 = self.extend(requestUntil, &[paramsUntil]);
response = self.contract_private_get_capi_v3_order_history(&[__ws_arg_31]).await;
}
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrder (spot)
// {
// "symbol": "DOGEUSDT",
// "orderId": 736557215397183592,
// "clientOrderId": "c4551206d34641efbeb64abaa066946d",
// "transactTime": 1775608924724
// }
//
// fetchOpenOrders / fetchOrders / fetchOrder (spot)
// {
// "symbol": "DOGEUSDT",
// "orderId": 736800333186991070,
// "clientOrderId": "082007092f624a18bb7af2ab42e7c8e8",
// "price": "0.08500",
// "origQty": "300.0",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "NEW",
// "timeInForce": "GTC",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1775666888520,
// "updateTime": 1775666888536,
// "isWorking": true
// }
//
// fetchOpenOrders (contract)
// {
// "avgPrice": "0.00000",
// "clientOrderId": "857e1482-3225-44ce-bc0a-947714c5cabc",
// "cumQuote": "0",
// "executedQty": "0",
// "orderId": 737185556881998184,
// "origQty": "1400",
// "price": "0.05000",
// "reduceOnly": false,
// "side": "BUY",
// "positionSide": "LONG",
// "status": "NEW",
// "stopPrice": "0",
// "symbol": "DOGEUSDT",
// "time": 1775758733006,
// "timeInForce": "GTC",
// "type": "LIMIT",
// "updateTime": 1775758733006,
// "workingType": "UNKNOWN_PRICE_TYPE"
// }
//
// fetchOpenOrders (contract-trigger)
// {
// "algoId": 737074389748547944,
// "clientAlgoId": "d574f517-cea5-433e-b029-415590d3bb80",
// "algoType": "CONDITIONAL",
// "orderType": "STOP_MARKET",
// "symbol": "DOGEUSDT",
// "side": "SELL",
// "positionSide": "LONG",
// "timeInForce": "IOC",
// "quantity": "100",
// "algoStatus": "UNTRIGGERED",
// "actualOrderId": 737074043320009064,
// "actualPrice": "0.00000",
// "triggerPrice": "0.02000",
// "price": "0.00000",
// "tpTriggerPrice": null,
// "tpPrice": null,
// "slTriggerPrice": null,
// "slPrice": null,
// "tpOrderType": null,
// "workingType": "CONTRACT_PRICE",
// "closePosition": false,
// "reduceOnly": true,
// "createTime": 1775732228695,
// "updateTime": 1775732228695,
// "triggerTime": 0
// }
//
// fetchCanceledAndClosedOrders (swap only)
// {
// "avgPrice": "0.00000",
// "clientOrderId": "7bd80776-0c3f-4ed9-ab9c-a616d66fac5e",
// "cumQuote": "0",
// "executedQty": "0",
// "orderId": 737074389744353640,
// "origQty": "100",
// "price": "0.00000",
// "reduceOnly": true,
// "side": "SELL",
// "positionSide": "LONG",
// "status": "CANCELED",
// "stopPrice": "1.00000",
// "symbol": "DOGEUSDT",
// "time": 1775732228695,
// "timeInForce": "IOC",
// "type": "TAKE_PROFIT_MARKET",
// "updateTime": 1775732228695,
// "workingType": "CONTRACT_PRICE"
// }
//
let mut errorCode: Value = self.safe_string_k(order.clone(), "errorCode", &[]);
let mut errorMessage: Value = self.safe_string_k(order.clone(), "errorMsg", &[]);
if (errorCode != Value::Null) || (errorMessage != Value::Null) {
self.handle_order_or_position_error(errorCode, errorMessage, order.clone());
}
let mut orderMarketId: Value = self.from_sandbox_market_id(self.safe_string_k(order.clone(), "symbol", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut positionSide: Option<String> = self.safe_string_k(order.clone(), "positionSide", &[]).as_str().map(str::to_owned);
let mut orderMarketType: Value = Value::Str("swap".into());
if (positionSide.is_none()) {
orderMarketType = Value::Str("spot".into());
}
let mut marketResolved: Value = self.safe_market(&[(if (market == Value::Null) { orderMarketId } else { Value::Null }), market, Value::Null, orderMarketType]);
let mut timestamp: Value = self.safe_integer_n(order.clone(), Value::from(vec![Value::Str("transactTime".into()), Value::Str("time".into()), Value::Str("createTime".into())]), &[]);
let mut rawStatus: Value = self.safe_string_lower2(order.clone(), Value::Str("status".into()), Value::Str("algoStatus".into()), &[]); // algo (trigger) order payloads carry algoStatus instead of status
let mut triggerPrice: Value = self.omit_zero(self.safe_string2(order.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]));
let mut rawType: Value = self.safe_string_upper2(order.clone(), Value::Str("type".into()), Value::Str("orderType".into()), &[]);
let mut isReduceOnly: Value = self.safe_bool_k(order.clone(), "reduceOnly", &[]);
// entry conditional orders reuse the STOP/TAKE_PROFIT types with reduceOnly set to false, their trigger price is not a stop loss / take profit price
// a missing reduceOnly counts as reduce-only to keep the legacy mapping for responses that omit the field
let mut isEntryTrigger: bool = !(self.safe_bool_k(order.clone(), "reduceOnly", &[Value::Bool(true)]).as_bool() == Some(true));
let mut takeProfitPrice: Value = Value::Null;
let mut stopLossPrice: Value = Value::Null;
if !isEntryTrigger {
if (rawType.as_str() == Some("TAKE_PROFIT_MARKET")) || (rawType.as_str() == Some("TAKE_PROFIT")) {
takeProfitPrice = triggerPrice.clone();
} else if (rawType.as_str() == Some("STOP_LOSS")) || (rawType.as_str() == Some("STOP")) || (rawType.as_str() == Some("STOP_MARKET")) {
stopLossPrice = triggerPrice.clone();
}
}
if (takeProfitPrice == Value::Null) {
takeProfitPrice = self.omit_zero(self.safe_string_k(order.clone(), "tpTriggerPrice", &[])); // attached take profit of a regular or conditional order
}
if (stopLossPrice == Value::Null) {
stopLossPrice = self.omit_zero(self.safe_string_k(order.clone(), "slTriggerPrice", &[])); // attached stop loss of a regular or conditional order
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_n(order.clone(), Value::from(vec![Value::Str("orderId".into()), Value::Str("algoId".into()), Value::Str("successOrderId".into())]), &[]));
m.insert("clientOrderId".to_string(), self.safe_string_n(order.clone(), Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("origClientOrderId".into()), Value::Str("clientAlgoId".into())]), &[]));
m.insert("symbol".to_string(), self.safe_string_k(marketResolved.clone(), "symbol", &[]));
m.insert("type".to_string(), self.parse_order_type(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), self.safe_string_k(order.clone(), "timeInForce", &[]));
m.insert("postOnly".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), isReduceOnly);
m.insert("side".to_string(), self.safe_string_lower_k(order.clone(), "side", &[]));
m.insert("amount".to_string(), self.safe_string2(order.clone(), Value::Str("origQty".into()), Value::Str("quantity".into()), &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("cost".to_string(), self.safe_string2(order.clone(), Value::Str("cummulativeQuoteQty".into()), Value::Str("cumQuote".into()), &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "executedQty", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fee".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_order_status(rawStatus).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(order.clone(), "updateTime", &[]));
m.insert("average".to_string(), self.safe_string_k(order.clone(), "avgPrice", &[]));
m.insert("trades".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("info".to_string(), order);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("new".to_string(), Value::Str("open".into()));
m.insert("partial_fill".to_string(), Value::Str("closed".into()));
m.insert("full_fill".to_string(), Value::Str("closed".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("cancelled".to_string(), Value::Str("canceled".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("rejected".to_string(), Value::Str("rejected".into()));
m.insert("untriggered".to_string(), Value::Str("open".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("LIMIT".to_string(), Value::Str("limit".into()));
m.insert("MARKET".to_string(), Value::Str("market".into()));
m.insert("STOP_LOSS".to_string(), Value::Str("limit".into()));
m.insert("STOP".to_string(), Value::Str("limit".into()));
m.insert("TAKE_PROFIT".to_string(), Value::Str("limit".into()));
m.insert("TAKE_PROFIT_MARKET".to_string(), Value::Str("market".into()));
m.insert("STOP_MARKET".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn handle_order_or_position_error(&self, mut errorCode: Value, mut errorMessage: Value, mut order: Value) {
let mut errorCodeValue: Value = (if (errorCode == Value::Null) { Value::Str("".into()) } else { errorCode.clone() });
let mut errorMessageValue: Value = (if (errorMessage == Value::Null) { Value::Str("".into()) } else { errorMessage.clone() });
if ((errorCode == Value::Null) || (errorCode.as_str() == Some(""))) && ((errorMessage == Value::Null) || (errorMessage.as_str() == Some(""))) {
return;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), json_stringify(&order)).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorMessageValue.clone(), feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCodeValue.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessageValue, feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorCodeValue, feedback.clone());
panic!("{}", crate::exchange_errors::invalid_order(feedback));
}
/*
* @method
* @name weex#fetchOrderTrades
* @description fetch all the trades made from a single order
* @see https://www.weex.com/api-doc/spot/orderApi/TransactionDetails // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetTradeDetails // contract
* @param {string} id order id
* @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 to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m
});
let __ws_arg_32 = self.extend(request, &[params]);
return self.fetch_my_trades(&[symbol, since, limit, __ws_arg_32]).await;
Value::Null
}
/*
* @method
* @name weex#fetchMyTrades
* @see https://www.weex.com/api-doc/spot/orderApi/TransactionDetails // spot
* @see https://www.weex.com/api-doc/contract/Transaction_API/GetTradeDetails // contract
* @description fetch all trades made by the user
* @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 {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)
* @param {string} [params.type] 'spot' or 'swap', used if symbol is not provided (default is 'spot')
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchMyTrades".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 isSpot: bool = marketType.as_str() == Some("spot");
if isSpot && (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() requires a symbol argument for spot markets".into()))));
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(paramsMarketType, Value::Str("fetchMyTrades".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);
let mut maxLimit: Value = Value::Int(100);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), self.safe_string_k(market.clone(), "id", &[])); }
}
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 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 mut response: Value = Value::Null;
if isSpot {
//
// [
// {
// "symbol": "DOGEUSDT",
// "id": 736825748291060702,
// "orderId": 736825748215563230,
// "price": "0.09349",
// "qty": "250.0",
// "quoteQty": "23.3725",
// "commission": "0.0233725",
// "time": 1775672947953,
// "isBuyer": false
// }
// ]
//
let __ws_arg_33 = self.extend(requestUntil.clone(), &[paramsUntil.clone()]);
response = self.private_get_api_v3_my_trades(&[__ws_arg_33]).await;
} else {
//
// [
// {
// "id": 737074389731770728,
// "orderId": 737074043320009064,
// "symbol": "DOGEUSDT",
// "buyer": true,
// "commission": "0.00183500",
// "commissionAsset": "USDT",
// "maker": true,
// "price": "0.09175",
// "qty": "100",
// "quoteQty": "9.17500",
// "realizedPnl": "0",
// "side": "BUY",
// "positionSide": "LONG",
// "time": 1775732228692
// }
// ]
//
let __ws_arg_34 = self.extend(requestUntil, &[paramsUntil]);
response = self.contract_private_get_capi_v3_user_trades(&[__ws_arg_34]).await;
}
let mut responseList: Value = Value::from(vec![]);
if (response != Value::Null) {
responseList = self.to_array(response);
}
return self.parse_trades(responseList, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name weex#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://www.weex.com/api-doc/spot/AccountAPI/GetBillRecords // spot
* @see https://www.weex.com/api-doc/spot/AccountAPI/GetFundBillRecords // funding
* @see https://www.weex.com/api-doc/contract/Account_API/GetContractBills // contract
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined, max is 100
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest ledger entry
* @param {string} [params.type] 'spot', 'funding' or 'swap' (default is 'spot')
* @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 {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchLedger".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);
let mut maxLimit: Value = Value::Int(100);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchLedger".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit]).await;
}
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchLedger".into()), &[Value::Null, paramsPaginate]);
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 accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut accountType: Option<String> = self.safe_string(accountsByType, marketType.clone(), &[marketType.clone()]).as_str().map(str::to_owned);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut items: Value = Value::Null;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
if (accountType.as_deref() == Some("contract")) {
if (currency != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (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 requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request.clone(), paramsMarketType.clone(), &[]);
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_35 = self.extend(requestUntil.clone(), &[paramsUntil.clone()]);
let mut contractResponse: Value = self.contract_private_post_capi_v3_account_income(&[__ws_arg_35]).await;
items = self.safe_list_k(contractResponse, "items", &[Value::from(vec![])]);
} else if (accountType.as_deref() == Some("funding")) {
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(), limit.clone()); }
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request.clone(), paramsMarketType.clone(), &[]);
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_36 = self.extend(requestUntil.clone(), &[paramsUntil.clone()]);
let mut fundingResponse: Value = self.private_post_api_v3_account_funding_bills(&[__ws_arg_36]).await;
items = self.safe_list_k(fundingResponse, "items", &[Value::from(vec![])]);
} else {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".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 requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("before".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_37 = self.extend(requestUntil, &[paramsUntil]);
let mut billsResponse: Value = self.private_post_api_v3_account_bills(&[__ws_arg_37]).await;
items = self.to_array(billsResponse);
}
return self.parse_ledger(items, &[currency, since, limit]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// spot
// {
// "billId": "736825748291061726",
// "coinId": 82,
// "coinName": "DOGE",
// "bizType": "trade_out",
// "fillSize": "250.0",
// "fillValue": "23.372500",
// "deltaAmount": "-250.0",
// "afterAmount": "49.70000000",
// "fees": "0",
// "cTime": "1775672947953"
// }
//
// contract
// {
// "billId": 736791763716407518,
// "asset": "USDT",
// "symbol": null,
// "income": "-90.00000000",
// "incomeType": "withdraw",
// "balance": "106.00000000",
// "fillFee": "0",
// "time": 1775664845399,
// "transferReason": "UNKNOWN_TRANSFER_REASON"
// }
//
// funding
// {
// "billId": "16502414",
// "coinId": 2,
// "coinName": "USDT",
// "bizType": "transfer_out",
// "fillSize": null,
// "fillValue": null,
// "deltaAmount": "-100.00000000",
// "afterAmount": "0.00000000",
// "fees": "0.00000000",
// "cTime": "1775664588931"
// }
//
let mut currencyId: Value = self.safe_string2(item.clone(), Value::Str("coinName".into()), Value::Str("asset".into()), &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut timestamp: Value = self.safe_integer2(item.clone(), Value::Str("cTime".into()), Value::Str("time".into()), &[]);
let mut amountRaw: Value = self.safe_string2(item.clone(), Value::Str("deltaAmount".into()), Value::Str("income".into()), &[]);
let mut after: Value = self.safe_string2(item.clone(), Value::Str("afterAmount".into()), Value::Str("balance".into()), &[]);
let mut before: Value = crate::precise::Precise::stringSub(&after, &amountRaw);
let mut amount: Value = self.parse_number(crate::precise::Precise::stringAbs(&amountRaw), &[]);
let mut direction: Value = Value::Str("in".into());
if (amountRaw == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseLedgerEntry() missing amountRaw".into()))));
}
if Value::Int(amountRaw.as_str().and_then(|__s| __s.find("-")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
direction = Value::Str("out".into());
}
let mut rawType: Value = self.safe_string2(item.clone(), Value::Str("bizType".into()), Value::Str("incomeType".into()), &[]);
let mut transferReason: Option<String> = self.safe_string_k(item.clone(), "transferReason", &[]).as_str().map(str::to_owned);
let mut isContractEntry: bool = transferReason.is_some();
if isContractEntry {
if (rawType.as_str() == Some("withdraw")) || (rawType.as_str() == Some("deposit")) {
rawType = Value::Str("transfer".into());
}
}
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), self.safe_string_k(item.clone(), "billId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("direction".to_string(), direction);
m.insert("account".to_string(), Value::Null);
m.insert("referenceId".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), self.parse_ledger_type(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), amount);
m.insert("before".to_string(), self.parse_number(before, &[]));
m.insert("after".to_string(), self.parse_number(after, &[]));
m.insert("status".to_string(), Value::Null);
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_number2(item, Value::Str("fees".into()), Value::Str("fillFee".into()), &[]));
m
}));
m
}), &[currencyResolved]);
Value::Null
}
pub fn parse_ledger_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("transfer_in".to_string(), Value::Str("transfer".into()));
m.insert("transfer_out".to_string(), Value::Str("transfer".into()));
m.insert("deposit".to_string(), Value::Str("deposit".into()));
m.insert("withdraw".to_string(), Value::Str("withdrawal".into()));
m.insert("trade_in".to_string(), Value::Str("trade".into()));
m.insert("trade_out".to_string(), Value::Str("trade".into()));
m.insert("position_open_long".to_string(), Value::Str("trade".into()));
m.insert("position_open_short".to_string(), Value::Str("trade".into()));
m.insert("position_close_long".to_string(), Value::Str("trade".into()));
m.insert("position_close_short".to_string(), Value::Str("trade".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name weex#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://www.weex.com/api-doc/contract/Account_API/GetContractBills
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve (default 20, max 100)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest funding history entry, requires since to be set, the span may not exceed 100 days
* @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 {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 paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, 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 paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchFundingHistory".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Int(100)]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("incomeType".to_string(), Value::Str("position_funding".into()));
m
});
if (symbol != Value::Null) {
market = 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::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() supports swap contracts only".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (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 requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("endTime".into()), request, paramsPaginate.clone(), &[]);
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);
// the exchange rejects startTime and endTime when either is sent alone, they only work as a pair
let mut hasSince: bool = since != Value::Null;
let mut until: Value = self.safe_integer2(paramsPaginate, Value::Str("until".into()), Value::Str("till".into()), &[]);
let mut hasUntil: bool = until != Value::Null;
if hasSince && !hasUntil {
if let Value::Dict(__d) = &mut requestUntil { std::sync::Arc::make_mut(__d).insert("endTime".into(), self.milliseconds()); }
} else if hasUntil && !hasSince {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingHistory() requires since to be set when until is used".into()))));
}
let __ws_arg_38 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.contract_private_post_capi_v3_account_income(&[__ws_arg_38]).await;
//
// {
// "hasNextPage": false,
// "nextKey": null,
// "items": [
// {
// "billId": "793622764958253481",
// "asset": "USDT",
// "symbol": "VIRTUALUSDT",
// "income": "0.00000378",
// "incomeType": "position_funding",
// "balance": "29.36239410",
// "fillFee": "0",
// "time": "1789214411964",
// "transferReason": "UNKNOWN_TRANSFER_REASON"
// }
// ]
// }
//
let mut items: Value = self.safe_list_k(response, "items", &[Value::from(vec![])]);
return self.parse_incomes(items, &[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);
//
// {
// "billId": "793622764958253481",
// "asset": "USDT",
// "symbol": "VIRTUALUSDT",
// "income": "0.00000378",
// "incomeType": "position_funding",
// "balance": "29.36239410",
// "fillFee": "0",
// "time": "1789214411964",
// "transferReason": "UNKNOWN_TRANSFER_REASON"
// }
//
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(), "billId", &[]));
m.insert("amount".to_string(), self.safe_number_k(income, "income", &[]));
m
});
Value::Null
}
/*
* @method
* @name weex#fetchPositions
* @description fetch all open positions
* @see https://www.weex.com/api-doc/contract/Account_API/GetAllPositions
* @see https://www.weex.com/api-doc/contract/demo/GetAllPositions // sandbox mode
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if sandboxMode.as_bool() == Some(true) {
response = self.contract_private_get_capi_v3_sim_position_all_position(&[params.clone()]).await;
} else {
response = self.contract_private_get_capi_v3_account_position_all_position(&[params]).await;
}
return self.parse_positions(response, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name weex#fetchPosition
* @description fetch data on an open position
* @see https://www.weex.com/api-doc/contract/Account_API/GetSinglePosition
* @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
}));
let mut positions: Value = self.fetch_positions_for_symbol(symbol, &[params]).await;
return self.safe_dict(positions, Value::Int(0), &[]);
Value::Null
}
/*
* @method
* @description fetch open positions for a single market
* @name weex#fetchPositionsForSymbol
* @see https://www.weex.com/api-doc/contract/Account_API/GetSinglePosition
* @description fetch all open positions for specific symbol
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_for_symbol(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if sandboxMode.as_bool() == Some(true) {
return self.fetch_positions(&[Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]), params.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
});
let __ws_arg_39 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_get_capi_v3_account_position_single_position(&[__ws_arg_39]).await;
return self.parse_positions(response, &[Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)])]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": 737191855967437160,
// "asset": "USDT",
// "symbol": "DOGEUSDT",
// "side": "LONG",
// "marginType": "CROSSED",
// "separatedMode": "COMBINED",
// "separatedOpenOrderId": 0,
// "leverage": "20.00",
// "size": "300",
// "openValue": "27.96900",
// "openFee": "0.02237520",
// "fundingFee": "0",
// "marginSize": "100",
// "isolatedMargin": "0",
// "isAutoAppendIsolatedMargin": false,
// "cumOpenSize": "300",
// "cumOpenValue": "27.96900",
// "cumOpenFee": "0.02237520",
// "cumCloseSize": "0",
// "cumCloseValue": "0",
// "cumCloseFee": "0",
// "cumFundingFee": "0",
// "cumLiquidateFee": "0",
// "createdMatchSequenceId": 5762536243,
// "updatedMatchSequenceId": 5762741613,
// "createdTime": 1775760234825,
// "updatedTime": 1775763170789,
// "unrealizePnl": "0.00600",
// "liquidatePrice": "0"
// }
//
// watchPoisions
// {
// "id": "739004481374519656",
// "coin": "USDT",
// "symbol": "DOGEUSDT",
// "side": "LONG",
// "marginMode": "CROSSED",
// "separatedMode": "COMBINED",
// "separatedOpenOrderId": "0",
// "leverage": "11",
// "size": "100",
// "openValue": "9.31100",
// "openFee": "0.00744880",
// "fundingFee": "0",
// "isolatedMargin": "0",
// "autoAppendIsolatedMargin": false,
// "cumOpenSize": "100",
// "cumOpenValue": "9.31100",
// "cumOpenFee": "0.00744880",
// "cumCloseSize": "0",
// "cumCloseValue": "0",
// "cumCloseFee": "0",
// "cumFundingFee": "0",
// "cumLiquidateFee": "0",
// "createdMatchSequenceId": "5792711540",
// "updatedMatchSequenceId": "5792711540",
// "createdTime": "1776192398399",
// "updatedTime": "1776192398399"
// }
//
let mut errorMessage: Value = self.safe_string_k(position.clone(), "errorMsg", &[]);
let mut errorCode: Value = self.safe_string_k(position.clone(), "errorCode", &[]);
if (errorMessage != Value::Null) {
self.handle_order_or_position_error(errorCode, errorMessage, position.clone());
}
let mut marketId: Value = self.from_sandbox_market_id(self.safe_string2(position.clone(), Value::Str("symbol".into()), Value::Str("coinId".into()), &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null); // coinId might be used in testnet: https://github.com/ccxt/ccxt/issues/28576#issuecomment-4439400273
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, Value::Str("contract".into())]);
let mut timestamp: Value = self.safe_integer_k(position.clone(), "createdTime", &[]);
let mut marginType: Option<String> = self.safe_string2(position.clone(), Value::Str("marginType".into()), Value::Str("marginMode".into()), &[]).as_str().map(str::to_owned);
let mut marginMode: Value = Value::Str("cross".into());
if (marginType.as_deref() == Some("ISOLATED")) {
marginMode = Value::Str("isolated".into());
}
let mut separatedMode: Option<String> = self.safe_string_k(position.clone(), "separatedMode", &[]).as_str().map(str::to_owned);
let mut hedged: Value = Value::Null;
if (separatedMode.as_deref() == Some("COMBINED")) {
hedged = Value::Bool(false);
} else if (separatedMode.as_deref() == Some("SEPARATED")) {
hedged = Value::Bool(true);
}
let mut notional: Value = self.safe_string_k(position.clone(), "openValue", &[]);
let mut size: Value = self.safe_string_k(position.clone(), "size", &[]);
let mut entryPrice: Value = crate::precise::Precise::stringDiv(¬ional, &size);
let mut unrealizePnl: Value = self.safe_string_k(position.clone(), "unrealizePnl", &[]);
let mut isolatedMargin: Value = self.omit_zero(self.safe_string2(position.clone(), Value::Str("isolatedMargin".into()), Value::Str("marginSize".into()), &[]));
let mut collateralString: Value = Value::Null;
if (marginMode.as_str() == Some("isolated")) && (isolatedMargin != Value::Null) {
collateralString = (if (unrealizePnl != Value::Null) { crate::precise::Precise::stringAdd(&isolatedMargin, &unrealizePnl) } else { isolatedMargin.clone() });
}
let mut initialMarginString: Value = self.omit_zero(self.safe_string2(position.clone(), Value::Str("marginSize".into()), Value::Str("isolatedMargin".into()), &[]));
let mut marginString: Value = Value::Null;
if (marginMode.as_str() == Some("isolated")) {
marginString = isolatedMargin;
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("id".to_string(), self.safe_string2(position.clone(), Value::Str("id".into()), Value::Str("positionId".into()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("contracts".to_string(), self.parse_number(size, &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("side".to_string(), self.safe_string_lower_k(position.clone(), "side", &[]));
m.insert("notional".to_string(), self.parse_number(notional, &[]));
m.insert("leverage".to_string(), self.safe_number_k(position.clone(), "leverage", &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizePnl, &[]));
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("positionMargin".to_string(), self.parse_number(marginString, &[]));
m.insert("collateral".to_string(), self.parse_number(collateralString, &[]));
m.insert("entryPrice".to_string(), self.parse_number(entryPrice, &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), self.parse_number(self.omit_zero(self.safe_string_k(position.clone(), "liquidatePrice", &[])), &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("hedged".to_string(), hedged);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.parse_number(initialMarginString, &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(position.clone(), "updatedTime", &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("info".to_string(), position);
m
}));
Value::Null
}
/*
* @method
* @name weex#closeAllPositions
* @description closes all open positions for a market type
* @see https://www.weex.com/api-doc/contract/Transaction_API/ClosePositions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} A list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn 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 response: Value = self.contract_private_post_capi_v3_close_positions(&[params]).await;
return self.parse_positions(response, &[]);
Value::Null
}
/*
* @method
* @name weex#closePosition
* @description closes open positions for a market
* @see https://www.weex.com/api-doc/contract/Transaction_API/ClosePositions
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] not used by current exchange
* @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 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 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_40 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_post_capi_v3_close_positions(&[__ws_arg_40]).await;
let mut order: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name weex#fetchTradingFee
* @see https://www.weex.com/api-doc/contract/Account_API/GetCommissionRate // contract
* @description fetch the trading fees for a contract market
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTradingFee() is not supported for spot 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_41 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_get_capi_v3_account_commission_rate(&[__ws_arg_41]).await;
return self.parse_trading_fee(response, &[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);
//
// contract
// {
// "symbol": "DOGEUSDT",
// "makerCommissionRate": "0.0002",
// "takerCommissionRate": "0.0008"
// }
//
let mut marketId: Value = self.safe_string_k(fee.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("contract".into())]));
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(true));
m.insert("tierBased".to_string(), Value::Bool(true));
m
});
Value::Null
}
/*
* @method
* @name weex#fetchMarginMode
* @description fetches the margin mode of a specific symbol
* @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} 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 __ws_arg_42 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_get_capi_v3_account_symbol_config(&[__ws_arg_42]).await;
//
// [
// {
// "symbol": "DOGEUSDT",
// "marginType": "CROSSED",
// "separatedType": "COMBINED",
// "crossLeverage": "20.00",
// "isolatedLongLeverage": "20.00",
// "isolatedShortLeverage": "20.00"
// }
// ]
//
let mut marginMode: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(marginMode, &[market]);
Value::Null
}
/*
* @method
* @name weex#fetchMarginModes
* @description fetches margin modes the symbols, with symbols=undefined all markets are returned
* @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
* @param {string[]} symbols unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [margin mode structures]{@link https://docs.ccxt.com/?id=margin-mode-structure}
*/
pub async fn fetch_margin_modes(&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 response: Value = self.contract_private_get_capi_v3_account_symbol_config(&[params]).await;
return self.parse_margin_modes(self.to_array(response), &[symbolsNormalized, Value::Str("symbol".into()), Value::Str("swap".into())]);
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_k(marginMode.clone(), "marginType", &[]);
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::Null, Value::Str("swap".into())]));
m.insert("marginMode".to_string(), self.parse_margin_type(marginType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parse_margin_type(&self, mut marginType: Value) -> Option<String> {
let mut marginTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CROSSED".to_string(), Value::Str("cross".into()));
m.insert("ISOLATED".to_string(), Value::Str("isolated".into()));
m
});
return self.safe_string(marginTypes, marginType.clone(), &[marginType.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name weex#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://www.weex.com/api-doc/contract/Account_API/ChangeMarginModeTRADE
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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(), self.encode_margin_mode(marginMode).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
let __ws_arg_43 = self.extend(request, &[params]);
return self.contract_private_post_capi_v3_account_margin_type(&[__ws_arg_43]).await;
Value::Null
}
pub fn encode_margin_mode(&self, mut marginMode: Value) -> Option<String> {
let mut marginTypes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cross".to_string(), Value::Str("CROSSED".into()));
m.insert("isolated".to_string(), Value::Str("ISOLATED".into()));
m
});
let mut result: Value = self.safe_string(marginTypes, marginMode, &[]);
if (result == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" marginMode must be either cross or isolated".into()))));
}
return result.as_str().map(str::to_owned);
}
/*
* @method
* @name weex#fetchLeverage
* @description fetch the set leverage for a market
* @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
* @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 __ws_arg_44 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_get_capi_v3_account_symbol_config(&[__ws_arg_44]).await;
let mut marginMode: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_leverage(marginMode, &[market]);
Value::Null
}
/*
* @method
* @name weex#fetchLeverages
* @description fetch the set leverage for all markets
* @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
* @param {string[]} [symbols] a list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverages(&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 response: Value = self.contract_private_get_capi_v3_account_symbol_config(&[params]).await;
return self.parse_leverages(self.to_array(response), &[symbolsNormalized, Value::Str("symbol".into()), Value::Str("swap".into())]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(leverage.clone(), "symbol", &[]);
let mut marginType: Value = self.safe_string_k(leverage.clone(), "marginType", &[]);
let mut marginMode: Value = self.parse_margin_type(marginType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut crossLeverage: Value = self.safe_number_k(leverage.clone(), "crossLeverage", &[]);
let mut longLeverage: Value = self.safe_number_k(leverage.clone(), "isolatedLongLeverage", &[]);
let mut shortLeverage: Value = self.safe_number_k(leverage.clone(), "isolatedShortLeverage", &[]);
if (marginMode.as_str() == Some("cross")) {
longLeverage = crossLeverage.clone();
shortLeverage = crossLeverage;
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage);
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market, Value::Null, Value::Str("swap".into())]));
m.insert("marginMode".to_string(), marginMode);
m.insert("longLeverage".to_string(), longLeverage);
m.insert("shortLeverage".to_string(), shortLeverage);
m
});
Value::Null
}
/*
* @method
* @name weex#setLeverage
* @description set the level of leverage for a market
* @see https://www.weex.com/api-doc/contract/Account_API/UpdateLeverageTRADE
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated' (default is 'cross' if specific leverage parameters are not provided)
* @param {number} [params.crossLeverage] *cross margin mode only* leverage for cross margin mode when marginMode is 'cross'
* @param {number} [params.isolatedLongLeverage] *isolated margin mode only* leverage for long positions when marginMode is 'isolated'
* @param {number} [params.isolatedShortLeverage] *isolated margin mode only* leverage for short positions when marginMode is 'isolated'
* If specific leverage parameters are not provided
* the leverage value will be applied to both long and short positions if marginMode is 'isolated'
* or to cross margin mode if marginMode is 'cross'
* If marginMode is not provided and specific leverage parameters are not provided too
* the leverage value will be applied to cross leverage
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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 marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("setLeverage".into()), &[params]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("marginType".into(), self.encode_margin_mode(marginMode.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
}
let mut isolatedLongLeverage: Option<f64> = self.safe_number_k(paramsMarginMode.clone(), "isolatedLongLeverage", &[]).as_f64();
let mut isolatedShortLeverage: Option<f64> = self.safe_number_k(paramsMarginMode.clone(), "isolatedShortLeverage", &[]).as_f64();
let mut crossLeverage: Option<f64> = self.safe_number_k(paramsMarginMode.clone(), "crossLeverage", &[]).as_f64();
if (isolatedLongLeverage.is_none()) && (isolatedShortLeverage.is_none()) && (crossLeverage.is_none()) {
if (marginMode.as_str() == Some("isolated")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("isolatedLongLeverage".into(), leverage.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("isolatedShortLeverage".into(), leverage.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("crossLeverage".into(), leverage); }
}
}
let __ws_arg_45 = self.extend(request, &[paramsMarginMode]);
return self.contract_private_post_capi_v3_account_leverage(&[__ws_arg_45]).await;
Value::Null
}
/*
* @method
* @name weex#fetchPositionMode
* @description fetchs the position mode, hedged or one way
* @see https://www.weex.com/api-doc/contract/Account_API/GetSymbolConfig
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an object detailing whether the market is in hedged or one-way mode
*/
pub async fn fetch_position_mode(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_46 = self.extend(request, &[params]);
let mut response: Value = self.contract_private_get_capi_v3_account_symbol_config(&[__ws_arg_46]).await;
let mut entry: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut separatedType: Option<String> = self.safe_string_k(entry, "separatedType", &[]).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(separatedType.as_deref() == Some("SEPARATED"))));
m
});
Value::Null
}
/*
* @method
* @name weex#setPositionMode
* @description set hedged to true or false for a market
* @see https://www.weex.com/api-doc/contract/Account_API/ChangeMarginModeTRADE
* @param {bool} hedged set to true to use dualSidePosition
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.marginMode 'cross' or 'isolated' (default is 'cross')
* @returns {object} response from the exchange
*/
pub async fn set_position_mode(&mut self, mut hedged: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setPositionMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("setPositionMode".into()), &[params]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setPositionMode() also sets marginMode, so a marginMode parameter is required".into()))));
}
let mut separatedType: Value = Value::Str("COMBINED".into());
if hedged.as_bool() == Some(true) {
separatedType = Value::Str("SEPARATED".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(), self.encode_margin_mode(marginMode).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("separatedType".to_string(), separatedType);
m
});
let __ws_arg_47 = self.extend(request, &[paramsMarginMode]);
return self.contract_private_post_capi_v3_account_margin_type(&[__ws_arg_47]).await;
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut isolatedPositionId: Value = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("positionId".into()), Value::Str("id".into()), Value::Str("isolatedPositionId".into())]), &[]);
if (isolatedPositionId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" modifyMarginHelper() requires a positionId parameter".into()))));
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("positionId".into()), Value::Str("id".into())]), &[]);
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isolatedPositionId".to_string(), isolatedPositionId);
m.insert("amount".to_string(), self.cost_to_precision(symbol, amount.clone()));
m.insert("type".to_string(), type_var.clone());
m
});
let mut parsedType: Value = Value::Str("reduce".into());
if (type_var.as_f64() == Some(1.0)) {
parsedType = Value::Str("add".into());
}
let __ws_arg_48 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.contract_private_post_capi_v3_account_position_margin(&[__ws_arg_48]).await;
let __ws_arg_49 = self.parse_margin_modification(response, &[market]);
let __ws_arg_50 = self.parse_number(amount, &[]);
return self.extend(__ws_arg_49, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), __ws_arg_50);
m.insert("type".to_string(), parsedType);
m
})]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "code": "200",
// "msg": "success",
// "requestTime": 1764505776347
// }
//
let mut msg: Option<String> = self.safe_string_k(data.clone(), "msg", &[]).as_str().map(str::to_owned);
let mut status: Value = Value::Str("failed".into());
if (msg.as_deref() == Some("success")) {
status = Value::Str("ok".into());
}
let mut timestamp: Value = self.safe_integer_k(data.clone(), "requestTime", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), self.safe_string_k(market, "settle", &[]));
m.insert("status".to_string(), status);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
/*
* @method
* @name weex#reduceMargin
* @description remove margin from a position
* @see https://www.weex.com/api-doc/contract/Account_API/AdjustPositionMarginTRADE
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.positionId the id of the position to reduce margin from, required
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Int(2), &[params]).await;
Value::Null
}
/*
* @method
* @name weex#addMargin
* @description add margin
* @see https://www.weex.com/api-doc/contract/Account_API/AdjustPositionMarginTRADE
* @param {string} symbol unified market symbol
* @param {float} amount amount of margin to add
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.positionId the id of the position to add margin to, required
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Int(1), &[params]).await;
Value::Null
}
/*
* @method
* @ignore
* @name weex#toSandboxMarketId
* @description get the market id to send in a request, converting to the demo-trading market id (e.g. BTCSUSDT) when sandbox mode is enabled, only valid for USDT-margined linear markets which is all the demo environment provides
* @param {object} market a unified market structure
* @returns {string} the market id for the request
*/
pub fn to_sandbox_market_id(&self, mut market: Value) -> Option<String> {
let __market_empty = indexmap::IndexMap::new();
let market = market.as_map().unwrap_or(&__market_empty);
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut baseId: Value = (match market.get("baseId") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if sandboxMode.as_bool() == Some(true) && (baseId != Value::Null) {
return Value::Str(format!("{}{}", baseId, Value::Str("SUSDT".into())).into()).as_str().map(str::to_owned);
}
return (match market.get("id") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
}
/*
* @method
* @ignore
* @name weex#fromSandboxMarketId
* @description convert a demo-trading market id (e.g. BTCSUSDT) from a response back into the live market id (e.g. BTCUSDT) when sandbox mode is enabled
* @param {string} [marketId] a market id from an exchange response
* @returns {string} the live market id
*/
pub fn from_sandbox_market_id(&self, mut marketId: Value) -> Option<String> {
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if (!(sandboxMode.as_bool() == Some(true))) || (marketId == Value::Null) {
return marketId.as_str().map(str::to_owned);
}
if (self.markets_by_id.clone() != Value::Null) && (matches!((&self.markets_by_id, &marketId), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
return marketId.as_str().map(str::to_owned);
}
if (marketId.as_str().is_some_and(|__s| __s.ends_with("SUSDT"))) {
let mut baseLength: Value = (match (&(Value::Int(marketId.len() as i64)), &(Value::Int(5))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
return Value::Str(format!("{}{}", (match (&(marketId), (match &(Value::Int(0)) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None }).unwrap_or(0), (match &(baseLength) { Value::Int(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b, __e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b, __e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null }), Value::Str("USDT".into())).into()).as_str().map(str::to_owned);
}
return marketId.as_str().map(str::to_owned);
}
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 sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut endpoint: Value = self.implode_params(path.clone(), params.clone());
let mut query: Value = self.omit(params, self.extract_params(path.clone()), &[]);
let mut isBatch: bool = Value::Int(path.as_str().and_then(|__s| __s.find("batch")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
if !isBatch && ((method.as_str() == Some("GET")) || (method.as_str() == Some("DELETE"))) {
if ((Value::Array(query.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).len() as i64) as f64) > ((0i64) as f64) {
endpoint = Value::Str(format!("{}{}", endpoint, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
}
let mut isPrivate: bool = (apiName.as_str() == Some("private")) || (apiName.as_str() == Some("contractPrivate"));
let mut hasJsonBody: bool = isPrivate && ((method.as_str() == Some("POST")) || isBatch);
let mut requestBody: Value = Value::Null;
if hasJsonBody {
requestBody = json_stringify(&query);
}
let mut requestHeaders: Value = Value::Null;
if isPrivate {
let mut sandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if sandboxMode.as_bool() == Some(true) && (Value::Int(path.as_str().and_then(|__s| __s.find("capi/v3/sim/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() != Some(0.0)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" is not available in sandbox mode, demo trading only supports fetchBalance, createOrder, fetchPositions, fetchClosedOrders and fetchCanceledOrders for swap markets".into()))));
}
self.check_required_credentials(&[]);
let mut timestamp: Value = self.number_to_string(self.nonce());
let mut payload: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, method).into()), Value::Str("/".into())).into()), endpoint).into());
if hasJsonBody {
payload = Value::Str(format!("{}{}", payload, requestBody).into());
}
let mut signature: Value = self.hmac(self.encode(payload), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("base64".into())]);
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("ACCESS-SIGN".to_string(), signature);
m.insert("ACCESS-PASSPHRASE".to_string(), self.password.clone());
m.insert("ACCESS-TIMESTAMP".to_string(), timestamp);
m
});
if (method.as_str() == Some("POST")) || (method.as_str() == Some("DELETE")) {
if let Value::Dict(__d) = &mut requestHeaders { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
}
} else {
requestHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("User-Agent".to_string(), Value::Str("ccxt".into()));
m
});
}
let mut baseApiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName, &[]);
if (baseApiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut baseUrl: Value = baseApiUrl;
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), endpoint).into());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), requestBody);
m.insert("headers".to_string(), requestHeaders);
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
//
// {
// "code": -1140,
// "msg": "Either orderId or origClientOrderId must be sent."
// }
//
let mut message: Value = self.safe_string_k(response.clone(), "msg", &[]);
if (message != Value::Null) {
let mut errorCode: Value = self.safe_string_k(response, "code", &[]);
if (errorCode.as_str() == Some("200")) && (message.as_str().map(|__s| Value::Str(__s.to_lowercase().into())).unwrap_or(Value::Null).as_str() == Some("success")) {
return Value::Null;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).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), errorCode, feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message, feedback);
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body)));
}
return Value::Null;
Value::Null
}
}