// 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 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);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for MudrexCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
MudrexCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on MudrexCore.
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 {
// Forward to the inherent method on MudrexCore.
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 {
// Forward to the inherent method on MudrexCore.
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,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => 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()).clone());
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()).clone());
m.insert("Params error".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("invalid trigger type".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("invalid order type".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("order price out of permissible range".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("quantity not a multiple of the quantity step".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("leverage out of permissible range".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("insufficient balance".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("asset not found".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("leverage not found".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("order not found".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("Rate limit exceeded".to_string(), Value::Str("RateLimitExceeded".into()).clone());
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::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut apiUrls: Value = self.safe_dict_k(self.urls.clone(), "api", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut base: Value = self.safe_string(apiUrls, api.clone(), &[]);
if (base == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" unknown API namespace: ".into())).into()), api)));
}
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (headers != Value::Null) {
requestHeaders = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[headers]);
}
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "broker", &[]);
if (brokerId != Value::Null) {
add_element_to_object(&mut requestHeaders, &Value::Str("Partner-Id".into()), brokerId);
}
let mut methodUpper: Value = to_upper(&method);
if (api.as_str() == Some("private")) {
self.check_required_credentials(&[]);
add_element_to_object(&mut requestHeaders, &Value::Str("X-Authentication".into()), self.secret.clone());
if (methodUpper.as_str() == Some("POST")) || (methodUpper.as_str() == Some("PATCH")) || (methodUpper.as_str() == Some("DELETE")) {
add_element_to_object(&mut requestHeaders, &Value::Str("Content-Type".into()), Value::Str("application/json".into()));
// is_symbol is a query-string flag even on write requests
let mut isSymbol: Value = self.safe_string_k(query.clone(), "is_symbol", &[]);
if (isSymbol != Value::Null) {
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);
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(), 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(), requestHeaders.clone());
m
});
}
}
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
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(), 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: Value = self.safe_bool_k(response.clone(), "success", &[Value::Bool(true)]);
if (success.as_bool() != Some(true)) {
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: Value = self.safe_string_k(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, 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 = to_lower(&text);
if (code.as_f64() == Some(401.0)) || Value::Int(low.as_str().and_then(|__s| __s.find("auth")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
panic!("{}", crate::exchange_errors::authentication_error(msg));
}
if (code.as_f64() == Some(429.0)) || Value::Int(low.as_str().and_then(|__s| __s.find("rate")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
panic!("{}", crate::exchange_errors::rate_limit_exceeded(msg));
}
if Value::Int(low.as_str().and_then(|__s| __s.find("insufficient")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
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
}
/*
* @method
* @name mudrex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.trade.mudrex.com/docs/historical-kline
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @param {string} [params.price] "mark" to fetch mark price candles
* @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);
let mut priceType: Option<String> = self.safe_string_k(params.clone(), "price", &[]).as_str().map(str::to_owned);
params = self.omit(params.clone(), Value::Str("price".into()), &[]);
// the endpoint expects the pair in "BASE/QUOTE" format (comma-separated for multiple)
let mut assetPair: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), Value::Str("/".into())).into()), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)).into());
let mut request: Value = Value::Map({
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
});
// the endpoint requires an explicit time window (in seconds)
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut requestLimit: Value = limit.clone();
if (requestLimit == Value::Null) {
requestLimit = Value::Int(500);
}
let mut now: Value = self.seconds();
let mut startTime: Value = Value::Null;
if (since != Value::Null) {
startTime = self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
} else {
startTime = (match (&(now), &((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 });
}
if (startTime == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() missing startTime".into()))));
}
let mut endTime: Value = (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", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
endTime = self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
} else if 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("start_time".into(), startTime); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_time".into(), endTime); }
let mut response: Value = Value::Null;
if (priceType.as_deref() == Some("mark")) {
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
response = self.market_get_price_mark_kline(&[__ws_arg_0]).await;
} else {
let __ws_arg_1 = self.extend(request, &[params]);
response = self.market_get_price_kline(&[__ws_arg_1]).await;
}
//
// {
// "success": true,
// "data": {
// "asset_ticks": {
// "btc/usdt": [ [ 1782984660, 60681, 60797.6, 60671.8, 60693.3, 275.741 ] ]
// }
// }
// }
//
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, to_lower(&assetPair), &[Value::from(vec![])]);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
/*
* @method
* @name mudrex#fetchMarkOHLCV
* @description fetches historical mark price candlestick data containing the open, high, low, and close price of a market
* @see https://docs.trade.mudrex.com/docs
* @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_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
}
/*
* @method
* @name mudrex#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.trade.mudrex.com/docs
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure](https://docs.ccxt.com/#/?id=ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("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(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
}
/*
* @method
* @name mudrex#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.trade.mudrex.com/docs
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures](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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_4 = self.extend(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 = (if (matches!(&data, Value::Arr(_))) { data.clone() } else { self.safe_list_k(data, "items", &[Value::from(vec![])]) });
let mut resultTickers: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_950: bool = true;
while { if !__for_first_950 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_950 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut t: Value = rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut sym: Value = self.safe_string_k(t.clone(), "symbol", &[]);
if (sym == Value::Null) {
continue;
}
let mut m: Value = self.safe_market(&[sym]);
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;
}
if let Value::Dict(__d) = &mut resultTickers { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), self.parse_ticker(t, &[m])); }
}
}
return self.filter_by_array_tickers(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: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
market = self.safe_market(&[ms, market.clone()]);
let mut symbol: Value = market.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
}), &[market]);
Value::Null
}
/*
* @method
* @name mudrex#fetchMarkets
* @description retrieves data on all markets for the exchange
* @see https://docs.trade.mudrex.com/docs
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut aggregated: Value = Value::from(vec![]);
let mut offset: Value = Value::Int(0);
let mut pageLimit: Value = Value::Int(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(), 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![])]);
// hoisted - inline length reads within conditionals become strlen for php, fatal on arrays
let mut itemsLength: Value = Value::Int(items.len() as i64);
if (itemsLength == Value::Null) || (itemsLength.as_f64() == Some(0.0)) {
items = self.safe_list_k(data.clone(), "results", &[Value::from(vec![])]);
itemsLength = Value::Int(items.len() as i64);
}
if (itemsLength.as_f64() == Some(0.0)) && (in_op(&data, &Value::Str("symbol".into()))) {
items = Value::from(vec![data.clone()]);
}
} else {
items = self.to_array(data);
}
let mut numItems: Value = Value::Int(items.len() as i64);
if (numItems == Value::Null) || (numItems.as_f64() == Some(0.0)) {
paging = false;
break;
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_951: bool = true;
while { if !__for_first_951 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_951 = false; i.as_f64().unwrap_or(f64::NAN) < numItems.as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut aggregated, 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.as_f64().unwrap_or(f64::NAN) < pageLimit.as_f64().unwrap_or(f64::NAN) {
paging = false;
} else {
// this.sum keeps the offset numeric across the php transpile, see https://github.com/ccxt/ccxt/pull/29684
offset = self.sum(&[offset.clone(), pageLimit.clone()]);
}
}
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_952: bool = true;
while { if !__for_first_952 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_952 = false; i.as_f64().unwrap_or(f64::NAN) < ((aggregated.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_market(aggregated.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)));
}
}
return result;
Value::Null
}
pub fn parse_market(&self, mut asset: Value) -> Value {
let mut ms: Value = self.safe_string_k(asset.clone(), "symbol", &[]);
let mut base: Value = ms.clone();
if (ms != Value::Null) && (ends_with(&ms, &Value::Str("USDT".into()))) {
base = ms.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 4).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
let mut quote: Value = Value::Str("USDT".into());
let mut settle: Value = Value::Str("USDT".into());
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);
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(), quote);
m.insert("settle".to_string(), 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
}
/*
* @method
* @name mudrex#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.trade.mudrex.com/docs
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'swap' (default) or 'spot' - which wallet balance to fetch
* @param {string} [params.trade_currency] the settlement currency to query the balance for
* @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params.clone(), Value::Str("swap".into())]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut requested: Value = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("trade_currency".into()), Value::Str("tradeCurrency".into()), Value::Str("currency".into())]), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("trade_currency".into()), Value::Str("tradeCurrency".into()), Value::Str("currency".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
if (requested != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), requested.clone()); }
}
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_wallet_funds(&[__ws_arg_5]).await;
} else {
if (requested != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("trade_currency".into(), requested.clone()); }
}
let __ws_arg_6 = self.extend(request, &[params]);
response = self.private_get_futures_funds(&[__ws_arg_6]).await;
}
let mut currency: Value = requested;
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()))));
}
add_element_to_object(&mut response, &Value::Str("currency".into()), currency);
return self.parse_balance(response);
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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
let mut account: Value = self.account();
let mut futuresBalance: Value = self.safe_string_k(data.clone(), "balance", &[]);
if (futuresBalance != Value::Null) {
// futures wallet: balance is the free/available margin, locked_amount is used, safeBalance derives total
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), futuresBalance); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(data.clone(), "locked_amount", &[])); }
} else {
// spot wallet: total is the total, withdrawable is free, safeBalance derives used
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(data.clone(), "total", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(data, "withdrawable", &[])); }
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(¤cy), account); }
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name mudrex#fetchLeverage
* @description fetch the set leverage for a market
* @see https://docs.trade.mudrex.com/docs
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage structure](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.clone());
let mut request: Value = Value::Map({
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_7 = self.extend(request, &[params]);
let mut response: Value = self.private_get_futures_asset_id_leverage(&[__ws_arg_7]).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
}
/*
* @method
* @name mudrex#setLeverage
* @description set the level of leverage for a market
* @see https://docs.trade.mudrex.com/docs
* @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.marginType] 'ISOLATED' (default) or 'CROSSED'
* @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".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marginType: Value = self.safe_string_k(params.clone(), "marginType", &[Value::Str("ISOLATED".into())]);
let mut request: Value = Value::Map({
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("margin_type".to_string(), marginType);
m.insert("leverage".to_string(), leverage);
m
});
params = self.omit(params.clone(), Value::from(vec![Value::Str("marginType".into())]), &[]);
let __ws_arg_8 = self.extend(request, &[params]);
let mut response: Value = self.private_post_futures_asset_id_leverage(&[__ws_arg_8]).await;
return response;
Value::Null
}
/*
* @method
* @name mudrex#createOrder
* @description create a trade order
* @see https://docs.trade.mudrex.com/docs
* @param {string} symbol unified market symbol
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency
* @param {float} [price] the price to fulfill the order, in units of the quote currency (also required for market orders on this exchange)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.leverage] leverage for the order, required if setLeverage() was not called beforehand
* @param {bool} [params.reduceOnly] true if the order is reduce only
* @param {object} [params.takeProfit] *takeProfit object in params* containing the trigger price of the take-profit order attached to this order
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the trigger price of the stop-loss order attached to this order
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {float} [params.takeProfitPrice] the trigger price for a standalone take-profit order on an existing position (requires params.positionId)
* @param {float} [params.stopLossPrice] the trigger price for a standalone stop-loss order on an existing position (requires params.positionId)
* @param {string} [params.positionId] the id of the position the standalone stopLossPrice/takeProfitPrice order is attached to
* @param {string} [params.trade_currency] the settlement currency for the order
* @returns {object} an [order structure](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());
// standalone stop-loss / take-profit orders (stopLossPrice/takeProfitPrice) are attached to
// an existing position through the riskorder endpoint, so a positionId is required
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
if (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null) {
let mut positionId: Value = self.safe_string2(params.clone(), Value::Str("positionId".into()), Value::Str("position_id".into()), &[]);
if (positionId == Value::Null) {
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()))));
}
params = 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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId);
m
});
if (takeProfitPrice != Value::Null) {
if let Value::Dict(__d) = &mut riskRequest { std::sync::Arc::make_mut(__d).insert("is_takeprofit".into(), Value::Bool(true)); }
if let Value::Dict(__d) = &mut riskRequest { std::sync::Arc::make_mut(__d).insert("takeprofit_price".into(), self.price_to_precision(symbol.clone(), takeProfitPrice)); }
}
if (stopLossPrice != Value::Null) {
if let Value::Dict(__d) = &mut riskRequest { std::sync::Arc::make_mut(__d).insert("is_stoploss".into(), Value::Bool(true)); }
if let Value::Dict(__d) = &mut riskRequest { std::sync::Arc::make_mut(__d).insert("stoploss_price".into(), self.price_to_precision(symbol.clone(), stopLossPrice)); }
}
let __ws_arg_9 = self.extend(riskRequest, &[params.clone()]);
let mut riskResponse: Value = self.private_post_futures_positions_position_id_riskorder(&[__ws_arg_9]).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: Value = Value::Map({
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
});
// mudrex only supports take-profit / stop-loss orders attached to the position-opening order
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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("is_takeprofit".into(), Value::Bool(true)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("is_stoploss".into(), Value::Bool(true)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).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())]), &[]))); }
}
params = self.omit(params.clone(), Value::from(vec![Value::Str("leverage".into()), Value::Str("reduceOnly".into()), Value::Str("takeProfit".into()), Value::Str("stopLoss".into())]), &[]);
let __ws_arg_10 = self.extend(request.clone(), &[params]);
let mut response: Value = self.private_post_futures_asset_id_order(&[__ws_arg_10]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[response.clone()]);
// the create response omits the order/trigger type, so parse a merged copy - the base derivations, like timeInForce, need to see them - then keep the untouched raw payload under info
let mut merged: Value = self.extend(data.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_type".to_string(), match &request { Value::Dict(__m15) => __m15.get("order_type").cloned().unwrap_or(Value::Null), _ => Value::Null });
m.insert("trigger_type".to_string(), match &request { Value::Dict(__m15) => __m15.get("trigger_type").cloned().unwrap_or(Value::Null), _ => Value::Null });
m
})]);
let mut order: Value = self.parse_order(merged, &[market]);
add_element_to_object(&mut order, &Value::Str("info".into()), data);
return order;
Value::Null
}
/*
* @method
* @name mudrex#editOrder
* @description edit a trade order
* @see https://docs.trade.mudrex.com/docs
* @param {string} id order id
* @param {string} symbol unified symbol of the market to edit an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} [amount] how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_price".into(), self.price_to_precision(symbol, price)); }
}
let __ws_arg_11 = self.extend(request, &[params]);
let mut response: Value = self.private_patch_futures_orders_order_id(&[__ws_arg_11]).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: Value = Value::Map({
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(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: Value = self.safe_string_k(order.clone(), "symbol", &[]);
market = self.safe_market(&[oms, market.clone()]);
let mut oid: Value = self.safe_string2(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());
}
// stop-loss / take-profit rows attached to a position carry the trigger value under the "price" key
let mut isRiskOrder: bool = (rawSide.as_deref() == Some("STOPLOSS")) || (rawSide.as_deref() == Some("TAKEPROFIT"));
let mut priceString: Value = self.safe_string2(order.clone(), Value::Str("price".into()), Value::Str("order_price".into()), &[]);
let mut orderPrice: Value = priceString.clone();
let mut triggerPrice: Value = Value::Null;
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if isRiskOrder {
triggerPrice = priceString.clone();
orderPrice = Value::Null;
if (rawSide.as_deref() == Some("STOPLOSS")) {
stopLossPrice = priceString.clone();
} else {
takeProfitPrice = priceString;
}
}
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(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut sym: Value = market.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);
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
}), &[market]);
Value::Null
}
/*
* @method
* @name mudrex#cancelOrder
* @description cancels an open order
* @see https://docs.trade.mudrex.com/docs
* @param {string} id order id
* @param {string} [symbol] unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure](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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_12 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_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
}
/*
* @method
* @name mudrex#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.trade.mudrex.com/docs
* @param {string} id the order id
* @param {string} [symbol] unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure](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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_13 = self.extend(request, &[params]);
let mut response: Value = self.private_get_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
}
/*
* @method
* @name mudrex#fetchOrdersByState
* @ignore
* @description fetches a list of orders filtered by their state
* @param {string} state the state of the orders to fetch
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
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: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut q { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut request: Value = self.extend(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: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_953: bool = true;
while { if !__for_first_953 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_953 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
append_to_array(&mut orders, self.parse_order(rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[market.clone()]));
}
}
return self.filter_by_symbol_since_limit(orders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name mudrex#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.trade.mudrex.com/docs
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures](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
}));
return self.fetch_orders_by_state(Value::Str("closed".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name mudrex#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.trade.mudrex.com/docs
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_state(Value::Str("open".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name mudrex#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.trade.mudrex.com/docs
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_state(Value::Str("closed".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name mudrex#fetchPositions
* @description fetch all open positions
* @see https://docs.trade.mudrex.com/docs
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.trade_currency] the settlement currency to query positions for
* @returns {object[]} a list of [position structures](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 q: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_14 = self.extend(q, &[params]);
let mut response: Value = self.private_get_futures_positions(&[__ws_arg_14]).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: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_954: bool = true;
while { if !__for_first_954 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_954 = false; i.as_f64().unwrap_or(f64::NAN) < ((rows.len() as i64) as f64) } {
let mut p: Value = rows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut symRaw: Value = self.safe_string_k(p.clone(), "symbol", &[]);
let mut m: Value = self.safe_market(&[symRaw]);
let mut pos: Value = self.parse_position(p, &[m]);
append_to_array(&mut outPos, pos);
}
}
return self.filter_by_array_positions(outPos, Value::Str("symbol".into()), &[symbols, Value::Bool(false)]);
Value::Null
}
/*
* @method
* @name mudrex#fetchPositionsHistory
* @description fetches the history of closed positions
* @see https://docs.trade.mudrex.com/docs/get-position-history
* @param {string[]} [symbols] a list of unified market symbols
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum number of position structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.trade_currency] the settlement currency to filter positions by
* @returns {object[]} a list of [position structures](https://docs.ccxt.com/#/?id=position-structure)
*/
pub async fn fetch_positions_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_15 = self.extend(request, &[params]);
let mut response: Value = self.private_get_futures_positions_history(&[__ws_arg_15]).await;
//
// {
// "success": true,
// "data": [
// {
// "id": "019f1ed6-...",
// "position_type": "SHORT",
// "status": "CLOSED",
// "leverage": "3",
// "entry_price": "1.3112",
// "closed_price": "1.3395",
// "quantity": "34",
// "pnl": "-0.9622",
// "created_at": "2026-07-01T10:18:57Z",
// "updated_at": "2026-07-01T18:00:21Z",
// "symbol": "CAKEUSDT",
// "trade_currency": "USDT"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[symbols]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
market = self.safe_market(&[Value::Null, market.clone()]);
let mut ms: Value = self.safe_string_k(position.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(ms, &[market.clone()]);
// open positions use "order_type", closed positions (history) use "position_type"
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: Value = self.safe_string_k(position.clone(), "quantity", &[]);
let mut entryPriceString: Value = self.safe_string_k(position.clone(), "entry_price", &[]);
let mut contractSizeString: Value = self.safe_string_k(market.clone(), "contractSize", &[Value::Str("1".into())]);
let mut notional: Value = Value::Null;
if (quantityString != Value::Null) && (entryPriceString != Value::Null) {
notional = self.parse_number(crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&quantityString, &entryPriceString), &contractSizeString), &[]);
}
let mut initialMargin: Value = self.safe_string_k(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(market, "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("collateral".to_string(), self.parse_number(initialMargin.clone(), &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMargin, &[]));
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
}
/*
* @method
* @name mudrex#closePosition
* @description closes an open position for a market
* @see https://docs.trade.mudrex.com/docs
* @param {string} symbol unified CCXT market symbol
* @param {string} [side] 'buy' or 'sell', not required by mudrex
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.position_id] the id of the position to close, resolved from the symbol if not provided
* @param {float} [params.amount] the amount to close for a partial close, closes the whole position if not provided
* @returns {object} an [order structure](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 positionId: Value = self.safe_string_k(params.clone(), "position_id", &[]);
let mut amount: Value = self.safe_value_k(params.clone(), "amount", &[]);
if (positionId == Value::Null) {
let mut market: Value = self.market(symbol.clone());
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol.clone()]), params.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_955: bool = true;
while { if !__for_first_955 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_955 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut p: Value = positions.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 (side != Value::Null) && (p.as_map().and_then(|__m| __m.get("side")).cloned().unwrap_or(Value::Null).as_str() != side.as_str()) {
continue;
}
if (p.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null).as_str() == market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null).as_str()) {
positionId = self.safe_string_k(p, "id", &[]);
break;
}
}
}
}
if (positionId == Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", self.id.clone(), Value::Str(" closePosition() could not resolve position_id".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId);
m
});
if (amount != Value::Null) {
let mut orderType: Value = self.safe_string_upper_k(params.clone(), "order_type", &[Value::Str("LIMIT".into())]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("order_type".into(), orderType.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quantity".into(), self.amount_to_precision(symbol, amount)); }
let mut lp: Value = self.safe_string_k(params.clone(), "limit_price", &[]);
if (orderType.as_str() == Some("LIMIT")) && (lp != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit_price".into(), lp); }
}
params = 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_16 = self.extend(request.clone(), &[params.clone()]);
let mut partialResponse: Value = self.private_post_futures_positions_position_id_close_partial(&[__ws_arg_16]).await;
return partialResponse;
}
params = self.omit(params.clone(), Value::from(vec![Value::Str("position_id".into())]), &[]);
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.private_post_futures_positions_position_id_close(&[__ws_arg_17]).await;
return response;
Value::Null
}
/*
* @method
* @name mudrex#addMargin
* @description add margin to a position
* @see https://docs.trade.mudrex.com/docs
* @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.position_id] the id of the position to add margin to, resolved from the symbol if not provided
* @returns {object} a [margin structure](https://docs.ccxt.com/#/?id=add-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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut positionId: Value = self.safe_string_k(params.clone(), "position_id", &[]);
if (positionId == Value::Null) {
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol.clone()]), params.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_956: bool = true;
while { if !__for_first_956 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_956 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut p: Value = positions.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 (p.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null).as_str() == symbol.as_str()) {
positionId = self.safe_string_k(p, "id", &[]);
break;
}
}
}
}
if (positionId == Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", self.id.clone(), Value::Str(" addMargin() could not resolve position_id".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("position_id".to_string(), positionId);
m.insert("margin".to_string(), self.cost_to_precision(symbol, amount));
m
});
params = self.omit(params.clone(), Value::from(vec![Value::Str("position_id".into())]), &[]);
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.private_post_futures_positions_position_id_add_margin(&[__ws_arg_18]).await;
return response;
Value::Null
}
/*
* @method
* @name mudrex#reduceMargin
* @description remove margin from a position
* @see https://docs.trade.mudrex.com/docs
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin structure](https://docs.ccxt.com/#/?id=reduce-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.add_margin(symbol, negate(&amount), &[params]).await;
Value::Null
}
/*
* @method
* @name mudrex#fetchMyTrades
* @description fetch all trades made by the user, derived from the TRANSACTION rows of the fee history endpoint - FUNDING rows are excluded and each fill's REBATE row is netted into the trade fee
* @see https://docs.trade.mudrex.com/docs/fees
* @param {string} [symbol] unified market symbol, applied client-side because the endpoint has no symbol filter
* @param {int} [since] the earliest time in ms to fetch trades for, applied client-side
* @param {int} [limit] the maximum number of trade structures to retrieve, further pages are requested until the limit is satisfied, the history ends or the page cap is reached
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.trade_currency] the settlement currency to filter trades by, 'USDT' (default) or 'INR'
* @param {int} [params.paginationCalls] the maximum number of pages to request (default 10) - a symbol with few or no recent fills can exhaust the cap and return fewer than limit trades
* @returns {Trade[]} a list of [trade structures](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);
}
let mut maxCalls: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".into()), Value::Str("paginationCalls".into()), &[Value::Int(10)]); maxCalls = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut pageSize: Value = Value::Int(0);
if (limit != Value::Null) {
// every fill produces a TRANSACTION row plus a REBATE row and funding rows share the page, so over-request and paginate until the unified limit is satisfied
pageSize = (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: Value = Value::from(vec![]);
let mut transactionsCount: Value = Value::Int(0);
let mut calls: Value = Value::Int(0);
let mut offset: Value = Value::Int(0);
let mut paging: bool = true;
while (paging) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if pageSize.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), pageSize.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("offset".into(), offset.clone()); }
}
let __ws_arg_19 = self.extend(request, &[params.clone()]);
let mut response: Value = self.private_get_futures_fee_history(&[__ws_arg_19]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut dataLength: Value = Value::Int(data.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_957: bool = true;
while { if !__for_first_957 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_957 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength.as_f64().unwrap_or(f64::NAN) } {
let mut entry: Value = data.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);
append_to_array(&mut allRows, entry.clone());
if (self.safe_string_k(entry.clone(), "fee_type", &[]).as_str() == Some("TRANSACTION")) {
// count only rows the client-side symbol filter keeps, otherwise a symbol-filtered call under-returns
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.sum(&[transactionsCount.clone(), Value::Int(1)]);
}
}
}
}
calls = self.sum(&[calls.clone(), Value::Int(1)]);
paging = false;
// the page cap bounds the walk when the requested symbol has few or no rows anywhere near the top of the history
if (limit != Value::Null) && (dataLength.as_f64() == pageSize.as_f64()) && (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)) {
// this.sum keeps the offset numeric across the php transpile, see https://github.com/ccxt/ccxt/pull/29684
offset = self.sum(&[offset.clone(), pageSize.clone()]);
paging = true;
}
}
// a REBATE row is a partial refund of one fill's TRANSACTION fee, matched by symbol, time and notional - each rebate is consumed once, so equal fills sharing a key net exactly one refund apiece
let mut rebateKeys: Value = Value::from(vec![]);
let mut rebateAmounts: Value = Value::from(vec![]);
let mut transactions: Value = Value::from(vec![]);
let mut transactionKeys: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_958: bool = true;
while { if !__for_first_958 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_958 = false; i.as_f64().unwrap_or(f64::NAN) < ((allRows.len() as i64) as f64) } {
let mut entry: Value = allRows.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut 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")) {
append_to_array(&mut transactions, entry.clone());
append_to_array(&mut transactionKeys, pairKey.clone());
} else if (feeType.as_deref() == Some("REBATE")) {
append_to_array(&mut rebateKeys, pairKey);
append_to_array(&mut rebateAmounts, self.safe_string_k(entry, "fee_amount", &[Value::Str("0".into())]));
}
}
}
let mut rows: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_960: bool = true;
while { if !__for_first_960 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_960 = 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_959: bool = true;
while { if !__for_first_959 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_959 = 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.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null).as_str()) {
rebate = rebateAmounts.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);
// blank the consumed key so the next equal fill matches the next rebate, never the same one twice
add_element_to_object(&mut rebateKeys, &j, Value::Null);
break;
}
}
}
if (rebate == Value::Null) {
append_to_array(&mut rows, transactions.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));
} else {
append_to_array(&mut rows, self.extend(transactions.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), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rebate_amount".to_string(), rebate);
m
})]));
}
}
}
return self.parse_trades(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);
//
// {
// "id": "019f21e1-9093-7333-866d-31f19c1300ed",
// "symbol": "APTUSDT",
// "fee_amount": "0.02468116",
// "fee_perc": "0.05900003",
// "fee_type": "TRANSACTION",
// "created_at": "2026-07-02T08:10:58Z",
// "transaction_amount": "41.83245",
// "trade_currency": "USDT",
// "order_type": "LONG",
// "trigger_type": "MARKET",
// "gst_amount": "0.00376492"
// }
//
let mut ms: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
market = self.safe_market(&[ms, market.clone()]);
let mut symbol: Value = market.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", &[]));
// exit fills carry STOPLOSS / TAKEPROFIT markers without the closing direction, so their unified direction stays undefined
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")) {
// a market execution always takes liquidity, a limit execution can be either
takerOrMaker = Value::Str("taker".into());
}
let mut fee: Value = Value::Null;
let mut feeCostString: Value = self.safe_string_k(trade.clone(), "fee_amount", &[]);
// rebate_amount is attached by fetchMyTrades from the fill's REBATE row - the reported fee is the net charge
let mut rebateString: Value = self.safe_string_k(trade.clone(), "rebate_amount", &[]);
if (feeCostString != Value::Null) && (rebateString != Value::Null) {
feeCostString = crate::precise::Precise::stringSub(&feeCostString, &rebateString);
}
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
}), &[market]);
Value::Null
}
/*
* @method
* @name mudrex#transfer
* @description transfer currency internally between wallets on the same account
* @see https://docs.trade.mudrex.com/docs
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount 'spot' or 'futures'
* @param {string} toAccount 'spot' or 'futures'
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure](https://docs.ccxt.com/#/?id=transfer-structure)
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
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(), &[to_upper(&fromAccount)]);
let mut tw: Value = self.safe_string(mp, toAccount.clone(), &[to_upper(&toAccount)]);
let mut body: Value = Value::Map({
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 {
// default USDT does not use the inr path
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_20 = self.extend(body.clone(), &[params.clone()]);
response = self.private_post_futures_transfers_inr(&[__ws_arg_20]).await;
} else {
let __ws_arg_21 = self.extend(body, &[params]);
response = self.private_post_wallet_futures_transfer(&[__ws_arg_21]).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
}
}