#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::exchange::CallDynamicChecked;
pub struct MudrexCore {
pub exchange: crate::exchange::Exchange,
}
impl MudrexCore {
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 = MudrexCore::describe(self);
self.initialize_properties(described);
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for MudrexCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
MudrexCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
MudrexCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
MudrexCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
MudrexCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
MudrexCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
MudrexCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
MudrexCore::parse_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
MudrexCore::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 {
MudrexCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for MudrexCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_mark_ohlcv" => self.fetch_mark_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_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_orders" => self.fetch_orders(&args[..]).await,
"fetch_orders_by_state" => self.fetch_orders_by_state(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_history" => self.fetch_positions_history(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"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)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for MudrexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for MudrexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl MudrexCore {
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("mudrex".into()));
m.insert("name".to_string(), Value::Str("Mudrex".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("IN".into())]));
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("dex".to_string(), Value::Bool(false));
m.insert("hostname".to_string(), Value::Str("trade.mudrex.com".into()));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createMarketOrder".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(false));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("watchOHLCV".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(true));
m.insert("watchTickers".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("3m".to_string(), Value::Str("3t".into()));
m.insert("5m".to_string(), Value::Str("5t".into()));
m.insert("10m".to_string(), Value::Str("10t".into()));
m.insert("15m".to_string(), Value::Str("15t".into()));
m.insert("30m".to_string(), Value::Str("30t".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1mth".into()));
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/72368864-84ed-43eb-8c75-d4fb77023b42".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://trade.mudrex.com/fapi/v1".into()));
m.insert("private".to_string(), Value::Str("https://trade.mudrex.com/fapi/v1".into()));
m.insert("market".to_string(), Value::Str("https://trade.mudrex.com/fapi/v1".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://mudrex.com".into()));
m.insert("doc".to_string(), Value::Str("https://docs.trade.mudrex.com/docs".into()));
m.insert("fees".to_string(), Value::Str("https://docs.trade.mudrex.com".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market".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("price/kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("price/mark-kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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("futures".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/{asset_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wallet/funds".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("futures/funds".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("futures/transactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/orders/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/positions/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/fee/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/{asset_id}/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/liq-price".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("wallet/futures/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("futures/transfers/inr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("futures/{asset_id}/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/close".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/close/partial".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/reverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/add-margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/positions/{position_id}/riskorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("futures/{asset_id}/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("patch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("futures/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("futures/positions/{position_id}/riskorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("futures/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00059".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00023".into()), &[]));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("broker".to_string(), Value::Str("42ce8902-8585-448c-a1e8-0371a6ca7ca8".into()));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("400 Invalid trade currency".to_string(), Value::Str("BadRequest".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Invalid trade currency".to_string(), Value::Str("BadRequest".into()));
m.insert("Params error".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid trigger type".to_string(), Value::Str("BadRequest".into()));
m.insert("invalid order type".to_string(), Value::Str("BadRequest".into()));
m.insert("order price out of permissible range".to_string(), Value::Str("BadRequest".into()));
m.insert("quantity not a multiple of the quantity step".to_string(), Value::Str("BadRequest".into()));
m.insert("leverage out of permissible range".to_string(), Value::Str("BadRequest".into()));
m.insert("insufficient balance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("asset not found".to_string(), Value::Str("BadSymbol".into()));
m.insert("leverage not found".to_string(), Value::Str("OrderNotFound".into()));
m.insert("order not found".to_string(), Value::Str("OrderNotFound".into()));
m.insert("Rate limit exceeded".to_string(), Value::Str("RateLimitExceeded".into()));
m
}));
m
}));
m
})]);
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut apiUrls: Value = self.safe_dict_k(self.urls.clone(), "api", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut base: Option<String> = self.safe_string_opt(apiUrls, apiName.clone(), &[]);
if (base.is_none()) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" unknown API namespace: ".into())).into()), apiName)));
}
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base.map(Value::from).unwrap_or(Value::Null), Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut requestHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut brokerId: Option<String> = self.safe_string_k_opt(self.options.clone(), "broker", &[]);
if (brokerId.is_some()) {
requestHeaders.insert("Partner-Id".into(), brokerId.map(Value::from).unwrap_or(Value::Null));
}
let mut methodUpper: Value = (if let Some(__s) = method.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
if (apiName.as_str() == Some("private")) {
self.check_required_credentials(&[]);
requestHeaders.insert("X-Authentication".into(), self.secret.clone());
if (methodUpper.as_str() == Some("POST")) || (methodUpper.as_str() == Some("PATCH")) || (methodUpper.as_str() == Some("DELETE")) {
requestHeaders.insert("Content-Type".into(), Value::Str("application/json".into()));
let mut isSymbol: Option<String> = self.safe_string_k_opt(query.clone(), "is_symbol", &[]);
if (isSymbol.is_some()) {
query = self.omit(query.clone(), Value::Str("is_symbol".into()), &[]);
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("is_symbol".to_string(), isSymbol.map(Value::from).unwrap_or(Value::Null));
m
}), &[])).into())).into());
}
if (methodUpper.as_str() == Some("DELETE")) && self.is_empty(query.clone()).as_bool() == Some(true) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), methodUpper.clone());
m.insert("body".to_string(), Value::Null);
m.insert("headers".to_string(), Value::Map(requestHeaders.clone()));
m
});
}
let mut bodyStr: Value = json_stringify(&query);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), methodUpper.clone());
m.insert("body".to_string(), bodyStr);
m.insert("headers".to_string(), Value::Map(requestHeaders.clone()));
m
});
}
}
if !(self.is_empty(query.clone()).as_bool() == Some(true)) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query, &[])).into())).into());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), methodUpper);
m.insert("body".to_string(), Value::Null);
m.insert("headers".to_string(), Value::Map(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 {
if (response == Value::Null) || !matches!(&response, Value::Dict(_)) {
return Value::Null;
}
let mut success: bool = self.safe_bool_k_opt(response.clone(), "success", &[Value::Bool(true)]).unwrap_or(true);
if !(success) {
let mut errors: Value = self.safe_list_k(response.clone(), "errors", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(errors, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut text: Value = self.safe_string_k(first.clone(), "text", &[json_stringify(&response)]);
let mut errCode: Option<String> = self.safe_string_k_opt(first, "code", &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), text.clone(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), text).into()));
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errCode.map(Value::from).unwrap_or(Value::Null), Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), text).into()));
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), text.clone(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), text).into()));
let mut msg: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), text).into());
let mut low: Value = (if let Some(__s) = text.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
if (code.as_f64() == Some(401.0)) || low.as_str().unwrap_or("").contains("auth") {
panic!("{}", crate::exchange_errors::authentication_error(msg));
}
if (code.as_f64() == Some(429.0)) || low.as_str().unwrap_or("").contains("rate") {
panic!("{}", crate::exchange_errors::rate_limit_exceeded(msg));
}
if low.as_str().unwrap_or("").contains("insufficient") {
panic!("{}", crate::exchange_errors::insufficient_funds(msg));
}
if (code.as_f64() == Some(400.0)) {
panic!("{}", crate::exchange_errors::bad_request(msg));
}
panic!("{}", crate::exchange_errors::exchange_error(msg));
}
return Value::Null;
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_timestamp(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
}
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut priceType: Option<String> = self.safe_string_k(params.clone(), "price", &[]).as_str().map(str::to_owned);
let baseIdString: String = self.safe_string_k_opt(market.clone(), "baseId", &[Value::Str("".into())]).unwrap_or_default();
let quoteIdString: String = self.safe_string_k_opt(market.clone(), "quoteId", &[Value::Str("".into())]).unwrap_or_default();
let mut assetPair: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseIdString, Value::Str("/".into())).into()), quoteIdString).into());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("assets".to_string(), assetPair.clone());
m.insert("aggregation".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut requestLimit: Value = (if (limit == Value::Null) { Value::Int(500) } else { limit.clone() });
let mut now: Value = self.seconds();
let mut windowLength: Value = (match (&(duration), &(requestLimit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
let mut defaultStart: Value = (match (&(now), &(windowLength)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut startTime: Value = self.parse_to_int((if (since != Value::Null) { ((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })) } else { defaultStart }));
let mut windowEnd: Value = self.parse_to_int((match (&(startTime), &((match (&(duration), &(requestLimit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("price".into()), Value::Str("until".into())]), &[]);
let mut cappedEnd: Value = (if (windowEnd.as_f64().unwrap_or(f64::NAN) > now.as_f64().unwrap_or(f64::NAN)) { now } else { windowEnd });
let mut endTime: Value = self.parse_to_int((if (until != Value::Null) { ((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })) } else { cappedEnd }));
request.insert("start_time".into(), startTime);
request.insert("end_time".into(), endTime);
let mut response: Value = Value::Null;
if (priceType.as_deref() == Some("mark")) {
let __ws_arg_0 = self.extend(Value::Map(request.clone()), &[paramsOmitted.clone()]);
response = self.market_get_price_mark_kline(&[__ws_arg_0]).await;
} else {
let __ws_arg_1 = self.extend(Value::Map(request), &[paramsOmitted]);
response = self.market_get_price_kline(&[__ws_arg_1]).await;
}
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut assetTicks: Value = self.safe_dict_k(data, "asset_ticks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ohlcvs: Value = self.safe_list(assetTicks, (if let Some(__s) = assetPair.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }), &[Value::from(vec![])]);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub async fn fetch_mark_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
}));
let __ws_arg_2 = self.extend(params, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("price".to_string(), Value::Str("mark".into()));
m
})]);
return self.fetch_ohlcv(symbol, &[timeframe, since, limit, __ws_arg_2]).await;
Value::Null
}
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("is_symbol".to_string(), Value::Int(1));
m
});
let __ws_arg_3 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_futures_asset_id(&[__ws_arg_3]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(data, &[market]);
Value::Null
}
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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_4 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_futures(&[__ws_arg_4]).await;
let mut data: Value = self.safe_value_k(response, "data", &[Value::from(vec![])]);
let mut rows: Value = Value::from(vec![]);
if (matches!(&data, Value::Arr(_))) {
rows = self.to_array(data.clone());
} else {
rows = self.safe_list_k(data, "items", &[Value::from(vec![])]);
}
let mut resultTickers: indexmap::IndexMap<String, Value> = {
let mut m = indexmap::IndexMap::new();
m
};
{
let mut i: i64 = 0;
let mut __for_first_970: bool = true;
while { if !__for_first_970 { i += 1; } __for_first_970 = false; i < (rows.len() as i64) } {
let mut t: Value = rows.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut sym: Option<String> = self.safe_string_k_opt(t.clone(), "symbol", &[]);
if (sym.is_none()) {
continue;
}
let mut m: Value = self.safe_market(&[sym.map(Value::from).unwrap_or(Value::Null)]);
let mut symbol: Value = m.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbols != Value::Null) && !(self.in_array(symbol.clone(), symbols.clone()).as_bool() == Some(true)) {
continue;
}
resultTickers.insert(crate::runtime::stringify_param(&symbol), self.parse_ticker(t, &[m]));
}
}
return self.filter_by_array_tickers(Value::Map(resultTickers), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut ms: Option<String> = self.safe_string_k_opt(ticker.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[ms.map(Value::from).unwrap_or(Value::Null), market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut pct: Value = self.safe_number_k(ticker.clone(), "change_perc", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), self.safe_number_k(ticker.clone(), "last_day_price", &[]));
m.insert("close".to_string(), self.safe_number_k(ticker.clone(), "price", &[]));
m.insert("last".to_string(), self.safe_number_k(ticker.clone(), "price", &[]));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), pct);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "volume", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut aggregated: Vec<Value> = Vec::new();
let mut offset: Value = Value::Int(0);
let mut pageLimit: i64 = 100;
let mut paging: bool = true;
while paging {
let mut q: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(pageLimit.clone()));
m.insert("offset".to_string(), offset.clone());
m
}), &[params.clone()]);
let mut response: Value = self.private_get_futures(&[q]).await;
let mut data: Value = self.safe_value_k(response, "data", &[Value::from(vec![])]);
let mut items: Value = Value::from(vec![]);
if matches!(&data, Value::Dict(_)) && !(matches!(&data, Value::Arr(_))) {
items = self.safe_list_k(data.clone(), "items", &[Value::from(vec![])]);
let mut itemsLength: i64 = items.len() as i64;
if (((itemsLength as f64) == 0.0)) {
items = self.safe_list_k(data.clone(), "results", &[Value::from(vec![])]);
itemsLength = items.len() as i64;
}
if (((itemsLength as f64) == 0.0)) && (in_op(&data, &Value::Str("symbol".into()))) {
items = Value::from(vec![data.clone()]);
}
} else {
items = self.to_array(data);
}
let mut numItems: f64 = ((items.len() as i64) as f64);
if (numItems == 0.0) {
paging = false;
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_971: bool = true;
while { if !__for_first_971 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_971 = false; i.as_f64().unwrap_or(f64::NAN) < numItems } {
aggregated.push(items.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
if numItems < (pageLimit as f64) {
paging = false;
} else {
offset = self.sum(&[offset.clone(), Value::Int(pageLimit.clone())]);
}
}
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_972: bool = true;
while { if !__for_first_972 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_972 = false; i.as_f64().unwrap_or(f64::NAN) < ((aggregated.len() as i64) as f64) } {
result.push(self.parse_market(aggregated.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)));
}
}
return Value::from(result);
Value::Null
}
pub fn parse_market(&self, mut asset: Value) -> Value {
let mut ms: Option<String> = self.safe_string_k_opt(asset.clone(), "symbol", &[]);
let mut base: Value = ms.clone().map(Value::from).unwrap_or(Value::Null);
if (ms.is_some()) && (ms.as_deref().unwrap_or("").ends_with("USDT")) {
base = ms.as_deref().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 4).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null);
}
let mut quote: String = "USDT".to_string();
let mut settle: String = "USDT".to_string();
let mut symbol: Value = Value::Null;
if (base != Value::Null) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), settle).into());
}
let mut priceStep: Value = self.safe_string_k(asset.clone(), "price_step", &[Value::Str("0.01".into())]);
let mut qtyStep: Value = self.safe_string_k(asset.clone(), "quantity_step", &[Value::Str("0.001".into())]);
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), ms.map(Value::from).unwrap_or(Value::Null));
m.insert("lowercaseId".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), Value::from(quote));
m.insert("settle".to_string(), Value::from(settle));
m.insert("baseId".to_string(), base);
m.insert("quoteId".to_string(), Value::Str("USDT".into()));
m.insert("settleId".to_string(), Value::Str("USDT".into()));
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(true));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("taker".into()), &[]));
m.insert("maker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("maker".into()), &[]));
m.insert("contractSize".to_string(), self.safe_number_k(asset.clone(), "contract_size", &[Value::Int(1)]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(qtyStep, &[]));
m.insert("price".to_string(), self.parse_number(priceStep, &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(asset.clone(), "min_contract", &[]));
m.insert("max".to_string(), self.safe_number_k(asset.clone(), "max_contract", &[]));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(asset.clone(), "min_price", &[]));
m.insert("max".to_string(), self.safe_number_k(asset.clone(), "max_price", &[]));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(asset.clone(), "min_notional_value", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), asset);
m.insert("created".to_string(), Value::Null);
m
})]);
Value::Null
}
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let type_varparamsMarketTypeVariable: Vec<Value> = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params, Value::Str("swap".into())]).as_array().cloned().unwrap_or_default();
let mut type_var: Value = type_varparamsMarketTypeVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.get(1).cloned().unwrap_or(Value::Null);
let mut requested: Option<String> = self.safe_string_n_opt(paramsMarketType.clone(), Value::from(vec![Value::Str("trade_currency".into()), Value::Str("tradeCurrency".into()), Value::Str("currency".into())]), &[]);
let mut paramsOmitted: Value = self.omit(paramsMarketType, Value::from(vec![Value::Str("trade_currency".into()), Value::Str("tradeCurrency".into()), Value::Str("currency".into())]), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
if (requested.is_some()) {
request.insert("currency".into(), requested.clone().map(Value::from).unwrap_or(Value::Null));
}
let __ws_arg_5 = self.extend(Value::Map(request.clone()), &[paramsOmitted.clone()]);
response = self.private_get_wallet_funds(&[__ws_arg_5]).await;
} else {
if (requested.is_some()) {
request.insert("trade_currency".into(), requested.clone().map(Value::from).unwrap_or(Value::Null));
}
let __ws_arg_6 = self.extend(Value::Map(request), &[paramsOmitted]);
response = self.private_get_futures_funds(&[__ws_arg_6]).await;
}
let mut currency: Value = requested.map(Value::from).unwrap_or(Value::Null);
if (currency == Value::Null) {
currency = Value::Str("USDT".into());
}
if (response == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance() returned empty response".into()))));
}
let __ws_arg_7 = self.extend(response, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currency);
m
})]);
return self.parse_balance(__ws_arg_7);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currency: Value = self.safe_string_k(response.clone(), "currency", &[Value::Str("USDT".into())]);
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
let mut account: indexmap::IndexMap<String, Value> = self.account().as_map().cloned().unwrap_or_default();
let mut futuresBalance: Option<String> = self.safe_string_k_opt(data.clone(), "balance", &[]);
if (futuresBalance.is_some()) {
account.insert("free".into(), futuresBalance.map(Value::from).unwrap_or(Value::Null));
account.insert("used".into(), self.safe_string_k(data.clone(), "locked_amount", &[]));
} else {
account.insert("total".into(), self.safe_string_k(data.clone(), "total", &[]));
account.insert("free".into(), self.safe_string_k(data, "withdrawable", &[]));
}
result.insert(crate::runtime::stringify_param(¤cy), Value::Map(account));
return self.safe_balance(Value::Map(result));
Value::Null
}
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: indexmap::IndexMap<String, Value> = self.market(symbol.clone()).as_map().cloned().unwrap_or_default();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_id".to_string(), market.get("id").cloned().unwrap_or(Value::Null));
m.insert("is_symbol".to_string(), Value::Int(1));
m
});
let __ws_arg_8 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_futures_asset_id_leverage(&[__ws_arg_8]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("symbol".to_string(), symbol);
m.insert("marginMode".to_string(), self.safe_string_lower_k(data.clone(), "margin_type", &[]));
m.insert("longLeverage".to_string(), self.safe_number_k(data.clone(), "leverage", &[]));
m.insert("shortLeverage".to_string(), self.safe_number_k(data, "leverage", &[]));
m
});
Value::Null
}
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".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut marginType: Value = self.safe_string_k(params.clone(), "marginType", &[Value::Str("ISOLATED".into())]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_id".to_string(), market.get("id").cloned().unwrap_or(Value::Null));
m.insert("is_symbol".to_string(), Value::Int(1));
m.insert("margin_type".to_string(), marginType);
m.insert("leverage".to_string(), leverage);
m
});
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("marginType".into())]), &[]);
let __ws_arg_9 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_post_futures_asset_id_leverage(&[__ws_arg_9]).await;
return response;
Value::Null
}
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut stopLossPrice: Option<String> = self.safe_string_k_opt(params.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Option<String> = self.safe_string_k_opt(params.clone(), "takeProfitPrice", &[]);
if (stopLossPrice.is_some()) || (takeProfitPrice.is_some()) {
let mut positionId: Option<String> = self.safe_string2_opt(params.clone(), Value::Str("positionId".into()), Value::Str("position_id".into()), &[]);
if (positionId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a positionId parameter to place a stopLossPrice or takeProfitPrice order".into()))));
}
let mut paramsOmitted: Value = self.omit(params.clone(), Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("positionId".into()), Value::Str("position_id".into())]), &[]);
let mut riskRequest: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId.map(Value::from).unwrap_or(Value::Null));
m
});
if (takeProfitPrice.is_some()) {
riskRequest.insert("is_takeprofit".into(), Value::Bool(true));
riskRequest.insert("takeprofit_price".into(), self.price_to_precision(symbol.clone(), takeProfitPrice.map(Value::from).unwrap_or(Value::Null)));
}
if (stopLossPrice.is_some()) {
riskRequest.insert("is_stoploss".into(), Value::Bool(true));
riskRequest.insert("stoploss_price".into(), self.price_to_precision(symbol.clone(), stopLossPrice.map(Value::from).unwrap_or(Value::Null)));
}
let __ws_arg_10 = self.extend(Value::Map(riskRequest), &[paramsOmitted]);
let mut riskResponse: Value = self.private_post_futures_positions_position_id_riskorder(&[__ws_arg_10]).await;
let mut riskData: Value = self.safe_dict_k(riskResponse.clone(), "data", &[riskResponse.clone()]);
return self.parse_order(riskData, &[market.clone()]);
}
let mut lev: Value = self.safe_integer_k(params.clone(), "leverage", &[Value::Int(1)]);
if (type_var.as_str() == Some("market")) && (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument for market orders".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("is_symbol".to_string(), Value::Int(1));
m.insert("leverage".to_string(), self.number_to_string(lev));
m.insert("quantity".to_string(), self.amount_to_precision(symbol.clone(), amount));
m.insert("order_price".to_string(), self.price_to_precision(symbol.clone(), price));
m.insert("order_type".to_string(), (if (side.as_str() == Some("buy")) { Value::Str("LONG".into()) } else { Value::Str("SHORT".into()) }));
m.insert("trigger_type".to_string(), (if (type_var.as_str() == Some("market")) { Value::Str("MARKET".into()) } else { Value::Str("LIMIT".into()) }));
m.insert("reduce_only".to_string(), self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]));
m
});
let mut takeProfit: Value = self.safe_dict_k(params.clone(), "takeProfit", &[]);
let mut stopLoss: Value = self.safe_dict_k(params.clone(), "stopLoss", &[]);
if (takeProfit != Value::Null) {
request.insert("is_takeprofit".into(), Value::Bool(true));
request.insert("takeprofit_price".into(), self.price_to_precision(symbol.clone(), self.safe_string_n(takeProfit, Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("price".into())]), &[])));
}
if (stopLoss != Value::Null) {
request.insert("is_stoploss".into(), Value::Bool(true));
request.insert("stoploss_price".into(), self.price_to_precision(symbol, self.safe_string_n(stopLoss, Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("price".into())]), &[])));
}
let mut orderParams: Value = self.omit(params, Value::from(vec![Value::Str("leverage".into()), Value::Str("reduceOnly".into()), Value::Str("takeProfit".into()), Value::Str("stopLoss".into())]), &[]);
let __ws_arg_11 = self.extend(Value::Map(request.clone()), &[orderParams]);
let mut response: Value = self.private_post_futures_asset_id_order(&[__ws_arg_11]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
let mut merged: Value = self.extend(data.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_type".to_string(), request.get("order_type").cloned().unwrap_or(Value::Null));
m.insert("trigger_type".to_string(), request.get("trigger_type").cloned().unwrap_or(Value::Null));
m
})]);
let mut order: indexmap::IndexMap<String, Value> = self.parse_order(merged, &[market]).as_map().cloned().unwrap_or_default();
order.insert("info".into(), data);
return Value::Map(order);
Value::Null
}
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
if (amount != Value::Null) {
request.insert("quantity".into(), self.amount_to_precision(symbol.clone(), amount));
}
if (price != Value::Null) {
request.insert("order_price".into(), self.price_to_precision(symbol, price));
}
let __ws_arg_12 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_patch_futures_orders_order_id(&[__ws_arg_12]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
return self.parse_order(data, &[market]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("created".to_string(), Value::Str("open".into()));
m.insert("new".to_string(), Value::Str("open".into()));
m.insert("pending".to_string(), Value::Str("open".into()));
m.insert("partially_filled".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("completed".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("expired".to_string(), Value::Str("expired".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut oms: Option<String> = self.safe_string_k_opt(order.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[oms.map(Value::from).unwrap_or(Value::Null), market]);
let mut oid: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("order_id".into()), Value::Str("id".into()), &[]);
let mut rawSide: Option<String> = self.safe_string_upper_k(order.clone(), "order_type", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("LONG")) {
side = Value::Str("buy".into());
} else if (rawSide.as_deref() == Some("SHORT")) {
side = Value::Str("sell".into());
}
let mut isRiskOrder: bool = (rawSide.as_deref() == Some("STOPLOSS")) || (rawSide.as_deref() == Some("TAKEPROFIT"));
let mut priceString: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("price".into()), Value::Str("order_price".into()), &[]);
let mut orderPrice: Value = priceString.clone().map(Value::from).unwrap_or(Value::Null);
let mut triggerPrice: Value = Value::Null;
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if isRiskOrder {
triggerPrice = priceString.clone().map(Value::from).unwrap_or(Value::Null);
orderPrice = Value::Null;
if (rawSide.as_deref() == Some("STOPLOSS")) {
stopLossPrice = priceString.clone().map(Value::from).unwrap_or(Value::Null);
} else {
takeProfitPrice = priceString.map(Value::from).unwrap_or(Value::Null);
}
}
let mut trig: Option<String> = self.safe_string_upper_k(order.clone(), "trigger_type", &[]).as_str().map(str::to_owned);
let mut typ: Value = Value::Null;
if (trig.as_deref() == Some("MARKET")) {
typ = Value::Str("market".into());
} else if (trig.as_deref() == Some("LIMIT")) {
typ = Value::Str("limit".into());
}
let mut ts: Value = self.parse8601(self.safe_string_k(order.clone(), "created_at", &[]));
let mut status: Value = self.parse_order_status(self.safe_string_lower_k(order.clone(), "status", &[])).map(Value::from).unwrap_or(Value::Null);
let mut sym: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), oid.map(Value::from).unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), sym);
m.insert("type".to_string(), typ);
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), orderPrice);
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), self.safe_string2(order.clone(), Value::Str("quantity".into()), Value::Str("amount".into()), &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string_k(order.clone(), "filled_price", &[]));
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "filled_quantity", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m.insert("fees".to_string(), Value::from(vec![]));
m.insert("lastUpdateTimestamp".to_string(), self.parse8601(self.safe_string_k(order.clone(), "updated_at", &[])));
m.insert("reduceOnly".to_string(), self.safe_bool_k(order, "reduce_only", &[]));
m
}), &[marketResolved]);
Value::Null
}
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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_delete_futures_orders_order_id(&[__ws_arg_13]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
return self.parse_order(data, &[market]);
Value::Null
}
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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_futures_orders_order_id(&[__ws_arg_14]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
return self.parse_order(data, &[market]);
Value::Null
}
pub async fn fetch_orders_by_state(&mut self, mut state: 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 q: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
q.insert("limit".into(), limit.clone());
}
let mut request: Value = self.extend(Value::Map(q), &[params]);
let mut response: Value = Value::Null;
if (state.as_str() == Some("closed")) {
response = self.private_get_futures_orders_history(&[request.clone()]).await;
} else {
response = self.private_get_futures_orders(&[request]).await;
}
let mut data: Value = self.safe_value_k(response, "data", &[Value::from(vec![])]);
let mut rows: Value = self.to_array(data);
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut orders: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_973: bool = true;
while { if !__for_first_973 { i += 1; } __for_first_973 = false; i < (rows.len() as i64) } {
orders.push(self.parse_order(rows.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null), &[market.clone()]));
}
}
return self.filter_by_symbol_since_limit(Value::from(orders), &[symbol, since, limit]);
Value::Null
}
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
}));
return self.fetch_orders_by_state(Value::Str("closed".into()), &[symbol, since, limit, params]).await;
Value::Null
}
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_state(Value::Str("open".into()), &[symbol, since, limit, params]).await;
Value::Null
}
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_state(Value::Str("closed".into()), &[symbol, since, limit, params]).await;
Value::Null
}
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 q: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_15 = self.extend(Value::Map(q), &[params]);
let mut response: Value = self.private_get_futures_positions(&[__ws_arg_15]).await;
let mut data: Value = self.safe_value_k(response, "data", &[Value::from(vec![])]);
if (data == Value::Null) {
return Value::from(vec![]);
}
let mut rows: Value = self.to_array(data);
let mut outPos: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_974: bool = true;
while { if !__for_first_974 { i += 1; } __for_first_974 = false; i < (rows.len() as i64) } {
let mut p: Value = rows.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut symRaw: Option<String> = self.safe_string_k_opt(p.clone(), "symbol", &[]);
let mut m: Value = self.safe_market(&[symRaw.map(Value::from).unwrap_or(Value::Null)]);
let mut pos: Value = self.parse_position(p, &[m]);
outPos.push(pos);
}
}
return self.filter_by_array_positions(Value::from(outPos), Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub async fn fetch_positions_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
request.insert("limit".into(), limit.clone());
}
let __ws_arg_16 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_futures_positions_history(&[__ws_arg_16]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[symbolsNormalized]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketResolved: Value = self.safe_market(&[Value::Null, market]);
let mut ms: Option<String> = self.safe_string_k_opt(position.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(ms.map(Value::from).unwrap_or(Value::Null), &[marketResolved.clone()]);
let mut rawSide: Option<String> = self.safe_string_upper2(position.clone(), Value::Str("order_type".into()), Value::Str("position_type".into()), &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("LONG")) {
side = Value::Str("long".into());
} else if (rawSide.as_deref() == Some("SHORT")) {
side = Value::Str("short".into());
}
let mut ts: Value = self.parse8601(self.safe_string_k(position.clone(), "updated_at", &[]));
if (ts == Value::Null) {
ts = self.parse8601(self.safe_string_k(position.clone(), "created_at", &[]));
}
let mut quantityString: Option<String> = self.safe_string_k_opt(position.clone(), "quantity", &[]);
let mut entryPriceString: Option<String> = self.safe_string_k_opt(position.clone(), "entry_price", &[]);
let mut contractSizeString: Value = self.safe_string_k(marketResolved.clone(), "contractSize", &[Value::Str("1".into())]);
let mut notional: Value = Value::Null;
if (quantityString.is_some()) && (entryPriceString.is_some()) {
notional = self.parse_number(crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&quantityString.clone().map(Value::from).unwrap_or(Value::Null), &entryPriceString.clone().map(Value::from).unwrap_or(Value::Null)), &contractSizeString), &[]);
}
let mut initialMargin: Option<String> = self.safe_string_k_opt(position.clone(), "initial_margin", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("isolated".to_string(), Value::Bool(true));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "quantity", &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "entry_price", &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), self.safe_number_k(position.clone(), "closed_price", &[]));
m.insert("notional".to_string(), notional);
m.insert("leverage".to_string(), self.safe_integer_k(position.clone(), "leverage", &[]));
m.insert("positionMargin".to_string(), self.parse_number(initialMargin.clone().map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("collateral".to_string(), self.parse_number(initialMargin.clone().map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMargin.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), self.safe_number_k(position.clone(), "maintenance_margin", &[]));
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), Value::Null);
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "pnl", &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(position, "liquidation_price", &[]));
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("percentage".to_string(), Value::Null);
m
});
Value::Null
}
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.clone());
let mut positionId: Option<String> = self.safe_string_k_opt(params.clone(), "position_id", &[]);
let mut amount: Value = self.safe_value_k(params.clone(), "amount", &[]);
if (positionId.is_none()) {
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol.clone()]), params.clone()]).await;
let mut candidates: Value = self.filter_by(positions, Value::Str("symbol".into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[]);
if (side != Value::Null) {
candidates = self.filter_by(candidates.clone(), Value::Str("side".into()), side, &[]);
}
let mut numCandidates: f64 = ((candidates.len() as i64) as f64);
if numCandidates > ((0i64) as f64) {
let mut found: Value = candidates.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
positionId = self.safe_string_k_opt(found, "id", &[]);
}
}
if (positionId.is_none()) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", self.id.clone(), Value::Str(" closePosition() could not resolve position_id".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId.map(Value::from).unwrap_or(Value::Null));
m
});
if (amount != Value::Null) {
let mut orderType: Value = self.safe_string_upper_k(params.clone(), "order_type", &[Value::Str("LIMIT".into())]);
request.insert("order_type".into(), orderType.clone());
request.insert("quantity".into(), self.amount_to_precision(symbol, amount));
let mut lp: Option<String> = self.safe_string_k_opt(params.clone(), "limit_price", &[]);
if (orderType.as_str() == Some("LIMIT")) && (lp.is_some()) {
request.insert("limit_price".into(), lp.map(Value::from).unwrap_or(Value::Null));
}
let mut partialParams: Value = self.omit(params.clone(), Value::from(vec![Value::Str("order_type".into()), Value::Str("limit_price".into()), Value::Str("amount".into()), Value::Str("position_id".into())]), &[]);
let __ws_arg_17 = self.extend(Value::Map(request.clone()), &[partialParams]);
let mut partialResponse: Value = self.private_post_futures_positions_position_id_close_partial(&[__ws_arg_17]).await;
let mut partialData: Value = self.safe_dict_k(partialResponse.clone(), "data", &[partialResponse.clone()]);
return self.parse_order(partialData, &[market.clone()]);
}
let mut closeParams: Value = self.omit(params, Value::from(vec![Value::Str("position_id".into())]), &[]);
let __ws_arg_18 = self.extend(Value::Map(request), &[closeParams]);
let mut response: Value = self.private_post_futures_positions_position_id_close(&[__ws_arg_18]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
return self.parse_order(data, &[market]);
Value::Null
}
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut positionId: Option<String> = self.safe_string_k_opt(params.clone(), "position_id", &[]);
if (positionId.is_none()) {
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol.clone()]), params.clone()]).await;
let mut matches: Value = self.filter_by(positions, Value::Str("symbol".into()), symbol.clone(), &[]);
let mut numMatches: f64 = ((matches.len() as i64) as f64);
if numMatches > ((0i64) as f64) {
let mut found: Value = matches.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
positionId = self.safe_string_k_opt(found, "id", &[]);
}
}
if (positionId.is_none()) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", self.id.clone(), Value::Str(" addMargin() could not resolve position_id".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId.map(Value::from).unwrap_or(Value::Null));
m.insert("margin".to_string(), self.cost_to_precision(symbol, amount));
m
});
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("position_id".into())]), &[]);
let __ws_arg_19 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.private_post_futures_positions_position_id_add_margin(&[__ws_arg_19]).await;
return self.extend(response, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.add_margin(symbol, (match &(amount) { Value::Int(x) => Value::Int(-x), Value::Float(x) => Value::Float(-x), _ => Value::Null }), &[params]).await;
Value::Null
}
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);
}
let maxCallsparamsPaginationCallsVariable: Vec<Value> = self.handle_option_integer_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginationCalls".into()), &[Value::Int(10)]).as_array().cloned().unwrap_or_default();
let mut maxCalls: Value = maxCallsparamsPaginationCallsVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginationCalls: Value = maxCallsparamsPaginationCallsVariable.get(1).cloned().unwrap_or(Value::Null);
let mut pageSize: Value = (if (limit == Value::Null) { Value::Int(0) } else { (match (&(limit), &(Value::Int(2))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }) });
let mut allRows: Vec<Value> = Vec::new();
let mut transactionsCount: Value = self.parse_to_int(Value::Int(0));
let mut calls: Value = self.parse_to_int(Value::Int(0));
let mut offset: Value = Value::Int(0);
let mut paging: bool = true;
while paging {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) && (limit.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
request.insert("limit".into(), pageSize.clone());
request.insert("offset".into(), offset.clone());
}
let __ws_arg_20 = self.extend(Value::Map(request), &[paramsPaginationCalls.clone()]);
let mut response: Value = self.private_get_futures_fee_history(&[__ws_arg_20]).await;
let mut data: Vec<Value> = self.safe_list_k(response, "data", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut dataLength: Value = Value::Int(data.len() as i64);
{
let mut i: i64 = 0;
let mut __for_first_975: bool = true;
while { if !__for_first_975 { i += 1; } __for_first_975 = false; i < (data.len() as i64) } {
let mut entry: Value = data.get(i as usize).cloned().unwrap_or(Value::Null);
allRows.push(entry.clone());
if (self.safe_string_k(entry.clone(), "fee_type", &[]).as_str() == Some("TRANSACTION")) {
if (market == Value::Null) || (self.safe_string_k(entry.clone(), "symbol", &[]).as_str() == market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null).as_str()) {
transactionsCount = self.parse_to_int((match (&(transactionsCount), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
}
}
}
}
calls = self.parse_to_int((match (&(calls), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
paging = false;
if (limit != Value::Null) && (dataLength.as_f64() == pageSize.as_f64()) {
if (transactionsCount.as_f64().unwrap_or(f64::NAN) < limit.as_f64().unwrap_or(f64::NAN)) && (calls.as_f64().unwrap_or(f64::NAN) < maxCalls.as_f64().unwrap_or(f64::NAN)) {
offset = self.sum(&[offset.clone(), pageSize.clone()]);
paging = true;
}
}
}
let mut rebateKeys: Value = Value::from(vec![]);
let mut rebateAmounts: Value = Value::from(vec![]);
let mut transactions: Vec<Value> = Vec::new();
let mut transactionKeys: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_976: bool = true;
while { if !__for_first_976 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_976 = false; i.as_f64().unwrap_or(f64::NAN) < ((allRows.len() as i64) as f64) } {
let mut entry: Value = allRows.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut feeType: Option<String> = self.safe_string_k(entry.clone(), "fee_type", &[]).as_str().map(str::to_owned);
let mut pairKey: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.safe_string_k(entry.clone(), "symbol", &[Value::Str("".into())]), Value::Str(":".into())).into()), self.safe_string_k(entry.clone(), "created_at", &[Value::Str("".into())])).into()),
Value::Str(":".into())).into()), self.safe_string_k(entry.clone(), "transaction_amount", &[Value::Str("".into())])).into());
if (feeType.as_deref() == Some("TRANSACTION")) {
transactions.push(entry.clone());
transactionKeys.push(pairKey.clone());
} else if (feeType.as_deref() == Some("REBATE")) {
if let Value::Arr(__a) = &mut rebateKeys { std::sync::Arc::make_mut(__a).push(pairKey); }
if let Value::Arr(__a) = &mut rebateAmounts { std::sync::Arc::make_mut(__a).push(self.safe_string_k(entry, "fee_amount", &[Value::Str("0".into())])); }
}
}
}
let mut rows: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_978: bool = true;
while { if !__for_first_978 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_978 = false; i.as_f64().unwrap_or(f64::NAN) < ((transactions.len() as i64) as f64) } {
let mut rebate: Value = Value::Null;
{
let mut j: Value = Value::Int(0);
let mut __for_first_977: bool = true;
while { if !__for_first_977 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_977 = false; j.as_f64().unwrap_or(f64::NAN) < ((rebateKeys.len() as i64) as f64) } {
if (rebateKeys.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null).as_str() == transactionKeys.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null).as_str()) {
rebate = self.safe_string(rebateAmounts.clone(), j.clone(), &[]);
add_element_to_object(&mut rebateKeys, &j, Value::Str("".into()));
break;
}
}
}
if (rebate == Value::Null) {
rows.push(transactions.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
} else {
rows.push(self.extend(transactions.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rebate_amount".to_string(), rebate);
m
})]));
}
}
}
return self.parse_trades(Value::from(rows), &[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);
let mut ms: Option<String> = self.safe_string_k_opt(trade.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[ms.map(Value::from).unwrap_or(Value::Null), market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut ts: Value = self.parse8601(self.safe_string_k(trade.clone(), "created_at", &[]));
let mut side: Option<String> = self.safe_string_lower_k(trade.clone(), "order_type", &[]).as_str().map(str::to_owned);
let mut tradeSide: Value = Value::Null;
if (side.as_deref() == Some("long")) {
tradeSide = Value::Str("buy".into());
} else if (side.as_deref() == Some("short")) {
tradeSide = Value::Str("sell".into());
}
let mut trig: Option<String> = self.safe_string_upper_k(trade.clone(), "trigger_type", &[]).as_str().map(str::to_owned);
let mut takerOrMaker: Value = Value::Null;
if (trig.as_deref() == Some("MARKET")) {
takerOrMaker = Value::Str("taker".into());
}
let mut fee: Value = Value::Null;
let mut feeCostString: Value = self.safe_string_k(trade.clone(), "fee_amount", &[]);
let mut rebateString: Option<String> = self.safe_string_k_opt(trade.clone(), "rebate_amount", &[]);
if (feeCostString != Value::Null) && (rebateString.is_some()) {
feeCostString = crate::precise::Precise::stringSub(&feeCostString, &rebateString.clone().map(Value::from).unwrap_or(Value::Null));
}
if (feeCostString != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCostString);
m.insert("currency".to_string(), self.safe_string_k(trade.clone(), "trade_currency", &[]));
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "id", &[]));
m.insert("order".to_string(), Value::Null);
m.insert("type".to_string(), self.safe_string_lower_k(trade.clone(), "trigger_type", &[]));
m.insert("side".to_string(), tradeSide);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), Value::Null);
m.insert("amount".to_string(), Value::Null);
m.insert("cost".to_string(), self.safe_string_k(trade, "transaction_amount", &[]));
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut mp: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("SPOT".into()));
m.insert("SPOT".to_string(), Value::Str("SPOT".into()));
m.insert("futures".to_string(), Value::Str("FUTURES".into()));
m.insert("future".to_string(), Value::Str("FUTURES".into()));
m.insert("FUTURES".to_string(), Value::Str("FUTURES".into()));
m
});
let mut fw: Value = self.safe_string(mp.clone(), fromAccount.clone(), &[(if let Some(__s) = fromAccount.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null })]);
let mut tw: Value = self.safe_string(mp, toAccount.clone(), &[(if let Some(__s) = toAccount.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null })]);
let mut body: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("from_wallet_type".to_string(), fw.clone());
m.insert("to_wallet_type".to_string(), tw.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m
});
let mut useInr: bool = false;
if (code.as_str() == Some("INR")) {
useInr = true;
} else {
let mut tradeCurrency: Option<String> = self.safe_string2(params.clone(), Value::Str("trade_currency".into()), Value::Str("tradeCurrency".into()), &[]).as_str().map(str::to_owned);
if (tradeCurrency.as_deref() == Some("INR")) {
useInr = true;
}
}
let mut response: Value = Value::Null;
if useInr {
let __ws_arg_21 = self.extend(Value::Map(body.clone()), &[params.clone()]);
response = self.private_post_futures_transfers_inr(&[__ws_arg_21]).await;
} else {
let __ws_arg_22 = self.extend(Value::Map(body), &[params]);
response = self.private_post_wallet_futures_transfer(&[__ws_arg_22]).await;
}
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("id".to_string(), self.safe_string_k(data, "id", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), amount);
m.insert("fromAccount".to_string(), fw);
m.insert("toAccount".to_string(), tw);
m.insert("status".to_string(), Value::Str("ok".into()));
m
});
Value::Null
}
}