// 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;
pub struct PhemexCore {
pub exchange: crate::exchange::Exchange,
}
impl PhemexCore {
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 = PhemexCore::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 PhemexCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_ticker(self, ticker, &[market.clone()])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_trade(self, trade, &[market.clone()])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_order(self, order, &[market.clone()])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_ohlcv(self, ohlcv, &[market.clone()])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_position(self, position, &[market.clone()])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_funding_rate(self, rate, &[market.clone()])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_transfer(self, transfer, &[currency.clone()])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_open_interest(self, interest, &[market.clone()])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_margin_modification(self, data, &[market.clone()])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_transaction(self, transaction, &[currency.clone()])
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_adl_rank(self, info, &[market.clone()])
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_conversion(self, conversion, &[from_currency.clone(), to_currency.clone()])
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PhemexCore.
PhemexCore::parse_market_leverage_tiers(self, info, &[market.clone()])
}
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 PhemexCore.
PhemexCore::sign(self, path, &[api.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
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 PhemexCore.
PhemexCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for PhemexCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders" => self.cancel_all_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_convert_trade" => self.create_convert_trade(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..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"custom_parse_bid_ask" => self.custom_parse_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"custom_parse_order_book" => self.custom_parse_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]),
"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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_convert_quote" => self.fetch_convert_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_convert_trade_history" => self.fetch_convert_trade_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_currencies" => self.fetch_currencies(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits" => self.fetch_deposits(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_leverage_tiers" => self.fetch_leverage_tiers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position_history" => self.fetch_position_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions_adl_rank" => self.fetch_positions_adl_rank(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_transfers" => self.fetch_transfers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"from_en" => self.from_en(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"from_ep" => self.from_ep(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"from_er" => self.from_er(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"from_ev" => self.from_ev(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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_adl_rank" => self.parse_adl_rank(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_conversion" => self.parse_conversion(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_fee_to_precision" => self.parse_funding_fee_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_margin_status" => self.parse_margin_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market_leverage_tiers" => self.parse_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_side" => self.parse_order_side(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_type" => self.parse_order_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_safe_number" => self.parse_safe_number(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"parse_spot_balance" => self.parse_spot_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_spot_market" => self.parse_spot_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_spot_order" => self.parse_spot_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_swap_balance" => self.parse_swap_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_swap_market" => self.parse_swap_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_swap_order" => self.parse_swap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transfer_status" => self.parse_transfer_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_margin" => self.set_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_position_mode" => self.set_position_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"to_en" => self.to_en(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"to_ep" => self.to_ep(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"to_ev" => self.to_ev(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args.get(3..).unwrap_or(&[]).to_vec()[..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for PhemexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for PhemexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl PhemexCore {
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("phemex".to_string()));
m.insert("name".to_string(), Value::Str("Phemex".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("CN".to_string())]));
m.insert("rateLimit".to_string(), Value::Float(120.5));
m.insert("version".to_string(), Value::Str("v1".to_string()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("hostname".to_string(), Value::Str("api.phemex.com".to_string()));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createConvertTrade".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLimitOrder".to_string(), Value::Bool(true));
m.insert("createStopMarketOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchConvertQuote".to_string(), Value::Bool(true));
m.insert("fetchConvertTrade".to_string(), Value::Bool(false));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistories".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositionADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionHistory".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(true));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/1294454/85225056-221eb600-b3d7-11ea-930d-564d2690e3f6.jpg".to_string()));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Str("https://testnet-api.phemex.com/v1".to_string()));
m.insert("v2".to_string(), Value::Str("https://testnet-api.phemex.com".to_string()));
m.insert("public".to_string(), Value::Str("https://testnet-api.phemex.com/exchange/public".to_string()));
m.insert("private".to_string(), Value::Str("https://testnet-api.phemex.com".to_string()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1".to_string(), Value::Str("https://{hostname}/v1".to_string()));
m.insert("v2".to_string(), Value::Str("https://{hostname}".to_string()));
m.insert("public".to_string(), Value::Str("https://{hostname}/exchange/public".to_string()));
m.insert("private".to_string(), Value::Str("https://{hostname}".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://phemex.com".to_string()));
m.insert("doc".to_string(), Value::Str("https://phemex-docs.github.io/#overview".to_string()));
m.insert("fees".to_string(), Value::Str("https://phemex.com/fees-conditions".to_string()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://phemex.com/register?referralCode=EDNVJ".to_string()));
m.insert("discount".to_string(), Value::Float(0.1));
m
}));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("60".to_string()));
m.insert("3m".to_string(), Value::Str("180".to_string()));
m.insert("5m".to_string(), Value::Str("300".to_string()));
m.insert("15m".to_string(), Value::Str("900".to_string()));
m.insert("30m".to_string(), Value::Str("1800".to_string()));
m.insert("1h".to_string(), Value::Str("3600".to_string()));
m.insert("2h".to_string(), Value::Str("7200".to_string()));
m.insert("3h".to_string(), Value::Str("10800".to_string()));
m.insert("4h".to_string(), Value::Str("14400".to_string()));
m.insert("6h".to_string(), Value::Str("21600".to_string()));
m.insert("12h".to_string(), Value::Str("43200".to_string()));
m.insert("1d".to_string(), Value::Str("86400".to_string()));
m.insert("1w".to_string(), Value::Str("604800".to_string()));
m.insert("1M".to_string(), Value::Str("2592000".to_string()));
m.insert("3M".to_string(), Value::Str("7776000".to_string()));
m.insert("1Y".to_string(), Value::Str("31104000".to_string()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cfg/v2/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("cfg/fundingRates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("nomics/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/kline/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/kline".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/kline/last".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/spot/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/public/cfg/chain-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m.insert("v1".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("md/fullbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/ticker/24hr/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/spot/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/spot/ticker/24hr/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/public/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/public/data/funding-rate-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m.insert("v2".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("public/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("public/products-plus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/ticker/24hr".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("md/v2/ticker/24hr/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/public/data/funding-rate-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot/orders/active".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/wallets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/spot/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/spot/order/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/order/v2/orderList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/order/v2/tradingList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("accounts/accountPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-accounts/accountPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-accounts/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(25));
m
}));
m.insert("g-accounts/risk-unit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api-data/futures/funding-fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/funding-fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/futures/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/futures/orders/by-order-id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/orders/by-order-id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/futures/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/futures/trading-fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/trading-fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/futures/v2/tradeAccountDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/g-futures/closedPosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("g-orders/activeList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/activeList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/order/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/order/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-user/users/children".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-user/wallets/v2/depositAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-user/wallets/tradeAccountDetail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-deposit/wallets/api/depositAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-deposit/wallets/api/depositHist".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-deposit/wallets/api/chainCfg".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-withdraw/wallets/api/withdrawHist".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-withdraw/wallets/api/asset/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-user/order/closedPositionList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/margins/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/confirm/withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/withdrawList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/depositList".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/v2/depositAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/funds".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/orders/by-order-id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/pnls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("api-data/spots/trades/by-order-id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/convert".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/spots/sub-accounts/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/futures/sub-accounts/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/assign".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/transferOut".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/transferIn".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/margins".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/createWithdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/cancelWithdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("exchange/wallets/createWithdrawAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/spots/sub-accounts/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/futures/sub-accounts/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/universal-transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("assets/convert".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-withdraw/wallets/api/createWithdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("phemex-withdraw/wallets/api/cancelWithdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot/orders/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/replace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-orders/replace".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-orders/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("g-positions/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("g-positions/switch-pos-mode-sync".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("positions/riskLimit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("spot/orders/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("orders/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("g-orders/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("g-orders/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m
}));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
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.001".to_string()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.001".to_string()), &[]));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mark".to_string(), Value::Bool(true));
m.insert("last".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Null);
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(200));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(2));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(200));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("daysBackCanceled".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(2));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".to_string()));
m
}));
m.insert("forDerivatives".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".to_string()));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerDirection".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mark".to_string(), Value::Bool(true));
m.insert("last".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("hedged".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(2000));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forDerivatives".to_string()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forDerivatives".to_string()));
m
}));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("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("401".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("412".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("6001".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("19999".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("10001".to_string(), Value::Str("DuplicateOrderId".to_string()).clone());
m.insert("10002".to_string(), Value::Str("OrderNotFound".to_string()).clone());
m.insert("10003".to_string(), Value::Str("CancelPending".to_string()).clone());
m.insert("10004".to_string(), Value::Str("CancelPending".to_string()).clone());
m.insert("10005".to_string(), Value::Str("CancelPending".to_string()).clone());
m.insert("11001".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11002".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11003".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11004".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11005".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11006".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11007".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11008".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11009".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11010".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11011".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11012".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11013".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11014".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11015".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11016".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11017".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11018".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11019".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11020".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11021".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11022".to_string(), Value::Str("AccountSuspended".to_string()).clone());
m.insert("11023".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11024".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11025".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11026".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11027".to_string(), Value::Str("BadSymbol".to_string()).clone());
m.insert("11028".to_string(), Value::Str("BadSymbol".to_string()).clone());
m.insert("11029".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11030".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11031".to_string(), Value::Str("DDoSProtection".to_string()).clone());
m.insert("11032".to_string(), Value::Str("DDoSProtection".to_string()).clone());
m.insert("11033".to_string(), Value::Str("DuplicateOrderId".to_string()).clone());
m.insert("11034".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11035".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11036".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11037".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11038".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11039".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11040".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11041".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11042".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11043".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11044".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11045".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11046".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11047".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11048".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11049".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11050".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11051".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11052".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11053".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11054".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11055".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11056".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11057".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11058".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11059".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11060".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11061".to_string(), Value::Str("CancelPending".to_string()).clone());
m.insert("11062".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11063".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11064".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11065".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11066".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11067".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11068".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11069".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11070".to_string(), Value::Str("BadSymbol".to_string()).clone());
m.insert("11071".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11072".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11073".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11074".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11075".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11076".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11077".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11078".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11079".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11080".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11081".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11082".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11083".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11084".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11085".to_string(), Value::Str("DuplicateOrderId".to_string()).clone());
m.insert("11086".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11087".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11088".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11089".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11090".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11091".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11092".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11093".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11094".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11095".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11096".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11097".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11098".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11099".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11100".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11101".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11102".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11103".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11104".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11105".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11106".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("11107".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("11108".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11109".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11110".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11111".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11112".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11113".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("11114".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11115".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11116".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11117".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11118".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11119".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11120".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11121".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11122".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11123".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11124".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11125".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11126".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11128".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11129".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11130".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11131".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11132".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11133".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("11134".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("30000".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("30018".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("34003".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("35104".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("39995".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("39996".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("39997".to_string(), Value::Str("BadSymbol".to_string()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("401 Insufficient privilege".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("401 Request IP mismatch".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("Failed to find api-key".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("Missing required parameter".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("API Signature verification failed".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("Api key not found".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("brokerId".to_string(), Value::Str("CCXT123456".to_string()));
m.insert("x-phemex-request-expiry".to_string(), Value::Int(60));
m.insert("createOrderByQuoteRequiresPrice".to_string(), Value::Bool(true));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TRC20".to_string(), Value::Str("TRX".to_string()));
m.insert("ERC20".to_string(), Value::Str("ETH".to_string()));
m.insert("BEP20".to_string(), Value::Str("BNB".to_string()));
m
}));
m.insert("defaultNetworks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("USDT".to_string(), Value::Str("ETH".to_string()));
m.insert("MKR".to_string(), Value::Str("ETH".to_string()));
m
}));
m.insert("defaultSubType".to_string(), Value::Str("linear".to_string()));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("spot".to_string()));
m.insert("swap".to_string(), Value::Str("future".to_string()));
m
}));
m.insert("stableCoins".to_string(), Value::List(vec![Value::Str("BUSD".to_string()), Value::Str("FEI".to_string()), Value::Str("TUSD".to_string()), Value::Str("USD".to_string()), Value::Str("USDC".to_string()), Value::Str("USDD".to_string()), Value::Str("USDP".to_string()), Value::Str("USDT".to_string())]));
m.insert("transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fillResponseFromRequest".to_string(), Value::Bool(true));
m
}));
m.insert("triggerPriceTypesMap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Str("ByLastPrice".to_string()));
m.insert("mark".to_string(), Value::Str("ByMarkPrice".to_string()));
m.insert("index".to_string(), Value::Str("ByIndexPrice".to_string()));
m.insert("ask".to_string(), Value::Str("ByAskPrice".to_string()));
m.insert("bid".to_string(), Value::Str("ByBidPrice".to_string()));
m
}));
m
}));
m
})]);
Value::Null
}
pub fn parse_safe_number(&self, optional_args: &[Value]) -> Value {
let mut value = get_arg(optional_args, 0, Value::Null);
if is_equal(&value, &Value::Null) {
return value;
}
let mut parts: Value = split(&value, &Value::Str(",".to_string()));
value = join(&parts, &Value::Str("".to_string()));
parts = split(&value, &Value::Str(" ".to_string()));
return self.safe_number(parts.clone(), Value::Int(0), &[]);
Value::Null
}
pub fn parse_swap_market(&self, mut market: Value) -> Value {
//
// {
// "symbol":"BTCUSD", //
// "code":"1",
// "type":"Perpetual",
// "displaySymbol":"BTC / USD",
// "indexSymbol":".BTC",
// "markSymbol":".MBTC",
// "fundingRateSymbol":".BTCFR",
// "fundingRate8hSymbol":".BTCFR8H",
// "contractUnderlyingAssets":"USD", // or eg. `1000 SHIB`
// "settleCurrency":"BTC",
// "quoteCurrency":"USD",
// "contractSize":"1 USD",
// "lotSize":1,
// "tickSize":0.5,
// "priceScale":4,
// "ratioScale":8,
// "pricePrecision":1,
// "minPriceEp":5000,
// "maxPriceEp":10000000000,
// "maxOrderQty":1000000,
// "status":"Listed",
// "tipOrderQty":1000000,
// "listTime":"1574650800000",
// "majorSymbol":true,
// "steps":"50",
// "riskLimits":[
// {"limit":100,"initialMargin":"1.0%","initialMarginEr":1000000,"maintenanceMargin":"0.5%","maintenanceMarginEr":500000},
// {"limit":150,"initialMargin":"1.5%","initialMarginEr":1500000,"maintenanceMargin":"1.0%","maintenanceMarginEr":1000000},
// {"limit":200,"initialMargin":"2.0%","initialMarginEr":2000000,"maintenanceMargin":"1.5%","maintenanceMarginEr":1500000},
// ],
// "underlyingSymbol":".BTC",
// "baseCurrency":"BTC",
// "settlementCurrency":"BTC",
// "valueScale":8,
// "defaultLeverage":0,
// "maxLeverage":100,
// "initMarginEr":"1000000",
// "maintMarginEr":"500000",
// "defaultRiskLimitEv":10000000000,
// "deleverage":true,
// "makerFeeRateEr":-250000,
// "takerFeeRateEr":750000,
// "fundingInterval":8,
// "marketUrl":"https://phemex.com/trade/BTCUSD",
// "description":"BTCUSD is a BTC/USD perpetual contract priced on the .BTC Index. Each contract is worth 1 USD of Bitcoin. Funding is paid and received every 8 hours. At UTC time: 00:00, 08:00, 16:00.",
// }
//
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut contractUnderlyingAssets: Value = self.safe_string_k(market.clone(), "contractUnderlyingAssets", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "baseCurrency", &[contractUnderlyingAssets.clone()]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteCurrency", &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "settleCurrency", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
base = replace_str(&base, &Value::Str(" ".to_string()), &Value::Str("".to_string())); // replace space for junction codes, eg. `1000 SHIB`
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut inverse: Value = Value::Bool(false);
if !is_equal(&settleId, "eId) {
inverse = Value::Bool(true);
// some unhandled cases
if !is_true(&(Value::Bool(in_op(&market, &Value::Str("baseCurrency".to_string()))))) && is_equal(&base, "e) {
base = settle.clone();
}
}
let mut priceScale: Value = self.safe_integer_k(market.clone(), "priceScale", &[]);
let mut ratioScale: Value = self.safe_integer_k(market.clone(), "ratioScale", &[]);
let mut valueScale: Value = self.safe_integer_k(market.clone(), "valueScale", &[]);
let mut minPriceEp: Value = self.safe_string_k(market.clone(), "minPriceEp", &[]);
let mut maxPriceEp: Value = self.safe_string_k(market.clone(), "maxPriceEp", &[]);
let mut makerFeeRateEr: Value = self.safe_string_k(market.clone(), "makerFeeRateEr", &[]);
let mut takerFeeRateEr: Value = self.safe_string_k(market.clone(), "takerFeeRateEr", &[]);
let mut status: Value = self.safe_string_k(market.clone(), "status", &[]);
let mut contractSizeString: Value = self.safe_string_k(market.clone(), "contractSize", &[Value::Str(" ".to_string())]);
let mut contractSize: Value = Value::Null;
if is_equal(&settle, &Value::Str("USDT".to_string())) {
contractSize = self.parse_number(Value::Str("1".to_string()), &[]);
} else if !is_equal(&get_index_of(&contractSizeString, &Value::Str(" ".to_string())), &negate(&Value::Int(1))) {
// "1 USD"
// "0.005 ETH"
let mut parts: Value = split(&contractSizeString, &Value::Str(" ".to_string()));
contractSize = self.parse_number(get_value(&parts, &Value::Int(0)), &[]);
} else {
// "1.0"
contractSize = self.parse_number(contractSizeString.clone(), &[]);
}
let mut isLinear: Value = Value::Bool(!is_true(&inverse));
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), add(&add(&add(&add(&base, &Value::Str("/".to_string())), "e), &Value::Str(":".to_string())), &settle));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), settle.clone());
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), settleId.clone());
m.insert("type".to_string(), Value::Str("swap".to_string()));
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(is_equal(&status, &Value::Str("Listed".to_string()))));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), isLinear.clone());
m.insert("inverse".to_string(), inverse.clone());
m.insert("taker".to_string(), self.parse_number(self.from_en(takerFeeRateEr.clone(), ratioScale.clone()), &[]));
m.insert("maker".to_string(), self.parse_number(self.from_en(makerFeeRateEr.clone(), ratioScale.clone()), &[]));
m.insert("contractSize".to_string(), contractSize.clone());
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("priceScale".to_string(), priceScale.clone());
m.insert("valueScale".to_string(), valueScale.clone());
m.insert("ratioScale".to_string(), ratioScale.clone());
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_number2(market.clone(), Value::Str("lotSize".to_string()), Value::Str("qtyStepSize".to_string()), &[]));
m.insert("price".to_string(), self.safe_number_k(market.clone(), "tickSize", &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("1".to_string()), &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "maxLeverage", &[]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(self.from_en(minPriceEp.clone(), priceScale.clone()), &[]));
m.insert("max".to_string(), self.parse_number(self.from_en(maxPriceEp.clone(), priceScale.clone()), &[]));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), self.parse_number(self.safe_string_k(market.clone(), "maxOrderQty", &[]), &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market.clone());
m
})]);
Value::Null
}
pub fn parse_spot_market(&self, mut market: Value) -> Value {
//
// {
// "symbol":"sBTCUSDT",
// "code":1001,
// "type":"Spot",
// "displaySymbol":"BTC / USDT",
// "quoteCurrency":"USDT",
// "priceScale":8,
// "ratioScale":8,
// "pricePrecision":2,
// "baseCurrency":"BTC",
// "baseTickSize":"0.000001 BTC",
// "baseTickSizeEv":100,
// "quoteTickSize":"0.01 USDT",
// "quoteTickSizeEv":1000000,
// "baseQtyPrecision":6,
// "quoteQtyPrecision":2,
// "minOrderValue":"10 USDT",
// "minOrderValueEv":1000000000,
// "maxBaseOrderSize":"1000 BTC",
// "maxBaseOrderSizeEv":100000000000,
// "maxOrderValue":"5,000,000 USDT",
// "maxOrderValueEv":500000000000000,
// "defaultTakerFee":"0.001",
// "defaultTakerFeeEr":100000,
// "defaultMakerFee":"0.001",
// "defaultMakerFeeEr":100000,
// "description":"BTCUSDT is a BTC/USDT spot trading pair. Minimum order value is 1 USDT",
// "status":"Listed",
// "tipOrderQty":2,
// "listTime":1589338800000,
// "buyPriceUpperLimitPct":110,
// "sellPriceLowerLimitPct":90,
// "leverage":5
// },
//
let mut type_var: Value = self.safe_string_lower(market.clone(), Value::Str("type".to_string()), &[]);
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteCurrency", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "baseCurrency", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut status: Value = self.safe_string_k(market.clone(), "status", &[]);
let mut precisionAmount: Value = self.parse_safe_number(&[self.safe_string_k(market.clone(), "baseTickSize", &[])]);
let mut precisionPrice: Value = self.parse_safe_number(&[self.safe_string_k(market.clone(), "quoteTickSize", &[])]);
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), add(&add(&base, &Value::Str("/".to_string())), "e));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(is_equal(&status, &Value::Str("Listed".to_string()))));
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "defaultTakerFee", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "defaultMakerFee", &[]));
m.insert("contractSize".to_string(), Value::Null);
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("priceScale".to_string(), self.safe_integer_k(market.clone(), "priceScale", &[]));
m.insert("valueScale".to_string(), self.safe_integer_k(market.clone(), "valueScale", &[]));
m.insert("ratioScale".to_string(), self.safe_integer_k(market.clone(), "ratioScale", &[]));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), precisionAmount.clone());
m.insert("price".to_string(), precisionPrice.clone());
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), precisionAmount.clone());
m.insert("max".to_string(), self.parse_safe_number(&[self.safe_string_k(market.clone(), "maxBaseOrderSize", &[])]));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), precisionPrice.clone());
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_safe_number(&[self.safe_string_k(market.clone(), "minOrderValue", &[])]));
m.insert("max".to_string(), self.parse_safe_number(&[self.safe_string_k(market.clone(), "maxOrderValue", &[])]));
m
}));
m
}));
m.insert("created".to_string(), self.safe_integer_k(market.clone(), "listTime", &[]));
m.insert("info".to_string(), market.clone());
m
})]);
Value::Null
}
/*
* @method
* @name phemex#fetchMarkets
* @description retrieves data on all markets for phemex
* @see https://phemex-docs.github.io/#query-product-information-3
* @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 v2ProductsPromise: Value = self.v2_get_public_products(&[params.clone()]).await;
//
// {
// "code":0,
// "msg":"",
// "data":{
// "currencies":[
// {"currency":"BTC","name":"Bitcoin","code":1,"valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"BTC","inAssetsDisplay":1,"perpetual":0,"stableCoin":0,"assetsPrecision":8},
// {"currency":"USD","name":"USD","code":2,"valueScale":4,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"USD","inAssetsDisplay":1,"perpetual":0,"stableCoin":0,"assetsPrecision":2},
// {"currency":"USDT","name":"TetherUS","code":3,"valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"USDT","inAssetsDisplay":1,"perpetual":2,"stableCoin":1,"assetsPrecision":8},
// ],
// "products":[
// {
// "symbol":"BTCUSD",
// "code":1,
// "type":"Perpetual"
// "displaySymbol":"BTC / USD",
// "indexSymbol":".BTC",
// "markSymbol":".MBTC",
// "fundingRateSymbol":".BTCFR",
// "fundingRate8hSymbol":".BTCFR8H",
// "contractUnderlyingAssets":"USD",
// "settleCurrency":"BTC",
// "quoteCurrency":"USD",
// "contractSize":1.0,
// "lotSize":1,
// "tickSize":0.5,
// "priceScale":4,
// "ratioScale":8,
// "pricePrecision":1,
// "minPriceEp":5000,
// "maxPriceEp":10000000000,
// "maxOrderQty":1000000,
// "description":"BTC/USD perpetual contracts are priced on the .BTC Index. Each contract is worth 1 USD. Funding fees are paid and received every 8 hours at UTC time: 00:00, 08:00 and 16:00.",
// "status":"Listed",
// "tipOrderQty":1000000,
// "listTime":1574650800000,
// "majorSymbol":true,
// "defaultLeverage":"-10",
// "fundingInterval":28800,
// "maxLeverage":100
// },
// {
// "symbol":"sBTCUSDT",
// "code":1001,
// "type":"Spot",
// "displaySymbol":"BTC / USDT",
// "quoteCurrency":"USDT",
// "priceScale":8,
// "ratioScale":8,
// "pricePrecision":2,
// "baseCurrency":"BTC",
// "baseTickSize":"0.000001 BTC",
// "baseTickSizeEv":100,
// "quoteTickSize":"0.01 USDT",
// "quoteTickSizeEv":1000000,
// "baseQtyPrecision":6,
// "quoteQtyPrecision":2,
// "minOrderValue":"10 USDT",
// "minOrderValueEv":1000000000,
// "maxBaseOrderSize":"1000 BTC",
// "maxBaseOrderSizeEv":100000000000,
// "maxOrderValue":"5,000,000 USDT",
// "maxOrderValueEv":500000000000000,
// "defaultTakerFee":"0.001",
// "defaultTakerFeeEr":100000,
// "defaultMakerFee":"0.001",
// "defaultMakerFeeEr":100000,
// "description":"BTCUSDT is a BTC/USDT spot trading pair. Minimum order value is 1 USDT",
// "status":"Listed",
// "tipOrderQty":2,
// "listTime":1589338800000,
// "buyPriceUpperLimitPct":110,
// "sellPriceLowerLimitPct":90,
// "leverage":5
// },
// ],
// "perpProductsV2":[
// {
// "symbol":"BTCUSDT",
// "code":41541,
// "type":"PerpetualV2",
// "displaySymbol":"BTC / USDT",
// "indexSymbol":".BTCUSDT",
// "markSymbol":".MBTCUSDT",
// "fundingRateSymbol":".BTCUSDTFR",
// "fundingRate8hSymbol":".BTCUSDTFR8H",
// "contractUnderlyingAssets":"BTC",
// "settleCurrency":"USDT",
// "quoteCurrency":"USDT",
// "tickSize":"0.1",
// "priceScale":0,
// "ratioScale":0,
// "pricePrecision":1,
// "baseCurrency":"BTC",
// "description":"BTC/USDT perpetual contracts are priced on the .BTCUSDT Index. Each contract is worth 1 BTC. Funding fees are paid and received every 8 hours at UTC time: 00:00, 08:00 and 16:00.",
// "status":"Listed",
// "tipOrderQty":0,
// "listTime":1668225600000,
// "majorSymbol":true,
// "defaultLeverage":"-10",
// "fundingInterval":28800,
// "maxLeverage":100,
// "maxOrderQtyRq":"1000",
// "maxPriceRp":"2000000000",
// "minOrderValueRv":"1",
// "minPriceRp":"1000.0",
// "qtyPrecision":3,
// "qtyStepSize":"0.001",
// "tipOrderQtyRq":"200",
// "maxOpenPosLeverage":100.0
// },
// ],
// "riskLimits":[
// {
// "symbol":"BTCUSD",
// "steps":"50",
// "riskLimits":[
// {"limit":100,"initialMargin":"1.0%","initialMarginEr":1000000,"maintenanceMargin":"0.5%","maintenanceMarginEr":500000},
// {"limit":150,"initialMargin":"1.5%","initialMarginEr":1500000,"maintenanceMargin":"1.0%","maintenanceMarginEr":1000000},
// {"limit":200,"initialMargin":"2.0%","initialMarginEr":2000000,"maintenanceMargin":"1.5%","maintenanceMarginEr":1500000},
// ]
// },
// ],
// "leverages":[
// {"initialMargin":"1.0%","initialMarginEr":1000000,"options":[1,2,3,5,10,25,50,100]},
// {"initialMargin":"1.5%","initialMarginEr":1500000,"options":[1,2,3,5,10,25,50,66]},
// {"initialMargin":"2.0%","initialMarginEr":2000000,"options":[1,2,3,5,10,25,33,50]},
// ],
// "riskLimitsV2":[
// {
// "symbol":"BTCUSDT",
// "steps":"2000K",
// "riskLimits":[
// {"limit":2000000,"initialMarginRr":"0.01","maintenanceMarginRr":"0.005"},
// {"limit":4000000,"initialMarginRr":"0.015","maintenanceMarginRr":"0.0075"},
// {"limit":6000000,"initialMarginRr":"0.02","maintenanceMarginRr":"0.01"},
// ]
// },
// ],
// "leveragesV2":[
// {"options":[1.0,2.0,3.0,5.0,10.0,25.0,50.0,100.0],"initialMarginRr":"0.01"},
// {"options":[1.0,2.0,3.0,5.0,10.0,25.0,50.0,66.67],"initialMarginRr":"0.015"},
// {"options":[1.0,2.0,3.0,5.0,10.0,25.0,33.0,50.0],"initialMarginRr":"0.02"},
// ],
// "ratioScale":8,
// "md5Checksum":"5c6604814d3c1bafbe602c3d11a7e8bf",
// }
// }
//
let mut v1ProductsPromise: Value = self.v1_get_exchange_public_products(&[params.clone()]).await;
let mut v2Productsv1ProductsVariable = promise_all(&Value::List(vec![v2ProductsPromise.clone(), v1ProductsPromise.clone()])).await;
let mut v2Products: Value = get_value(&v2Productsv1ProductsVariable, &Value::Int(0));
let mut v1Products: Value = get_value(&v2Productsv1ProductsVariable, &Value::Int(1));
let mut v1ProductsData: Value = self.safe_value_k(v1Products.clone(), "data", &[Value::List(vec![])]);
//
// {
// "code":0,
// "msg":"OK",
// "data":[
// {
// "symbol":"BTCUSD",
// "underlyingSymbol":".BTC",
// "quoteCurrency":"USD",
// "baseCurrency":"BTC",
// "settlementCurrency":"BTC",
// "maxOrderQty":1000000,
// "maxPriceEp":100000000000000,
// "lotSize":1,
// "tickSize":"0.5",
// "contractSize":"1 USD",
// "priceScale":4,
// "ratioScale":8,
// "valueScale":8,
// "defaultLeverage":0,
// "maxLeverage":100,
// "initMarginEr":"1000000",
// "maintMarginEr":"500000",
// "defaultRiskLimitEv":10000000000,
// "deleverage":true,
// "makerFeeRateEr":-250000,
// "takerFeeRateEr":750000,
// "fundingInterval":8,
// "marketUrl":"https://phemex.com/trade/BTCUSD",
// "description":"BTCUSD is a BTC/USD perpetual contract priced on the .BTC Index. Each contract is worth 1 USD of Bitcoin. Funding is paid and received every 8 hours. At UTC time: 00:00, 08:00, 16:00.",
// "type":"Perpetual"
// },
// ]
// }
//
let mut v2ProductsData: Value = self.safe_dict_k(v2Products.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut products: Value = self.safe_list_k(v2ProductsData.clone(), "products", &[Value::List(vec![])]);
let mut perpetualProductsV2: Value = self.safe_list_k(v2ProductsData.clone(), "perpProductsV2", &[Value::List(vec![])]);
products = self.array_concat(products.clone(), perpetualProductsV2.clone());
let mut riskLimits: Value = self.safe_list_k(v2ProductsData.clone(), "riskLimits", &[Value::List(vec![])]);
let mut riskLimitsV2: Value = self.safe_list_k(v2ProductsData.clone(), "riskLimitsV2", &[Value::List(vec![])]);
riskLimits = self.array_concat(riskLimits.clone(), riskLimitsV2.clone());
let mut currencies: Value = self.safe_list_k(v2ProductsData.clone(), "currencies", &[Value::List(vec![])]);
let mut riskLimitsById: Value = self.index_by(riskLimits.clone(), Value::Str("symbol".to_string()));
let mut v1ProductsById: Value = self.index_by(v1ProductsData.clone(), Value::Str("symbol".to_string()));
let mut currenciesByCode: Value = self.index_by(currencies.clone(), Value::Str("currency".to_string()));
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1045: bool = true;
while { if !__for_first_1045 { i = add(&i, &Value::Int(1)); } __for_first_1045 = false; is_less_than(&i, &get_array_length(&products)) } {
let mut market: Value = get_value(&products, &i);
let mut market: Value = get_value(&products, &i);
let mut type_var: Value = self.safe_string_lower(market.clone(), Value::Str("type".to_string()), &[]);
if is_true(&(is_equal(&type_var, &Value::Str("perpetual".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("perpetualv2".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("perpetualpilot".to_string())))) {
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut riskLimitValues: Value = self.safe_dict(riskLimitsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
market = self.extend(market.clone(), &[riskLimitValues.clone()]);
let mut v1ProductsValues: Value = self.safe_dict(v1ProductsById.clone(), id.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
market = self.extend(market.clone(), &[v1ProductsValues.clone()]);
market = self.parse_swap_market(market.clone());
} else {
let mut baseCurrency: Value = self.safe_string_k(market.clone(), "baseCurrency", &[]);
let mut currencyValues: Value = self.safe_dict(currenciesByCode.clone(), baseCurrency.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut valueScale: Value = self.safe_string_k(currencyValues.clone(), "valueScale", &[Value::Str("8".to_string())]);
market = self.extend(market.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("valueScale".to_string(), valueScale.clone());
m
})]);
market = self.parse_spot_market(market.clone());
}
append_to_array(&mut result, market.clone());
}
}
return result;
Value::Null
}
/*
* @method
* @name phemex#fetchCurrencies
* @description fetches all available currencies on an exchange
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.v2_get_public_products(&[params.clone()]).await;
//
// {
// "code":0,
// "msg":"OK",
// "data":{
// ...,
// "currencies":[
// {"currency":"BTC","name":"Bitcoin","code":1,"valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"BTC","inAssetsDisplay":1,"perpetual":0,"stableCoin":0,"assetsPrecision":8},
// {"currency":"USD","name":"USD","code":2,"valueScale":4,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"USD","inAssetsDisplay":1,"perpetual":0,"stableCoin":0,"assetsPrecision":2},
// {"currency":"USDT","name":"TetherUS","code":3,"valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"needAddrTag":0,"status":"Listed","displayCurrency":"USDT","inAssetsDisplay":1,"perpetual":2,"stableCoin":1,"assetsPrecision":8},
// ],
// ...
// }
// }
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currencies: Value = self.safe_value_k(data.clone(), "currencies", &[Value::List(vec![])]);
return self.parse_currencies(currencies.clone());
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut valueScaleString: Value = self.safe_string_k(rawCurrency.clone(), "valueScale", &[]);
let mut valueScale: Value = crate::runtime::parse_int(&valueScaleString);
let mut minValueEv: Value = self.safe_string_k(rawCurrency.clone(), "minValueEv", &[]);
let mut maxValueEv: Value = self.safe_string_k(rawCurrency.clone(), "maxValueEv", &[]);
let mut minAmount: Value = Value::Null;
let mut maxAmount: Value = Value::Null;
let mut precision: Value = Value::Null;
if !is_equal(&valueScale, &Value::Null) {
let mut precisionString: Value = self.parse_precision(&[valueScaleString.clone()]);
precision = self.parse_number(precisionString.clone(), &[]);
minAmount = self.parse_number(crate::precise::Precise::stringMul(&minValueEv, &precisionString), &[]);
maxAmount = self.parse_number(crate::precise::Precise::stringMul(&maxValueEv, &precisionString), &[]);
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("info".to_string(), rawCurrency.clone());
m.insert("code".to_string(), code.clone());
m.insert("name".to_string(), self.safe_string_k(rawCurrency.clone(), "name", &[]));
m.insert("active".to_string(), Value::Bool(is_equal(&self.safe_string_k(rawCurrency.clone(), "status", &[]), &Value::Str("Listed".to_string()))));
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), precision.clone());
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(), minAmount.clone());
m.insert("max".to_string(), maxAmount.clone());
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("valueScale".to_string(), valueScale.clone());
m.insert("networks".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("crypto".to_string()));
m
}));
Value::Null
}
pub fn custom_parse_bid_ask(&self, mut bidask: Value, optional_args: &[Value]) -> Value {
let mut priceKey = get_arg(optional_args, 0, Value::Int(0));
let mut amountKey = get_arg(optional_args, 1, Value::Int(1));
let mut market = get_arg(optional_args, 2, Value::Null);
if is_equal(&market, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" customParseBidAsk() requires a market argument".to_string()))));
}
let mut amount: Value = self.safe_string(bidask.clone(), amountKey.clone(), &[]);
if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
amount = self.from_ev(amount.clone(), &[market.clone()]);
}
return Value::List(vec![self.parse_number(self.from_ep(self.safe_string(bidask.clone(), priceKey.clone(), &[]), &[market.clone()]), &[]), self.parse_number(amount.clone(), &[])]);
Value::Null
}
pub fn custom_parse_order_book(&self, mut orderbook: Value, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timestamp = get_arg(optional_args, 0, Value::Null);
let mut bidsKey = get_arg(optional_args, 1, Value::Str("bids".to_string()));
let mut asksKey = get_arg(optional_args, 2, Value::Str("asks".to_string()));
let mut priceKey = get_arg(optional_args, 3, Value::Int(0));
let mut amountKey = get_arg(optional_args, 4, Value::Int(1));
let mut market = get_arg(optional_args, 5, Value::Null);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("nonce".to_string(), Value::Null);
m
});
let mut sides: Value = Value::List(vec![bidsKey.clone(), asksKey.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1047: bool = true;
while { if !__for_first_1047 { i = add(&i, &Value::Int(1)); } __for_first_1047 = false; is_less_than(&i, &get_array_length(&sides)) } {
let mut side: Value = get_value(&sides, &i);
let mut side: Value = get_value(&sides, &i);
let mut orders: Value = Value::List(vec![]);
let mut bidasks: Value = self.safe_value(orderbook.clone(), side.clone(), &[]);
{
let mut k: Value = Value::Int(0);
let mut __for_first_1046: bool = true;
while { if !__for_first_1046 { k = add(&k, &Value::Int(1)); } __for_first_1046 = false; is_less_than(&k, &get_array_length(&bidasks)) } {
append_to_array(&mut orders, self.custom_parse_bid_ask(get_value(&bidasks, &k), &[priceKey.clone(), amountKey.clone(), market.clone()]));
}
}
add_element_to_object(&mut result, &side, orders.clone());
}
}
{ let __be_tmp = self.sort_by(get_value(&result, &bidsKey), Value::Int(0), &[Value::Bool(true)]); add_element_to_object(&mut result, &bidsKey, __be_tmp); };
{ let __be_tmp = self.sort_by(get_value(&result, &asksKey), Value::Int(0), &[]); add_element_to_object(&mut result, &asksKey, __be_tmp); };
return result;
Value::Null
}
/*
* @method
* @name phemex#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorderbook
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
let mut isStableSettled: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())))) || is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()))));
if is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) && is_true(&isStableSettled) {
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_get_md_v2_orderbook(&[__ws_arg_0]).await;
} else {
if is_true(&(!is_equal(&limit, &Value::Null))) && is_true(&(is_less_than_or_equal(&limit, &Value::Int(30)))) {
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_orderbook(&[__ws_arg_1]).await;
} else {
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_fullbook(&[__ws_arg_2]).await;
}
}
//
// {
// "error": null,
// "id": 0,
// "result": {
// "book": {
// "asks": [
// [ 23415000000, 105262000 ],
// [ 23416000000, 147914000 ],
// [ 23419000000, 160914000 ],
// ],
// "bids": [
// [ 23360000000, 32995000 ],
// [ 23359000000, 221887000 ],
// [ 23356000000, 284599000 ],
// ],
// },
// "depth": 30,
// "sequence": 1592059928,
// "symbol": "sETHUSDT",
// "timestamp": 1592387340020000955,
// "type": "snapshot"
// }
// }
//
let mut result: Value = self.safe_value_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut book: Value = self.safe_value2(result.clone(), Value::Str("book".to_string()), Value::Str("orderbook_p".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_product(result.clone(), Value::Str("timestamp".to_string()), Value::Float(0.000001), &[]);
let mut orderbook: Value = self.custom_parse_order_book(book.clone(), symbol.clone(), &[timestamp.clone(), Value::Str("bids".to_string()), Value::Str("asks".to_string()), Value::Int(0), Value::Int(1), market.clone()]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".to_string()), self.safe_integer_k(result.clone(), "sequence", &[]));
return orderbook;
Value::Null
}
pub fn to_en(&self, mut n: Value, mut scale: Value) -> Value {
if is_true(&(is_equal(&n, &Value::Null))) || is_true(&(is_equal(&scale, &Value::Null))) {
return Value::Null;
}
let mut stringN: Value = self.number_to_string(n.clone());
let mut precise = Precise::new(stringN);
{ let __sv_tmp = subtract(&get_value(&precise, &Value::Str("decimals".to_string())), &scale); crate::set_value(&mut precise, &Value::Str("decimals".to_string()), __sv_tmp); }
precise.reduce();
let mut preciseString: Value = to_string_val(&precise);
return self.parse_to_numeric(preciseString.clone());
Value::Null
}
pub fn to_ev(&self, mut amount: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
if is_true(&(is_equal(&amount, &Value::Null))) || is_true(&(is_equal(&market, &Value::Null))) {
return amount;
}
return self.to_en(amount.clone(), self.safe_integer_k(market.clone(), "valueScale", &[]));
Value::Null
}
pub fn to_ep(&self, mut price: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
if is_true(&(is_equal(&price, &Value::Null))) || is_true(&(is_equal(&market, &Value::Null))) {
return price;
}
return self.to_en(price.clone(), self.safe_integer_k(market.clone(), "priceScale", &[]));
Value::Null
}
pub fn from_en(&self, mut en: Value, mut scale: Value) -> Value {
if is_equal(&en, &Value::Null) || is_equal(&scale, &Value::Null) {
return Value::Null;
}
let mut precise = Precise::new(en);
{ let __sv_tmp = self.sum(&[get_value(&precise, &Value::Str("decimals".to_string())), scale.clone()]); crate::set_value(&mut precise, &Value::Str("decimals".to_string()), __sv_tmp); }
precise.reduce();
return to_string_val(&precise);
Value::Null
}
pub fn from_ep(&self, mut ep: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
if is_true(&(is_equal(&ep, &Value::Null))) || is_true(&(is_equal(&market, &Value::Null))) {
return ep;
}
return self.from_en(ep.clone(), self.safe_integer_k(market.clone(), "priceScale", &[]));
Value::Null
}
pub fn from_ev(&self, mut ev: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
if is_true(&(is_equal(&ev, &Value::Null))) || is_true(&(is_equal(&market, &Value::Null))) {
return ev;
}
return self.from_en(ev.clone(), self.safe_integer_k(market.clone(), "valueScale", &[]));
Value::Null
}
pub fn from_er(&self, mut er: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
if is_true(&(is_equal(&er, &Value::Null))) || is_true(&(is_equal(&market, &Value::Null))) {
return er;
}
return self.from_en(er.clone(), self.safe_integer_k(market.clone(), "ratioScale", &[]));
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// 1592467200, // timestamp
// 300, // interval
// 23376000000, // last
// 23322000000, // open
// 23381000000, // high
// 23315000000, // low
// 23367000000, // close
// 208671000, // base volume
// 48759063370, // quote volume
// ]
//
let mut baseVolume: Value = Value::Null;
if is_true(&(!is_equal(&market, &Value::Null))) && is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))) {
baseVolume = self.parse_number(self.from_ev(self.safe_string(ohlcv.clone(), Value::Int(7), &[]), &[market.clone()]), &[]);
} else {
baseVolume = self.safe_number(ohlcv.clone(), Value::Int(7), &[]);
}
return Value::List(vec![self.safe_timestamp(ohlcv.clone(), Value::Int(0), &[]), self.parse_number(self.from_ep(self.safe_string(ohlcv.clone(), Value::Int(3), &[]), &[market.clone()]), &[]), self.parse_number(self.from_ep(self.safe_string(ohlcv.clone(), Value::Int(4), &[]), &[market.clone()]), &[]), self.parse_number(self.from_ep(self.safe_string(ohlcv.clone(), Value::Int(5), &[]), &[market.clone()]), &[]), self.parse_number(self.from_ep(self.safe_string(ohlcv.clone(), Value::Int(6), &[]), &[market.clone()]), &[]), baseVolume.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querykline
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-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] *only used for USDT settled contracts, otherwise is emulated and not supported by the exchange* 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] *USDT settled/ linear swaps only* end time in ms
* @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".to_string()));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut userLimit: Value = limit.clone();
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("resolution".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut until: Value = self.safe_integer2(params.clone(), Value::Str("until".to_string()), Value::Str("to".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
let mut isStableSettled: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())))) || is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()))));
let mut usesSpecialFromToEndpoint: bool = is_true(&((is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) || is_true(&isStableSettled)))) && is_true(&(is_true(&(!is_equal(&since, &Value::Null))) || is_true(&(!is_equal(&until, &Value::Null)))));
let mut maxLimit: Value = Value::Int(1000);
if is_true(&usesSpecialFromToEndpoint) {
maxLimit = Value::Int(2000);
}
if is_equal(&limit, &Value::Null) {
limit = maxLimit.clone();
}
add_element_to_object(&mut request, &Value::Str("limit".to_string()), crate::runtime::Math::min(&limit, &maxLimit));
let mut response: Value = Value::Null;
if is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) || is_true(&isStableSettled) {
if is_true(&(!is_equal(&until, &Value::Null))) || is_true(&(!is_equal(&since, &Value::Null))) {
let mut candleDuration: Value = self.parse_timeframe(timeframe.clone());
if !is_equal(&since, &Value::Null) {
since = math_round(÷(&since, &Value::Int(1000)));
add_element_to_object(&mut request, &Value::Str("from".to_string()), since.clone());
} else {
// when 'to' is defined since is mandatory
since = subtract(&math_round(÷(&until, &Value::Int(1000))), &(multiply(&maxLimit, &candleDuration)));
add_element_to_object(&mut request, &Value::Str("from".to_string()), since.clone());
}
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("to".to_string()), math_round(÷(&until, &Value::Int(1000))));
} else {
// when since is defined 'to' is mandatory
let mut to: Value = add(&since, &(multiply(&maxLimit, &candleDuration)));
let mut now: Value = self.seconds();
if is_greater_than(&to, &now) {
to = now.clone();
}
add_element_to_object(&mut request, &Value::Str("to".to_string()), to.clone());
}
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_md_v2_kline_list(&[__ws_arg_3]).await;
} else {
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_md_v2_kline_last(&[__ws_arg_4]).await;
}
} else {
if !is_equal(&since, &Value::Null) {
// phemex also provides kline query with from/to, however, this interface is NOT recommended and does not work properly.
// we do not send since param to the exchange, instead we calculate appropriate limit param
let mut duration: Value = multiply(&self.parse_timeframe(timeframe.clone()), &Value::Int(1000));
let mut timeDelta: Value = subtract(&self.milliseconds(), &since);
limit = self.parse_to_int(divide(&timeDelta, &duration)); // setting limit to the number of candles after since
}
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_md_v2_kline(&[__ws_arg_5]).await;
}
//
// {
// "code":0,
// "msg":"OK",
// "data":{
// "total":-1,
// "rows":[
// [1592467200,300,23376000000,23322000000,23381000000,23315000000,23367000000,208671000,48759063370],
// [1592467500,300,23367000000,23314000000,23390000000,23311000000,23331000000,234820000,54848948710],
// [1592467800,300,23331000000,23385000000,23391000000,23326000000,23387000000,152931000,35747882250],
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
return self.parse_ohlc_vs(rows.clone(), &[market.clone(), timeframe.clone(), since.clone(), userLimit.clone()]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot
//
// {
// "askEp": 943836000000,
// "bidEp": 943601000000,
// "highEp": 955946000000,
// "lastEp": 943803000000,
// "lowEp": 924973000000,
// "openEp": 948693000000,
// "symbol": "sBTCUSDT",
// "timestamp": 1592471203505728630,
// "turnoverEv": 111822826123103,
// "volumeEv": 11880532281
// }
//
// swap
//
// {
// "askEp": 2332500,
// "bidEp": 2331000,
// "fundingRateEr": 10000,
// "highEp": 2380000,
// "indexEp": 2329057,
// "lastEp": 2331500,
// "lowEp": 2274000,
// "markEp": 2329232,
// "openEp": 2337500,
// "openInterest": 1298050,
// "predFundingRateEr": 19921,
// "symbol": "ETHUSD",
// "timestamp": 1592474241582701416,
// "turnoverEv": 47228362330,
// "volume": 4053863
// }
// linear swap v2
//
// {
// "closeRp":"16820.5",
// "fundingRateRr":"0.0001",
// "highRp":"16962.1",
// "indexPriceRp":"16830.15651565",
// "lowRp":"16785",
// "markPriceRp":"16830.97534951",
// "openInterestRv":"1323.596",
// "openRp":"16851.7",
// "predFundingRateRr":"0.0001",
// "symbol":"BTCUSDT",
// "timestamp":"1672142789065593096",
// "turnoverRv":"124835296.0538",
// "volumeRq":"7406.95"
// }
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut timestamp: Value = self.safe_integer_product(ticker.clone(), Value::Str("timestamp".to_string()), Value::Float(0.000001), &[]);
let mut last: Value = self.from_ep(self.safe_string2(ticker.clone(), Value::Str("lastEp".to_string()), Value::Str("closeRp".to_string()), &[]), &[market.clone()]);
let mut quoteVolume: Value = self.from_er(self.safe_string2(ticker.clone(), Value::Str("turnoverEv".to_string()), Value::Str("turnoverRv".to_string()), &[]), &[market.clone()]);
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "volume", &[]);
if is_equal(&baseVolume, &Value::Null) {
baseVolume = self.from_ev(self.safe_string2(ticker.clone(), Value::Str("volumeEv".to_string()), Value::Str("volumeRq".to_string()), &[]), &[market.clone()]);
}
let mut open: Value = self.from_ep(self.safe_string_k(ticker.clone(), "openEp", &[]), &[market.clone()]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("high".to_string(), self.from_ep(self.safe_string2(ticker.clone(), Value::Str("highEp".to_string()), Value::Str("highRp".to_string()), &[]), &[market.clone()]));
m.insert("low".to_string(), self.from_ep(self.safe_string2(ticker.clone(), Value::Str("lowEp".to_string()), Value::Str("lowRp".to_string()), &[]), &[market.clone()]));
m.insert("bid".to_string(), self.from_ep(self.safe_string_k(ticker.clone(), "bidEp", &[]), &[market.clone()]));
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), self.from_ep(self.safe_string_k(ticker.clone(), "askEp", &[]), &[market.clone()]));
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), open.clone());
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last.clone());
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume.clone());
m.insert("quoteVolume".to_string(), quoteVolume.clone());
m.insert("info".to_string(), ticker.clone());
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query24hrsticker
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
if is_true(&(is_equal(&get_value(&market, &Value::Str("inverse".to_string())), &Value::Bool(true)))) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USD".to_string())) {
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_ticker24hr(&[__ws_arg_6]).await;
} else {
let __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_get_md_v2_ticker24hr(&[__ws_arg_7]).await;
}
} else {
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_spot_ticker24hr(&[__ws_arg_8]).await;
}
//
// spot
//
// {
// "error": null,
// "id": 0,
// "result": {
// "askEp": 943836000000,
// "bidEp": 943601000000,
// "highEp": 955946000000,
// "lastEp": 943803000000,
// "lowEp": 924973000000,
// "openEp": 948693000000,
// "symbol": "sBTCUSDT",
// "timestamp": 1592471203505728630,
// "turnoverEv": 111822826123103,
// "volumeEv": 11880532281
// }
// }
//
// swap
//
// {
// "error": null,
// "id": 0,
// "result": {
// "askEp": 2332500,
// "bidEp": 2331000,
// "fundingRateEr": 10000,
// "highEp": 2380000,
// "indexEp": 2329057,
// "lastEp": 2331500,
// "lowEp": 2274000,
// "markEp": 2329232,
// "openEp": 2337500,
// "openInterest": 1298050,
// "predFundingRateEr": 19921,
// "symbol": "ETHUSD",
// "timestamp": 1592474241582701416,
// "turnoverEv": 47228362330,
// "volume": 4053863
// }
// }
//
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(result.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://phemex-docs.github.io/#query-24-hours-ticker-for-all-symbols-2 // spot
* @see https://phemex-docs.github.io/#query-24-ticker-for-all-symbols // linear
* @see https://phemex-docs.github.io/#query-24-hours-ticker-for-all-symbols // inverse
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbols, &Value::Null) {
let mut first: Value = self.safe_value(symbols.clone(), Value::Int(0), &[]);
market = self.market(first.clone());
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchTickers".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut subType: Value = Value::Null;
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("fetchTickers".to_string()), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut query: Value = self.omit(params.clone(), Value::Str("type".to_string()), &[]);
let mut response: Value = Value::Null;
if is_equal(&type_var, &Value::Str("spot".to_string())) {
response = self.v1_get_md_spot_ticker24hr_all(&[query.clone()]).await;
} else if is_equal(&subType, &Value::Str("inverse".to_string())) || is_equal(&self.safe_string_k(market.clone(), "settle", &[]), &Value::Str("USD".to_string())) {
response = self.v1_get_md_ticker24hr_all(&[query.clone()]).await;
} else {
response = self.v2_get_md_v2_ticker24hr_all(&[query.clone()]).await;
}
let mut result: Value = self.safe_list_k(response.clone(), "result", &[Value::List(vec![])]);
return self.parse_tickers(result.clone(), &[symbols.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#querytrades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
let mut isStableSettled: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())))) || is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()))));
if is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))) && is_true(&isStableSettled) {
let __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_get_md_v2_trade(&[__ws_arg_9]).await;
} else {
let __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_trade(&[__ws_arg_10]).await;
}
//
// {
// "error": null,
// "id": 0,
// "result": {
// "sequence": 1315644947,
// "symbol": "BTCUSD",
// "trades": [
// [ 1592541746712239749, 13156448570000, "Buy", 93070000, 40173 ],
// [ 1592541740434625085, 13156447110000, "Sell", 93065000, 5000 ],
// [ 1592541732958241616, 13156441390000, "Buy", 93070000, 3460 ],
// ],
// "type": "snapshot"
// }
// }
//
let mut result: Value = self.safe_value_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trades: Value = self.safe_value2(result.clone(), Value::Str("trades".to_string()), Value::Str("trades_p".to_string()), &[Value::List(vec![])]);
return self.parse_trades(trades.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades (public) spot & contract
//
// [
// 1592541746712239749,
// 13156448570000,
// "Buy",
// 93070000,
// 40173
// ]
//
// fetchTrades (public) perp
//
// [
// 1675690986063435800,
// "Sell",
// "22857.4",
// "0.269"
// ]
//
// fetchMyTrades (private)
//
// spot
//
// {
// "qtyType": "ByQuote",
// "transactTimeNs": 1589450974800550100,
// "clOrdID": "8ba59d40-df25-d4b0-14cf-0703f44e9690",
// "orderID": "b2b7018d-f02f-4c59-b4cf-051b9c2d2e83",
// "symbol": "sBTCUSDT",
// "side": "Buy",
// "priceEP": 970056000000,
// "baseQtyEv": 0,
// "quoteQtyEv": 1000000000,
// "action": "New",
// "execStatus": "MakerFill",
// "ordStatus": "Filled",
// "ordType": "Limit",
// "execInst": "None",
// "timeInForce": "GoodTillCancel",
// "stopDirection": "UNSPECIFIED",
// "tradeType": "Trade",
// "stopPxEp": 0,
// "execId": "c6bd8979-07ba-5946-b07e-f8b65135dbb1",
// "execPriceEp": 970056000000,
// "execBaseQtyEv": 103000,
// "execQuoteQtyEv": 999157680,
// "leavesBaseQtyEv": 0,
// "leavesQuoteQtyEv": 0,
// "execFeeEv": 0,
// "feeRateEr": 0
// "baseCurrency": "BTC",
// "quoteCurrency": "USDT",
// "feeCurrency": "BTC"
// }
//
// swap
//
// {
// "transactTimeNs": 1578026629824704800,
// "symbol": "BTCUSD",
// "currency": "BTC",
// "action": "Replace",
// "side": "Sell",
// "tradeType": "Trade",
// "execQty": 700,
// "execPriceEp": 71500000,
// "orderQty": 700,
// "priceEp": 71500000,
// "execValueEv": 9790209,
// "feeRateEr": -25000,
// "execFeeEv": -2447,
// "ordType": "Limit",
// "execID": "b01671a1-5ddc-5def-b80a-5311522fd4bf",
// "orderID": "b63bc982-be3a-45e0-8974-43d6375fb626",
// "clOrdID": "uuid-1577463487504",
// "execStatus": "MakerFill"
// }
// perpetual
// {
// "accountID": 9328670003,
// "action": "New",
// "actionBy": "ByUser",
// "actionTimeNs": 1666858780876924611,
// "addedSeq": 77751555,
// "apRp": "0",
// "bonusChangedAmountRv": "0",
// "bpRp": "0",
// "clOrdID": "c0327a7d-9064-62a9-28f6-2db9aaaa04e0",
// "closedPnlRv": "0",
// "closedSize": "0",
// "code": 0,
// "cumFeeRv": "0",
// "cumQty": "0",
// "cumValueRv": "0",
// "curAccBalanceRv": "1508.489893982237",
// "curAssignedPosBalanceRv": "24.62786650928",
// "curBonusBalanceRv": "0",
// "curLeverageRr": "-10",
// "curPosSide": "Buy",
// "curPosSize": "0.043",
// "curPosTerm": 1,
// "curPosValueRv": "894.0689",
// "curRiskLimitRv": "1000000",
// "currency": "USDT",
// "cxlRejReason": 0,
// "displayQty": "0.003",
// "execFeeRv": "0",
// "execID": "00000000-0000-0000-0000-000000000000",
// "execPriceRp": "20723.7",
// "execQty": "0",
// "execSeq": 77751555,
// "execStatus": "New",
// "execValueRv": "0",
// "feeRateRr": "0",
// "leavesQty": "0.003",
// "leavesValueRv": "63.4503",
// "message": "No error",
// "ordStatus": "New",
// "ordType": "Market",
// "orderID": "fa64c6f2-47a4-4929-aab4-b7fa9bbc4323",
// "orderQty": "0.003",
// "pegOffsetValueRp": "0",
// "posSide": "Long",
// "priceRp": "21150.1",
// "relatedPosTerm": 1,
// "relatedReqNum": 11,
// "side": "Buy",
// "slTrigger": "ByMarkPrice",
// "stopLossRp": "0",
// "stopPxRp": "0",
// "symbol": "BTCUSDT",
// "takeProfitRp": "0",
// "timeInForce": "ImmediateOrCancel",
// "tpTrigger": "ByLastPrice",
// "tradeType": "Amend",
// "transactTimeNs": 1666858780881545305,
// "userID": 932867
// }
//
// swap - USDT
//
// {
// "createdAt": 1666226932259,
// "symbol": "ETHUSDT",
// "currency": "USDT",
// "action": 1,
// "tradeType": 1,
// "execQtyRq": "0.01",
// "execPriceRp": "1271.9",
// "side": 1,
// "orderQtyRq": "0.78",
// "priceRp": "1271.9",
// "execValueRv": "12.719",
// "feeRateRr": "0.0001",
// "execFeeRv": "0.0012719",
// "ordType": 2,
// "execId": "8718cae",
// "execStatus": 6
// }
// spot with fees paid using PT token
// "createdAt": "1714990724076",
// "symbol": "BTCUSDT",
// "currency": "USDT",
// "action": "1",
// "tradeType": "1",
// "execQtyRq": "0.003",
// "execPriceRp": "64935",
// "side": "2",
// "orderQtyRq": "0.003",
// "priceRp": "51600",
// "execValueRv": "194.805",
// "feeRateRr": "0.000495",
// "execFeeRv": "0",
// "ordType": "3",
// "execId": "XXXXXX",
// "execStatus": "7",
// "posSide": "1",
// "ptFeeRv": "0.110012249248",
// "ptPriceRp": "0.876524893"
//
let mut priceString: Value = Value::Null;
let mut amountString: Value = Value::Null;
let mut timestamp: Value = Value::Null;
let mut id: Value = Value::Null;
let mut side: Value = Value::Null;
let mut costString: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut feeCostString: Value = Value::Null;
let mut feeRateString: Value = Value::Null;
let mut feeCurrencyCode: Value = Value::Null;
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut orderId: Value = Value::Null;
let mut takerOrMaker: Value = Value::Null;
if is_true(&Value::Bool(is_array(&trade))) {
let mut tradeLength: Value = get_array_length(&trade);
timestamp = self.safe_integer_product(trade.clone(), Value::Int(0), Value::Float(0.000001), &[]);
if is_greater_than(&tradeLength, &Value::Int(4)) {
id = self.safe_string(trade.clone(), subtract(&tradeLength, &Value::Int(4)), &[]);
}
side = self.safe_string_lower(trade.clone(), subtract(&tradeLength, &Value::Int(3)), &[]);
priceString = self.safe_string(trade.clone(), subtract(&tradeLength, &Value::Int(2)), &[]);
amountString = self.safe_string(trade.clone(), subtract(&tradeLength, &Value::Int(1)), &[]);
if is_number(&get_value(&trade, &subtract(&tradeLength, &Value::Int(2)))) {
priceString = self.from_ep(priceString.clone(), &[market.clone()]);
amountString = self.from_ev(amountString.clone(), &[market.clone()]);
}
} else {
timestamp = self.safe_integer_product(trade.clone(), Value::Str("transactTimeNs".to_string()), Value::Float(0.000001), &[]);
if is_equal(×tamp, &Value::Null) {
timestamp = self.safe_integer_k(trade.clone(), "createdAt", &[]);
}
id = self.safe_string2(trade.clone(), Value::Str("execId".to_string()), Value::Str("execID".to_string()), &[]);
orderId = self.safe_string_k(trade.clone(), "orderID", &[]);
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
let mut sideId: Value = self.safe_string_lower(trade.clone(), Value::Str("side".to_string()), &[]);
if is_true(&(is_equal(&sideId, &Value::Str("buy".to_string())))) || is_true(&(is_equal(&sideId, &Value::Str("sell".to_string())))) {
side = sideId.clone();
} else if !is_equal(&sideId, &Value::Null) {
side = ternary(is_true(&(is_equal(&sideId, &Value::Str("1".to_string())))), Value::Str("buy".to_string()), Value::Str("sell".to_string()));
}
let mut ordType: Value = self.safe_string_k(trade.clone(), "ordType", &[]);
if is_equal(&ordType, &Value::Str("1".to_string())) {
type_var = Value::Str("market".to_string());
} else if is_equal(&ordType, &Value::Str("2".to_string())) {
type_var = Value::Str("limit".to_string());
}
priceString = self.safe_string_k(trade.clone(), "execPriceRp", &[]);
amountString = self.safe_string_k(trade.clone(), "execQtyRq", &[]);
costString = self.safe_string_k(trade.clone(), "execValueRv", &[]);
feeCostString = self.omit_zero(self.safe_string_k(trade.clone(), "execFeeRv", &[]));
feeRateString = self.safe_string_k(trade.clone(), "feeRateRr", &[]);
if !is_equal(&feeCostString, &Value::Null) {
let mut currencyId: Value = self.safe_string_k(trade.clone(), "currency", &[]);
feeCurrencyCode = self.safe_currency_code(currencyId.clone(), &[]);
} else {
let mut ptFeeRv: Value = self.omit_zero(self.safe_string_k(trade.clone(), "ptFeeRv", &[]));
if !is_equal(&ptFeeRv, &Value::Null) {
feeCostString = ptFeeRv.clone();
feeCurrencyCode = Value::Str("PT".to_string());
}
}
} else {
side = self.safe_string_lower(trade.clone(), Value::Str("side".to_string()), &[]);
type_var = self.parse_order_type(self.safe_string_k(trade.clone(), "ordType", &[]));
let mut execStatus: Value = self.safe_string_k(trade.clone(), "execStatus", &[]);
if is_equal(&execStatus, &Value::Str("MakerFill".to_string())) {
takerOrMaker = Value::Str("maker".to_string());
}
priceString = self.from_ep(self.safe_string_k(trade.clone(), "execPriceEp", &[]), &[market.clone()]);
amountString = self.from_ev(self.safe_string_k(trade.clone(), "execBaseQtyEv", &[]), &[market.clone()]);
amountString = self.safe_string_k(trade.clone(), "execQty", &[amountString.clone()]);
costString = self.from_er(self.safe_string2(trade.clone(), Value::Str("execQuoteQtyEv".to_string()), Value::Str("execValueEv".to_string()), &[]), &[market.clone()]);
feeCostString = self.from_er(self.omit_zero(self.safe_string_k(trade.clone(), "execFeeEv", &[])), &[market.clone()]);
if !is_equal(&feeCostString, &Value::Null) {
feeRateString = self.from_er(self.safe_string_k(trade.clone(), "feeRateEr", &[]), &[market.clone()]);
if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
feeCurrencyCode = self.safe_currency_code(self.safe_string_k(trade.clone(), "feeCurrency", &[]), &[]);
} else {
let mut info: Value = self.safe_value_k(market.clone(), "info", &[]);
if !is_equal(&info, &Value::Null) {
let mut settlementCurrencyId: Value = self.safe_string_k(info.clone(), "settlementCurrency", &[]);
feeCurrencyCode = self.safe_currency_code(settlementCurrencyId.clone(), &[]);
}
}
} else {
feeCostString = self.safe_string_k(trade.clone(), "ptFeeRv", &[]);
if !is_equal(&feeCostString, &Value::Null) {
feeCurrencyCode = Value::Str("PT".to_string());
}
}
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCostString.clone());
m.insert("rate".to_string(), feeRateString.clone());
m.insert("currency".to_string(), feeCurrencyCode.clone());
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("order".to_string(), orderId.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("side".to_string(), side.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("price".to_string(), priceString.clone());
m.insert("amount".to_string(), amountString.clone());
m.insert("cost".to_string(), costString.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_spot_balance(&self, mut response: Value) -> Value {
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "currency":"USDT",
// "balanceEv":0,
// "lockedTradingBalanceEv":0,
// "lockedWithdrawEv":0,
// "lastUpdateTimeNs":1592065834511322514,
// "walletVid":0
// },
// {
// "currency":"ETH",
// "balanceEv":0,
// "lockedTradingBalanceEv":0,
// "lockedWithdrawEv":0,
// "lastUpdateTimeNs":1592065834511322514,
// "walletVid":0
// }
// ]
// }
//
let mut timestamp: Value = Value::Null;
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1048: bool = true;
while { if !__for_first_1048 { i = add(&i, &Value::Int(1)); } __for_first_1048 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut balance: Value = get_value(&data, &i);
let mut balance: Value = get_value(&data, &i);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut currency: Value = self.safe_value(self.currencies.clone(), code.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut scale: Value = self.safe_integer_k(currency.clone(), "valueScale", &[Value::Int(8)]);
let mut account: Value = self.account();
let mut balanceEv: Value = self.safe_string_k(balance.clone(), "balanceEv", &[]);
let mut lockedTradingBalanceEv: Value = self.safe_string_k(balance.clone(), "lockedTradingBalanceEv", &[]);
let mut lockedWithdrawEv: Value = self.safe_string_k(balance.clone(), "lockedWithdrawEv", &[]);
let mut total: Value = self.from_en(balanceEv.clone(), scale.clone());
let mut lockedTradingBalance: Value = self.from_en(lockedTradingBalanceEv.clone(), scale.clone());
let mut lockedWithdraw: Value = self.from_en(lockedWithdrawEv.clone(), scale.clone());
let mut used: Value = crate::precise::Precise::stringAdd(&lockedTradingBalance, &lockedWithdraw);
let mut lastUpdateTimeNs: Value = self.safe_integer_product(balance.clone(), Value::Str("lastUpdateTimeNs".to_string()), Value::Float(0.000001), &[]);
timestamp = ternary(is_true(&(is_equal(×tamp, &Value::Null))), lastUpdateTimeNs.clone(), crate::runtime::Math::max(×tamp, &lastUpdateTimeNs));
add_element_to_object(&mut account, &Value::Str("total".to_string()), total.clone());
add_element_to_object(&mut account, &Value::Str("used".to_string()), used.clone());
add_element_to_object(&mut result, &code, account.clone());
}
}
add_element_to_object(&mut result, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut result, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
return self.safe_balance(result.clone());
Value::Null
}
pub fn parse_swap_balance(&self, mut response: Value) -> Value {
// usdt
// {
// "info": {
// "code": "0",
// "msg": '',
// "data": {
// "account": {
// "userID": "940666",
// "accountId": "9406660003",
// "currency": "USDT",
// "accountBalanceRv": "99.93143972",
// "totalUsedBalanceRv": "0.40456",
// "bonusBalanceRv": "0"
// },
// }
//
// {
// "code":0,
// "msg":"",
// "data":{
// "account":{
// "accountId":6192120001,
// "currency":"BTC",
// "accountBalanceEv":1254744,
// "totalUsedBalanceEv":0,
// "bonusBalanceEv":1254744
// }
// }
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut balance: Value = self.safe_value_k(data.clone(), "account", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut currency: Value = self.currency(code.clone());
let mut valueScale: Value = self.safe_integer_k(currency.clone(), "valueScale", &[Value::Int(8)]);
let mut account: Value = self.account();
let mut accountBalanceEv: Value = self.safe_string2(balance.clone(), Value::Str("accountBalanceEv".to_string()), Value::Str("accountBalanceRv".to_string()), &[]);
let mut totalUsedBalanceEv: Value = self.safe_string2(balance.clone(), Value::Str("totalUsedBalanceEv".to_string()), Value::Str("totalUsedBalanceRv".to_string()), &[]);
let mut needsConversion: bool = !is_equal(&code, &Value::Str("USDT".to_string()));
add_element_to_object(&mut account, &Value::Str("total".to_string()), ternary(is_true(&needsConversion), self.from_en(accountBalanceEv.clone(), valueScale.clone()), accountBalanceEv.clone()));
add_element_to_object(&mut account, &Value::Str("used".to_string()), ternary(is_true(&needsConversion), self.from_en(totalUsedBalanceEv.clone(), valueScale.clone()), totalUsedBalanceEv.clone()));
add_element_to_object(&mut result, &code, account.clone());
return self.safe_balance(result.clone());
Value::Null
}
/*
* @method
* @name phemex#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://phemex-docs.github.io/#query-wallets
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
* @see https://phemex-docs.github.io/#query-trading-account-and-positions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] spot or swap
* @param {string} [params.code] *swap only* currency code of the balance to query (USD, USDT, etc), default is USDT
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &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".to_string()), &[Value::Null, params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut code: Value = self.safe_string_k(params.clone(), "code", &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("code".to_string())]), &[]);
let mut response: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_true(&(!is_equal(&type_var, &Value::Str("spot".to_string())))) && is_true(&(!is_equal(&type_var, &Value::Str("swap".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&add(&add(&self.id, &Value::Str(" does not support ".to_string())), &type_var), &Value::Str(" markets, only spot and swap".to_string()))));
}
if is_equal(&type_var, &Value::Str("swap".to_string())) {
let mut settle: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchBalance".to_string()), Value::Str("settle".to_string()), &[Value::Str("USDT".to_string())]); settle = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&code, &Value::Null) || !is_equal(&settle, &Value::Null) {
let mut coin: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
coin = code.clone();
} else {
coin = settle.clone();
}
let mut currency: Value = self.currency(coin.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
if is_equal(&get_value(¤cy, &Value::Str("id".to_string())), &Value::Str("USDT".to_string())) {
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_accounts_account_positions(&[__ws_arg_11]).await;
} else {
let __ws_arg_12 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_accounts_account_positions(&[__ws_arg_12]).await;
}
} else {
let mut currency: Value = self.safe_string_k(params.clone(), "currency", &[]);
if is_equal(¤cy, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" fetchBalance() requires a code parameter or a currency or settle parameter for ".to_string())), &type_var), &Value::Str(" type".to_string()))));
}
let __ws_arg_13 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_spot_wallets(&[__ws_arg_13]).await;
}
} else {
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_spot_wallets(&[__ws_arg_14]).await;
}
//
// usdt
// {
// "info": {
// "code": "0",
// "msg": '',
// "data": {
// "account": {
// "userID": "940666",
// "accountId": "9406660003",
// "currency": "USDT",
// "accountBalanceRv": "99.93143972",
// "totalUsedBalanceRv": "0.40456",
// "bonusBalanceRv": "0"
// },
// }
//
// spot
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "currency":"USDT",
// "balanceEv":0,
// "lockedTradingBalanceEv":0,
// "lockedWithdrawEv":0,
// "lastUpdateTimeNs":1592065834511322514,
// "walletVid":0
// },
// {
// "currency":"ETH",
// "balanceEv":0,
// "lockedTradingBalanceEv":0,
// "lockedWithdrawEv":0,
// "lastUpdateTimeNs":1592065834511322514,
// "walletVid":0
// }
// ]
// }
//
// swap
//
// {
// "code":0,
// "msg":"",
// "data":{
// "account":{
// "accountId":6192120001,
// "currency":"BTC",
// "accountBalanceEv":1254744,
// "totalUsedBalanceEv":0,
// "bonusBalanceEv":1254744
// },
// "positions":[
// {
// "accountID":6192120001,
// "symbol":"BTCUSD",
// "currency":"BTC",
// "side":"None",
// "positionStatus":"Normal",
// "crossMargin":false,
// "leverageEr":0,
// "leverage":0E-8,
// "initMarginReqEr":1000000,
// "initMarginReq":0.01000000,
// "maintMarginReqEr":500000,
// "maintMarginReq":0.00500000,
// "riskLimitEv":10000000000,
// "riskLimit":100.00000000,
// "size":0,
// "value":0E-8,
// "valueEv":0,
// "avgEntryPriceEp":0,
// "avgEntryPrice":0E-8,
// "posCostEv":0,
// "posCost":0E-8,
// "assignedPosBalanceEv":0,
// "assignedPosBalance":0E-8,
// "bankruptCommEv":0,
// "bankruptComm":0E-8,
// "bankruptPriceEp":0,
// "bankruptPrice":0E-8,
// "positionMarginEv":0,
// "positionMargin":0E-8,
// "liquidationPriceEp":0,
// "liquidationPrice":0E-8,
// "deleveragePercentileEr":0,
// "deleveragePercentile":0E-8,
// "buyValueToCostEr":1150750,
// "buyValueToCost":0.01150750,
// "sellValueToCostEr":1149250,
// "sellValueToCost":0.01149250,
// "markPriceEp":96359083,
// "markPrice":9635.90830000,
// "markValueEv":0,
// "markValue":null,
// "unRealisedPosLossEv":0,
// "unRealisedPosLoss":null,
// "estimatedOrdLossEv":0,
// "estimatedOrdLoss":0E-8,
// "usedBalanceEv":0,
// "usedBalance":0E-8,
// "takeProfitEp":0,
// "takeProfit":null,
// "stopLossEp":0,
// "stopLoss":null,
// "realisedPnlEv":0,
// "realisedPnl":null,
// "cumRealisedPnlEv":0,
// "cumRealisedPnl":null
// }
// ]
// }
// }
//
if is_equal(&type_var, &Value::Str("swap".to_string())) {
return self.parse_swap_balance(response.clone());
}
return self.parse_spot_balance(response.clone());
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Created".to_string(), Value::Str("open".to_string()));
m.insert("Untriggered".to_string(), Value::Str("open".to_string()));
m.insert("Deactivated".to_string(), Value::Str("closed".to_string()));
m.insert("Triggered".to_string(), Value::Str("open".to_string()));
m.insert("Rejected".to_string(), Value::Str("rejected".to_string()));
m.insert("New".to_string(), Value::Str("open".to_string()));
m.insert("PartiallyFilled".to_string(), Value::Str("open".to_string()));
m.insert("Filled".to_string(), Value::Str("closed".to_string()));
m.insert("Canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("Suspended".to_string(), Value::Str("canceled".to_string()));
m.insert("1".to_string(), Value::Str("open".to_string()));
m.insert("2".to_string(), Value::Str("canceled".to_string()));
m.insert("3".to_string(), Value::Str("closed".to_string()));
m.insert("4".to_string(), Value::Str("canceled".to_string()));
m.insert("5".to_string(), Value::Str("open".to_string()));
m.insert("6".to_string(), Value::Str("open".to_string()));
m.insert("7".to_string(), Value::Str("closed".to_string()));
m.insert("8".to_string(), Value::Str("canceled".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("market".to_string()));
m.insert("2".to_string(), Value::Str("limit".to_string()));
m.insert("3".to_string(), Value::Str("stop".to_string()));
m.insert("4".to_string(), Value::Str("stopLimit".to_string()));
m.insert("5".to_string(), Value::Str("market".to_string()));
m.insert("6".to_string(), Value::Str("limit".to_string()));
m.insert("7".to_string(), Value::Str("market".to_string()));
m.insert("8".to_string(), Value::Str("market".to_string()));
m.insert("9".to_string(), Value::Str("stopLimit".to_string()));
m.insert("10".to_string(), Value::Str("market".to_string()));
m.insert("Limit".to_string(), Value::Str("limit".to_string()));
m.insert("Market".to_string(), Value::Str("market".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GoodTillCancel".to_string(), Value::Str("GTC".to_string()));
m.insert("PostOnly".to_string(), Value::Str("PO".to_string()));
m.insert("ImmediateOrCancel".to_string(), Value::Str("IOC".to_string()));
m.insert("FillOrKill".to_string(), Value::Str("FOK".to_string()));
m
});
return self.safe_string(timeInForces.clone(), timeInForce.clone(), &[timeInForce.clone()]);
Value::Null
}
pub fn parse_spot_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// spot
//
// {
// "orderID": "d1d09454-cabc-4a23-89a7-59d43363f16d",
// "clOrdID": "309bcd5c-9f6e-4a68-b775-4494542eb5cb",
// "priceEp": 0,
// "action": "New",
// "trigger": "UNSPECIFIED",
// "pegPriceType": "UNSPECIFIED",
// "stopDirection": "UNSPECIFIED",
// "bizError": 0,
// "symbol": "sBTCUSDT",
// "side": "Buy",
// "baseQtyEv": 0,
// "ordType": "Limit",
// "timeInForce": "GoodTillCancel",
// "ordStatus": "Created",
// "cumFeeEv": 0,
// "cumBaseQtyEv": 0,
// "cumQuoteQtyEv": 0,
// "leavesBaseQtyEv": 0,
// "leavesQuoteQtyEv": 0,
// "avgPriceEp": 0,
// "cumBaseAmountEv": 0,
// "cumQuoteAmountEv": 0,
// "quoteQtyEv": 0,
// "qtyType": "ByBase",
// "stopPxEp": 0,
// "pegOffsetValueEp": 0
// }
//
// {
// "orderID":"99232c3e-3d6a-455f-98cc-2061cdfe91bc",
// "stopPxEp":0,
// "avgPriceEp":0,
// "qtyType":"ByBase",
// "leavesBaseQtyEv":0,
// "leavesQuoteQtyEv":0,
// "baseQtyEv":"1000000000",
// "feeCurrency":"4",
// "stopDirection":"UNSPECIFIED",
// "symbol":"sETHUSDT",
// "side":"Buy",
// "quoteQtyEv":250000000000,
// "priceEp":25000000000,
// "ordType":"Limit",
// "timeInForce":"GoodTillCancel",
// "ordStatus":"Rejected",
// "execStatus":"NewRejected",
// "createTimeNs":1592675305266037130,
// "cumFeeEv":0,
// "cumBaseValueEv":0,
// "cumQuoteValueEv":0
// }
//
let mut id: Value = self.safe_string_k(order.clone(), "orderID", &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clOrdID", &[]);
if is_true(&(!is_equal(&clientOrderId, &Value::Null))) && is_true(&(is_less_than(&get_array_length(&clientOrderId), &Value::Int(1)))) {
clientOrderId = Value::Null;
}
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut price: Value = self.from_ep(self.safe_string_k(order.clone(), "priceEp", &[]), &[market.clone()]);
let mut amount: Value = self.from_ev(self.safe_string_k(order.clone(), "baseQtyEv", &[]), &[market.clone()]);
let mut remaining: Value = self.omit_zero(self.from_ev(self.safe_string_k(order.clone(), "leavesBaseQtyEv", &[]), &[market.clone()]));
let mut filled: Value = self.from_ev(self.safe_string2(order.clone(), Value::Str("cumBaseQtyEv".to_string()), Value::Str("cumBaseValueEv".to_string()), &[]), &[market.clone()]);
let mut cost: Value = self.from_er(self.safe_string2(order.clone(), Value::Str("cumQuoteValueEv".to_string()), Value::Str("quoteQtyEv".to_string()), &[]), &[market.clone()]);
let mut average: Value = self.from_ep(self.safe_string_k(order.clone(), "avgPriceEp", &[]), &[market.clone()]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "ordStatus", &[]));
let mut side: Value = self.safe_string_lower(order.clone(), Value::Str("side".to_string()), &[]);
let mut type_var: Value = self.parse_order_type(self.safe_string_k(order.clone(), "ordType", &[]));
let mut timestamp: Value = self.safe_integer_product2(order.clone(), Value::Str("actionTimeNs".to_string()), Value::Str("createTimeNs".to_string()), Value::Float(0.000001), &[]);
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.from_ev(self.safe_string_k(order.clone(), "cumFeeEv", &[]), &[market.clone()]);
if !is_equal(&feeCost, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(order.clone(), "feeCurrency", &[]), &[]));
m
});
}
let mut timeInForce: Value = self.parse_time_in_force(self.safe_string_k(order.clone(), "timeInForce", &[]));
let mut triggerPrice: Value = self.parse_number(self.omit_zero(self.from_ep(self.safe_string_k(order.clone(), "stopPxEp", &[]), &[])), &[]);
let mut postOnly: Value = Value::Bool(is_equal(&timeInForce, &Value::Str("PO".to_string())));
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), id.clone());
m.insert("clientOrderId".to_string(), clientOrderId.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("postOnly".to_string(), postOnly.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("triggerPrice".to_string(), triggerPrice.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("average".to_string(), average.clone());
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), remaining.clone());
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_order_side(&self, mut side: Value) -> Value {
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("buy".to_string()));
m.insert("2".to_string(), Value::Str("sell".to_string()));
m
});
return self.safe_string(sides.clone(), side.clone(), &[side.clone()]);
Value::Null
}
pub fn parse_swap_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "bizError":0,
// "orderID":"7a1ad384-44a3-4e54-a102-de4195a29e32",
// "clOrdID":"",
// "symbol":"ETHUSD",
// "side":"Buy",
// "actionTimeNs":1592668973945065381,
// "transactTimeNs":0,
// "orderType":"Market",
// "priceEp":2267500,
// "price":226.75000000,
// "orderQty":1,
// "displayQty":0,
// "timeInForce":"ImmediateOrCancel",
// "reduceOnly":false,
// "closedPnlEv":0,
// "closedPnl":0E-8,
// "closedSize":0,
// "cumQty":0,
// "cumValueEv":0,
// "cumValue":0E-8,
// "leavesQty":1,
// "leavesValueEv":11337,
// "leavesValue":1.13370000,
// "stopDirection":"UNSPECIFIED",
// "stopPxEp":0,
// "stopPx":0E-8,
// "trigger":"UNSPECIFIED",
// "pegOffsetValueEp":0,
// "execStatus":"PendingNew",
// "pegPriceType":"UNSPECIFIED",
// "ordStatus":"Created",
// "execInst": "ReduceOnly"
// }
//
// usdt
// {
// "bizError":"0",
// "orderID":"bd720dff-5647-4596-aa4e-656bac87aaad",
// "clOrdID":"ccxt2022843dffac9477b497",
// "symbol":"LTCUSDT",
// "side":"Buy",
// "actionTimeNs":"1677667878751724052",
// "transactTimeNs":"1677667878754017434",
// "orderType":"Limit",
// "priceRp":"40",
// "orderQtyRq":"0.1",
// "displayQtyRq":"0.1",
// "timeInForce":"GoodTillCancel",
// "reduceOnly":false,
// "closedPnlRv":"0",
// "closedSizeRq":"0",
// "cumQtyRq":"0",
// "cumValueRv":"0",
// "leavesQtyRq":"0.1",
// "leavesValueRv":"4",
// "stopDirection":"UNSPECIFIED",
// "stopPxRp":"0",
// "trigger":"UNSPECIFIED",
// "pegOffsetValueRp":"0",
// "pegOffsetProportionRr":"0",
// "execStatus":"New",
// "pegPriceType":"UNSPECIFIED",
// "ordStatus":"New",
// "execInst":"None",
// "takeProfitRp":"0",
// "stopLossRp":"0"
// }
//
// v2 orderList
// {
// "createdAt":"1677686231301",
// "symbol":"LTCUSDT",
// "orderQtyRq":"0.2",
// "side":"1",
// "posSide":"3",
// "priceRp":"50",
// "execQtyRq":"0",
// "leavesQtyRq":"0.2",
// "execPriceRp":"0",
// "orderValueRv":"10",
// "leavesValueRv":"10",
// "cumValueRv":"0",
// "stopDirection":"0",
// "stopPxRp":"0",
// "trigger":"0",
// "actionBy":"1",
// "execFeeRv":"0",
// "ordType":"2",
// "ordStatus":"5",
// "clOrdId":"4b3b188",
// "orderId":"4b3b1884-87cf-4897-b596-6693b7ed84d1",
// "execStatus":"5",
// "bizError":"0",
// "totalPnlRv":null,
// "avgTransactPriceRp":null,
// "orderDetailsVos":null,
// "tradeType":"0"
// }
//
let mut id: Value = self.safe_string2(order.clone(), Value::Str("orderID".to_string()), Value::Str("orderId".to_string()), &[]);
let mut clientOrderId: Value = self.safe_string2(order.clone(), Value::Str("clOrdID".to_string()), Value::Str("clOrdId".to_string()), &[]);
if is_true(&(!is_equal(&clientOrderId, &Value::Null))) && is_true(&(is_less_than(&get_array_length(&clientOrderId), &Value::Int(1)))) {
clientOrderId = Value::Null;
}
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "ordStatus", &[]));
let mut side: Value = self.parse_order_side(self.safe_string_lower(order.clone(), Value::Str("side".to_string()), &[]));
let mut type_var: Value = self.parse_order_type(self.safe_string_k(order.clone(), "orderType", &[]));
let mut price: Value = self.safe_string_k(order.clone(), "priceRp", &[]);
if is_equal(&price, &Value::Null) {
price = self.from_ep(self.safe_string_k(order.clone(), "priceEp", &[]), &[market.clone()]);
}
let mut amount: Value = self.safe_number2(order.clone(), Value::Str("orderQty".to_string()), Value::Str("orderQtyRq".to_string()), &[]);
let mut filled: Value = self.safe_number2(order.clone(), Value::Str("cumQty".to_string()), Value::Str("cumQtyRq".to_string()), &[]);
let mut remaining: Value = self.safe_number2(order.clone(), Value::Str("leavesQty".to_string()), Value::Str("leavesQtyRq".to_string()), &[]);
let mut timestamp: Value = self.safe_integer_product(order.clone(), Value::Str("actionTimeNs".to_string()), Value::Float(0.000001), &[]);
if is_equal(×tamp, &Value::Null) {
timestamp = self.safe_integer_k(order.clone(), "createdAt", &[]);
}
let mut cost: Value = self.safe_number2(order.clone(), Value::Str("cumValue".to_string()), Value::Str("cumValueRv".to_string()), &[]);
let mut lastTradeTimestamp: Value = self.safe_integer_product(order.clone(), Value::Str("transactTimeNs".to_string()), Value::Float(0.000001), &[]);
if is_equal(&lastTradeTimestamp, &Value::Int(0)) {
lastTradeTimestamp = Value::Null;
}
let mut timeInForce: Value = self.parse_time_in_force(self.safe_string_k(order.clone(), "timeInForce", &[]));
let mut triggerPrice: Value = self.omit_zero(self.safe_string2(order.clone(), Value::Str("stopPx".to_string()), Value::Str("stopPxRp".to_string()), &[]));
let mut postOnly: Value = Value::Bool(is_equal(&timeInForce, &Value::Str("PO".to_string())));
let mut reduceOnly: Value = self.safe_value_k(order.clone(), "reduceOnly", &[]);
let mut execInst: Value = self.safe_string_k(order.clone(), "execInst", &[]);
if is_equal(&execInst, &Value::Str("ReduceOnly".to_string())) {
reduceOnly = Value::Bool(true);
}
let mut takeProfit: Value = self.safe_string_k(order.clone(), "takeProfitRp", &[]);
let mut stopLoss: Value = self.safe_string_k(order.clone(), "stopLossRp", &[]);
let mut feeValue: Value = self.omit_zero(self.safe_string_k(order.clone(), "execFeeRv", &[]));
let mut ptFeeRv: Value = self.omit_zero(self.safe_string_k(order.clone(), "ptFeeRv", &[]));
let mut fee: Value = Value::Null;
if !is_equal(&feeValue, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeValue.clone());
m.insert("currency".to_string(), get_value(&market, &Value::Str("quote".to_string())));
m
});
} else if !is_equal(&ptFeeRv, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), ptFeeRv.clone());
m.insert("currency".to_string(), Value::Str("PT".to_string()));
m
});
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), id.clone());
m.insert("clientOrderId".to_string(), clientOrderId.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("postOnly".to_string(), postOnly.clone());
m.insert("reduceOnly".to_string(), reduceOnly.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("triggerPrice".to_string(), triggerPrice.clone());
m.insert("takeProfitPrice".to_string(), takeProfit.clone());
m.insert("stopLossPrice".to_string(), stopLoss.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), remaining.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("average".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut isSwap: Value = self.safe_bool_k(market.clone(), "swap", &[Value::Bool(false)]);
let mut hasPnl: bool = is_true(&(Value::Bool(in_op(&order, &Value::Str("closedPnl".to_string()))))) || is_true(&(Value::Bool(in_op(&order, &Value::Str("closedPnlRv".to_string()))))) || is_true(&(Value::Bool(in_op(&order, &Value::Str("totalPnlRv".to_string())))));
if is_true(&(is_equal(&isSwap, &Value::Bool(true)))) || is_true(&hasPnl) {
return self.parse_swap_order(order.clone(), &[market.clone()]);
}
return self.parse_spot_order(order.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#createOrder
* @description create a trade order
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#place-order
* @see https://phemex-docs.github.io/#place-order-http-put-prefered-3
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.trigger] trigger price for conditional orders
* @param {object} [params.takeProfit] *swap only* *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered (perpetual swap markets only)
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *swap only* *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered (perpetual swap markets only)
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {string} [params.posSide] *swap only* "Merged" for one way mode, "Long" for buy side of hedged mode, "Short" for sell side of hedged mode
* @param {bool} [params.hedged] *swap only* true for hedged mode, false for one way mode, default is false
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut requestSide: Value = self.capitalize(side.clone());
type_var = self.capitalize(type_var.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("side".to_string(), requestSide.clone());
m.insert("ordType".to_string(), type_var.clone());
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string()), &[]);
let mut stopLoss: Value = self.safe_value_k(params.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_value_k(params.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = !is_equal(&stopLoss, &Value::Null);
let mut hasTakeProfit: bool = !is_equal(&takeProfit, &Value::Null);
let mut isStableSettled: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())))) || is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()))));
if is_equal(&clientOrderId, &Value::Null) {
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("CCXT123456".to_string())]);
if !is_equal(&brokerId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), add(&brokerId, &self.uuid16(&[])));
}
} else {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), clientOrderId.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string())]), &[]);
}
let mut triggerPrice: Value = self.safe_string_n(params.clone(), Value::List(vec![Value::Str("stopPx".to_string()), Value::Str("stopPrice".to_string()), Value::Str("triggerPrice".to_string())]), &[]);
if !is_equal(&triggerPrice, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("stopPxRp".to_string()), self.price_to_precision(symbol.clone(), triggerPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("stopPxEp".to_string()), self.to_ep(triggerPrice.clone(), &[market.clone()]));
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("stopPx".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stopLoss".to_string()), Value::Str("takeProfit".to_string()), Value::Str("triggerPrice".to_string())]), &[]);
if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
let mut qtyType: Value = self.safe_value_k(params.clone(), "qtyType", &[Value::Str("ByBase".to_string())]);
if is_true(&(is_equal(&type_var, &Value::Str("Market".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("Stop".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("MarketIfTouched".to_string())))) {
if !is_equal(&price, &Value::Null) {
qtyType = Value::Str("ByQuote".to_string());
}
}
if !is_equal(&triggerPrice, &Value::Null) {
if is_equal(&type_var, &Value::Str("Limit".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), Value::Str("StopLimit".to_string()));
} else if is_equal(&type_var, &Value::Str("Market".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), Value::Str("Stop".to_string()));
}
add_element_to_object(&mut request, &Value::Str("trigger".to_string()), Value::Str("ByLastPrice".to_string()));
}
add_element_to_object(&mut request, &Value::Str("qtyType".to_string()), qtyType.clone());
if is_equal(&qtyType, &Value::Str("ByQuote".to_string())) {
let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
params = self.omit(params.clone(), Value::Str("cost".to_string()), &[]);
if is_equal(&get_value(&self.options, &Value::Str("createOrderByQuoteRequiresPrice".to_string())), &Value::Bool(true)) {
if !is_equal(&price, &Value::Null) {
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price.clone());
let mut quoteAmount: Value = crate::precise::Precise::stringMul(&amountString, &priceString);
cost = self.parse_number(quoteAmount.clone(), &[]);
} else if is_equal(&cost, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" createOrder() ".to_string())), &qtyType), &Value::Str(" requires a price argument or a cost parameter".to_string()))));
}
}
cost = ternary(is_true(&(is_equal(&cost, &Value::Null))), amount.clone(), cost.clone());
let mut costString: Value = self.cost_to_precision(symbol.clone(), cost.clone());
add_element_to_object(&mut request, &Value::Str("quoteQtyEv".to_string()), self.to_ev(costString.clone(), &[market.clone()]));
} else {
let mut amountString: Value = self.amount_to_precision(symbol.clone(), amount.clone());
add_element_to_object(&mut request, &Value::Str("baseQtyEv".to_string()), self.to_ev(amountString.clone(), &[market.clone()]));
}
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let mut hedged: Value = self.safe_bool_k(params.clone(), "hedged", &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::Str("hedged".to_string()), &[]);
let mut posSide: Value = self.safe_string_lower(params.clone(), Value::Str("posSide".to_string()), &[]);
if is_equal(&posSide, &Value::Null) {
if is_equal(&hedged, &Value::Bool(true)) {
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[]);
if is_equal(&reduceOnly, &Value::Bool(true)) {
side = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("sell".to_string()), Value::Str("buy".to_string()));
params = self.omit(params.clone(), Value::Str("reduceOnly".to_string()), &[]);
}
posSide = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("Long".to_string()), Value::Str("Short".to_string()));
} else {
posSide = Value::Str("Merged".to_string());
}
}
posSide = self.capitalize(posSide.clone());
add_element_to_object(&mut request, &Value::Str("posSide".to_string()), posSide.clone());
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("orderQtyRq".to_string()), self.amount_to_precision(symbol.clone(), amount.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("orderQty".to_string()), self.parse_to_int(self.amount_to_precision(symbol.clone(), amount.clone())));
}
if !is_equal(&triggerPrice, &Value::Null) {
let mut triggerType: Value = self.safe_string_k(params.clone(), "triggerType", &[Value::Str("ByMarkPrice".to_string())]);
add_element_to_object(&mut request, &Value::Str("triggerType".to_string()), triggerType.clone());
// set direction & exchange specific order type
let mut triggerDirection: Value = Value::Null;
{ let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("triggerDirection".to_string()), &[]); triggerDirection = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&triggerDirection, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createOrder() also requires a 'triggerDirection' parameter with either 'ascending' or 'descending' value".to_string()))));
}
// the flow defined per https://phemex-docs.github.io/#more-order-type-examples
if is_equal(&triggerDirection, &Value::Str("ascending".to_string())) || is_equal(&triggerDirection, &Value::Str("up".to_string())) {
if is_equal(&side, &Value::Str("sell".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), ternary(is_true(&(is_equal(&type_var, &Value::Str("Market".to_string())))), Value::Str("MarketIfTouched".to_string()), Value::Str("LimitIfTouched".to_string())));
} else if is_equal(&side, &Value::Str("buy".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), ternary(is_true(&(is_equal(&type_var, &Value::Str("Market".to_string())))), Value::Str("Stop".to_string()), Value::Str("StopLimit".to_string())));
}
} else if is_equal(&triggerDirection, &Value::Str("descending".to_string())) || is_equal(&triggerDirection, &Value::Str("down".to_string())) {
if is_equal(&side, &Value::Str("sell".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), ternary(is_true(&(is_equal(&type_var, &Value::Str("Market".to_string())))), Value::Str("Stop".to_string()), Value::Str("StopLimit".to_string())));
} else if is_equal(&side, &Value::Str("buy".to_string())) {
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), ternary(is_true(&(is_equal(&type_var, &Value::Str("Market".to_string())))), Value::Str("MarketIfTouched".to_string()), Value::Str("LimitIfTouched".to_string())));
}
}
}
if is_true(&hasStopLoss) || is_true(&hasTakeProfit) {
if is_true(&hasStopLoss) {
let mut stopLossTriggerPrice: Value = self.safe_value2(stopLoss.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
if is_equal(&stopLossTriggerPrice, &Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &Value::Str(" createOrder() requires a trigger price in params[\"stopLoss\"][\"triggerPrice\"] for a stop loss order".to_string()))));
}
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("stopLossRp".to_string()), self.price_to_precision(symbol.clone(), stopLossTriggerPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("stopLossEp".to_string()), self.to_ep(stopLossTriggerPrice.clone(), &[market.clone()]));
}
let mut stopLossTriggerPriceType: Value = self.safe_string2(stopLoss.clone(), Value::Str("triggerPriceType".to_string()), Value::Str("slTrigger".to_string()), &[]);
if !is_equal(&stopLossTriggerPriceType, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("slTrigger".to_string()), self.safe_string(get_value(&self.options, &Value::Str("triggerPriceTypesMap".to_string())), stopLossTriggerPriceType.clone(), &[stopLossTriggerPriceType.clone()]));
}
let mut slLimitPrice: Value = self.safe_string_k(stopLoss.clone(), "price", &[]);
if !is_equal(&slLimitPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("slPxRp".to_string()), self.price_to_precision(symbol.clone(), slLimitPrice.clone()));
}
}
if is_true(&hasTakeProfit) {
let mut takeProfitTriggerPrice: Value = self.safe_value2(takeProfit.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
if is_equal(&takeProfitTriggerPrice, &Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &Value::Str(" createOrder() requires a trigger price in params[\"takeProfit\"][\"triggerPrice\"] for a take profit order".to_string()))));
}
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("takeProfitRp".to_string()), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("takeProfitEp".to_string()), self.to_ep(takeProfitTriggerPrice.clone(), &[market.clone()]));
}
let mut takeProfitTriggerPriceType: Value = self.safe_string2(takeProfit.clone(), Value::Str("triggerPriceType".to_string()), Value::Str("tpTrigger".to_string()), &[]);
if !is_equal(&takeProfitTriggerPriceType, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("tpTrigger".to_string()), self.safe_string(get_value(&self.options, &Value::Str("triggerPriceTypesMap".to_string())), takeProfitTriggerPriceType.clone(), &[takeProfitTriggerPriceType.clone()]));
}
let mut tpLimitPrice: Value = self.safe_string_k(takeProfit.clone(), "price", &[]);
if !is_equal(&tpLimitPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("tpPxRp".to_string()), self.price_to_precision(symbol.clone(), tpLimitPrice.clone()));
}
}
}
}
if is_true(&(is_equal(&type_var, &Value::Str("Limit".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("StopLimit".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("LimitIfTouched".to_string())))) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("priceRp".to_string()), self.price_to_precision(symbol.clone(), price.clone()));
} else {
let mut priceString: Value = self.number_to_string(price.clone());
add_element_to_object(&mut request, &Value::Str("priceEp".to_string()), self.to_ep(priceString.clone(), &[market.clone()]));
}
}
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
if !is_equal(&takeProfitPrice, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("takeProfitRp".to_string()), self.price_to_precision(symbol.clone(), takeProfitPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("takeProfitEp".to_string()), self.to_ep(takeProfitPrice.clone(), &[market.clone()]));
}
params = self.omit(params.clone(), Value::Str("takeProfitPrice".to_string()), &[]);
}
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[]);
if !is_equal(&stopLossPrice, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("stopLossRp".to_string()), self.price_to_precision(symbol.clone(), stopLossPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("stopLossEp".to_string()), self.to_ep(stopLossPrice.clone(), &[market.clone()]));
}
params = self.omit(params.clone(), Value::Str("stopLossPrice".to_string()), &[]);
}
let mut response: Value = Value::Null;
if is_true(&isStableSettled) {
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
response = self.private_post_g_orders(&[__ws_arg_15]).await;
} else if is_equal(&get_value(&market, &Value::Str("contract".to_string())), &Value::Bool(true)) {
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
response = self.private_post_orders(&[__ws_arg_16]).await;
} else {
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
response = self.private_post_spot_orders(&[__ws_arg_17]).await;
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orderID": "d1d09454-cabc-4a23-89a7-59d43363f16d",
// "clOrdID": "309bcd5c-9f6e-4a68-b775-4494542eb5cb",
// "priceEp": 0,
// "action": "New",
// "trigger": "UNSPECIFIED",
// "pegPriceType": "UNSPECIFIED",
// "stopDirection": "UNSPECIFIED",
// "bizError": 0,
// "symbol": "sBTCUSDT",
// "side": "Buy",
// "baseQtyEv": 0,
// "ordType": "Limit",
// "timeInForce": "GoodTillCancel",
// "ordStatus": "Created",
// "cumFeeEv": 0,
// "cumBaseQtyEv": 0,
// "cumQuoteQtyEv": 0,
// "leavesBaseQtyEv": 0,
// "leavesQuoteQtyEv": 0,
// "avgPriceEp": 0,
// "cumBaseAmountEv": 0,
// "cumQuoteAmountEv": 0,
// "quoteQtyEv": 0,
// "qtyType": "ByBase",
// "stopPxEp": 0,
// "pegOffsetValueEp": 0
// }
// }
//
// swap
//
// {
// "code":0,
// "msg":"",
// "data":{
// "bizError":0,
// "orderID":"7a1ad384-44a3-4e54-a102-de4195a29e32",
// "clOrdID":"",
// "symbol":"ETHUSD",
// "side":"Buy",
// "actionTimeNs":1592668973945065381,
// "transactTimeNs":0,
// "orderType":"Market",
// "priceEp":2267500,
// "price":226.75000000,
// "orderQty":1,
// "displayQty":0,
// "timeInForce":"ImmediateOrCancel",
// "reduceOnly":false,
// "closedPnlEv":0,
// "closedPnl":0E-8,
// "closedSize":0,
// "cumQty":0,
// "cumValueEv":0,
// "cumValue":0E-8,
// "leavesQty":1,
// "leavesValueEv":11337,
// "leavesValue":1.13370000,
// "stopDirection":"UNSPECIFIED",
// "stopPxEp":0,
// "stopPx":0E-8,
// "trigger":"UNSPECIFIED",
// "pegOffsetValueEp":0,
// "execStatus":"PendingNew",
// "pegPriceType":"UNSPECIFIED",
// "ordStatus":"Created"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#editOrder
* @description edit a trade order
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#amend-order-by-orderid
* @param {string} id cancel order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.posSide] either 'Merged' or 'Long' or 'Short'
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string())]), &[]);
let mut isStableSettled: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())))) || is_true(&(is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()))));
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), clientOrderId.clone());
} else {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), id.clone());
}
if !is_equal(&price, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("priceRp".to_string()), self.price_to_precision(get_value(&market, &Value::Str("symbol".to_string())), price.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("priceEp".to_string()), self.to_ep(price.clone(), &[market.clone()]));
}
}
// Note the uppercase 'V' in 'baseQtyEV' request. that is exchange's requirement at this moment. However, to avoid mistakes from user side, let's support lowercased 'baseQtyEv' too
let mut finalQty: Value = self.safe_string_k(params.clone(), "baseQtyEv", &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("baseQtyEv".to_string())]), &[]);
if !is_equal(&finalQty, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("baseQtyEV".to_string()), finalQty.clone());
} else if !is_equal(&amount, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("orderQtyRq".to_string()), self.amount_to_precision(get_value(&market, &Value::Str("symbol".to_string())), amount.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("baseQtyEV".to_string()), self.to_ev(amount.clone(), &[market.clone()]));
}
}
let mut triggerPrice: Value = self.safe_string_n(params.clone(), Value::List(vec![Value::Str("triggerPrice".to_string()), Value::Str("stopPx".to_string()), Value::Str("stopPrice".to_string())]), &[]);
if !is_equal(&triggerPrice, &Value::Null) {
if is_true(&isStableSettled) {
add_element_to_object(&mut request, &Value::Str("stopPxRp".to_string()), self.price_to_precision(symbol.clone(), triggerPrice.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("stopPxEp".to_string()), self.to_ep(triggerPrice.clone(), &[market.clone()]));
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("triggerPrice".to_string()), Value::Str("stopPx".to_string()), Value::Str("stopPrice".to_string())]), &[]);
let mut response: Value = Value::Null;
if is_true(&isStableSettled) {
let mut posSide: Value = self.safe_string_k(params.clone(), "posSide", &[]);
if is_equal(&posSide, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("posSide".to_string()), Value::Str("Merged".to_string()));
}
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
response = self.private_put_g_orders_replace(&[__ws_arg_18]).await;
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
response = self.private_put_orders_replace(&[__ws_arg_19]).await;
} else {
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
response = self.private_put_spot_orders(&[__ws_arg_20]).await;
}
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#cancelOrder
* @description cancels an open order
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#cancel-single-order-by-orderid
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.posSide] either 'Merged' or 'Long' or 'Short'
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrder() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string())]), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), clientOrderId.clone());
} else {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), id.clone());
}
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
let mut posSide: Value = self.safe_string_k(params.clone(), "posSide", &[]);
if is_equal(&posSide, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("posSide".to_string()), Value::Str("Merged".to_string()));
}
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_g_orders_cancel(&[__ws_arg_21]).await;
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let __ws_arg_22 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_orders_cancel(&[__ws_arg_22]).await;
} else {
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_spot_orders(&[__ws_arg_23]).await;
}
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#cancelAllOrders
* @description cancel all open orders in a market
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#cancelall
* @param {string} symbol unified market symbol of the market to cancel orders in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelAllOrders() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut trigger: Value = self.safe_value2(params.clone(), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if is_equal(&trigger, &Value::Bool(true)) {
add_element_to_object(&mut request, &Value::Str("untriggerred".to_string()), trigger.clone());
}
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
let __ws_arg_24 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_g_orders_all(&[__ws_arg_24]).await;
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let __ws_arg_25 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_orders_all(&[__ws_arg_25]).await;
} else {
let __ws_arg_26 = self.extend(request.clone(), &[params.clone()]);
response = self.private_delete_spot_orders_all(&[__ws_arg_26]).await;
}
return Value::List(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
}), &[])]);
Value::Null
}
/*
* @method
* @name phemex#fetchOrder
* @see https://phemex-docs.github.io/#query-orders-by-ids
* @description fetches information on an order made by the user
* @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]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOrder() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string()), Value::Str("clOrdID".to_string())]), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), clientOrderId.clone());
} else {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), id.clone());
}
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
let __ws_arg_27 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_api_data_g_futures_orders_by_order_id(&[__ws_arg_27]).await;
} else if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
let __ws_arg_28 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_api_data_spots_orders_by_order_id(&[__ws_arg_28]).await;
} else {
let __ws_arg_29 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order(&[__ws_arg_29]).await;
}
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = data.clone();
if is_true(&Value::Bool(is_array(&data))) {
let mut numOrders: Value = get_array_length(&data);
if is_less_than(&numOrders, &Value::Int(1)) {
if !is_equal(&clientOrderId, &Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&add(&add(&add(&self.id, &Value::Str(" fetchOrder() ".to_string())), &symbol), &Value::Str(" order with clientOrderId ".to_string())), &clientOrderId), &Value::Str(" not found".to_string()))));
} else {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&add(&add(&add(&self.id, &Value::Str(" fetchOrder() ".to_string())), &symbol), &Value::Str(" order with id ".to_string())), &id), &Value::Str(" not found".to_string()))));
}
}
order = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
order = self.safe_dict(rows.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
return self.parse_order(order.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorder
* @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]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOrders() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(&market, &Value::Str("settle".to_string())));
let __ws_arg_30 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_v2_order_list(&[__ws_arg_30]).await;
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let __ws_arg_31 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_list(&[__ws_arg_31]).await;
} else {
let __ws_arg_32 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_api_data_spots_orders(&[__ws_arg_32]).await;
}
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[data.clone()]);
return self.parse_orders(rows.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryopenorder
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotListAllOpenOrder
* @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]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchOpenOrders() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
let __ws_arg_33 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_orders_active_list(&[__ws_arg_33]).await;
} else if is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
let __ws_arg_34 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_orders_active_list(&[__ws_arg_34]).await;
} else {
let __ws_arg_35 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_spot_orders(&[__ws_arg_35]).await;
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if is_true(&is_instance(&e, &Value::Str("OrderNotFound".to_string()))) {
return Value::List(vec![]);
}
panic!("{}", e);
}
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_true(&Value::Bool(is_array(&data))) {
return self.parse_orders(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
} else {
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
return self.parse_orders(rows.clone(), &[market.clone(), since.clone(), limit.clone()]);
}
Value::Null
}
/*
* @method
* @name phemex#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#queryorder
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#queryorder
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedgedd-Perpetual-API.md#query-closed-orders-by-symbol
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotDataOrdersByIds
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.settle] the settlement currency to fetch orders for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&market, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut response: Value = Value::Null;
if is_true(&(is_equal(&symbol, &Value::Null))) || is_true(&(is_equal(&self.safe_string_k(market.clone(), "settle", &[]), &Value::Str("USDT".to_string())))) {
add_element_to_object(&mut request, &Value::Str("currency".to_string()), self.safe_string_k(params.clone(), "settle", &[Value::Str("USDT".to_string())]));
let __ws_arg_36 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_v2_order_list(&[__ws_arg_36]).await;
} else if !is_equal(&market, &Value::Null) && is_true(&(is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))) {
let __ws_arg_37 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_list(&[__ws_arg_37]).await;
} else {
let __ws_arg_38 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_spot_order(&[__ws_arg_38]).await;
}
//
// spot
//
// {
// "code":0,
// "msg":"OK",
// "data":{
// "total":8,
// "rows":[
// {
// "orderID":"99232c3e-3d6a-455f-98cc-2061cdfe91bc",
// "stopPxEp":0,
// "avgPriceEp":0,
// "qtyType":"ByBase",
// "leavesBaseQtyEv":0,
// "leavesQuoteQtyEv":0,
// "baseQtyEv":"1000000000",
// "feeCurrency":"4",
// "stopDirection":"UNSPECIFIED",
// "symbol":"sETHUSDT",
// "side":"Buy",
// "quoteQtyEv":250000000000,
// "priceEp":25000000000,
// "ordType":"Limit",
// "timeInForce":"GoodTillCancel",
// "ordStatus":"Rejected",
// "execStatus":"NewRejected",
// "createTimeNs":1592675305266037130,
// "cumFeeEv":0,
// "cumBaseValueEv":0,
// "cumQuoteValueEv":0
// },
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_true(&Value::Bool(is_array(&data))) {
return self.parse_orders(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
} else {
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
return self.parse_orders(rows.clone(), &[market.clone(), since.clone(), limit.clone()]);
}
Value::Null
}
/*
* @method
* @name phemex#fetchMyTrades
* @description fetch all trades made by the user
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-user-trade
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-user-trade
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Spot-API-en.md#spotDataTradesHist
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchMyTrades".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&limit, &Value::Null) {
limit = crate::runtime::Math::min(&Value::Int(200), &limit);
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut isUSDTSettled: bool = is_true(&(!is_equal(&type_var, &Value::Str("spot".to_string())))) && is_true(&(is_true(&(is_equal(&symbol, &Value::Null))) || is_true(&(is_equal(&self.safe_string_k(market.clone(), "settle", &[]), &Value::Str("USDT".to_string()))))));
if is_true(&isUSDTSettled) {
add_element_to_object(&mut request, &Value::Str("currency".to_string()), Value::Str("USDT".to_string()));
add_element_to_object(&mut request, &Value::Str("offset".to_string()), Value::Int(0));
if is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), Value::Int(200));
}
} else if !is_equal(&symbol, &Value::Null) && !is_equal(&market, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), since.clone());
}
let mut response: Value = Value::Null;
if is_true(&isUSDTSettled) {
let __ws_arg_39 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_v2_trading_list(&[__ws_arg_39]).await;
} else if is_equal(&type_var, &Value::Str("swap".to_string())) {
add_element_to_object(&mut request, &Value::Str("tradeType".to_string()), Value::Str("Trade".to_string()));
let __ws_arg_40 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_order_trade(&[__ws_arg_40]).await;
} else {
let __ws_arg_41 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_exchange_spot_order_trades(&[__ws_arg_41]).await;
}
//
// spot
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "total": 1,
// "rows": [
// {
// "qtyType": "ByQuote",
// "transactTimeNs": 1589450974800550100,
// "clOrdID": "8ba59d40-df25-d4b0-14cf-0703f44e9690",
// "orderID": "b2b7018d-f02f-4c59-b4cf-051b9c2d2e83",
// "symbol": "sBTCUSDT",
// "side": "Buy",
// "priceEP": 970056000000,
// "baseQtyEv": 0,
// "quoteQtyEv": 1000000000,
// "action": "New",
// "execStatus": "MakerFill",
// "ordStatus": "Filled",
// "ordType": "Limit",
// "execInst": "None",
// "timeInForce": "GoodTillCancel",
// "stopDirection": "UNSPECIFIED",
// "tradeType": "Trade",
// "stopPxEp": 0,
// "execId": "c6bd8979-07ba-5946-b07e-f8b65135dbb1",
// "execPriceEp": 970056000000,
// "execBaseQtyEv": 103000,
// "execQuoteQtyEv": 999157680,
// "leavesBaseQtyEv": 0,
// "leavesQuoteQtyEv": 0,
// "execFeeEv": 0,
// "feeRateEr": 0
// }
// ]
// }
// }
//
//
// swap
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "total": 79,
// "rows": [
// {
// "transactTimeNs": 1606054879331565300,
// "symbol": "BTCUSD",
// "currency": "BTC",
// "action": "New",
// "side": "Buy",
// "tradeType": "Trade",
// "execQty": 5,
// "execPriceEp": 182990000,
// "orderQty": 5,
// "priceEp": 183870000,
// "execValueEv": 27323,
// "feeRateEr": 75000,
// "execFeeEv": 21,
// "ordType": "Market",
// "execID": "5eee56a4-04a9-5677-8eb0-c2fe22ae3645",
// "orderID": "ee0acb82-f712-4543-a11d-d23efca73197",
// "clOrdID": "",
// "execStatus": "TakerFill"
// },
// ]
// }
// }
//
// swap - usdt
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "total": 4,
// "rows": [
// {
// "createdAt": 1666226932259,
// "symbol": "ETHUSDT",
// "currency": "USDT",
// "action": 1,
// "tradeType": 1,
// "execQtyRq": "0.01",
// "execPriceRp": "1271.9",
// "side": 1,
// "orderQtyRq": "0.78",
// "priceRp": "1271.9",
// "execValueRv": "12.719",
// "feeRateRr": "0.0001",
// "execFeeRv": "0.0012719",
// "ordType": 2,
// "execId": "8718cae",
// "execStatus": 6
// },
// ]
// }
// }
//
let mut data: Value = Value::Null;
if is_true(&isUSDTSettled) {
data = self.safe_value_k(response.clone(), "data", &[Value::List(vec![])]);
} else {
data = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
data = self.safe_value_k(data.clone(), "rows", &[Value::List(vec![])]);
}
return self.parse_trades(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] the chain name to fetch the deposit address e.g. ETH, TRX, EOS, SOL, etc.
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
let mut defaultNetworks: Value = self.safe_dict_k(self.options.clone(), "defaultNetworks", &[]);
let mut defaultNetwork: Value = self.safe_string_upper(defaultNetworks.clone(), code.clone(), &[]);
let mut networks: Value = self.safe_dict_k(self.options.clone(), "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut network: Value = self.safe_string_upper2(params.clone(), Value::Str("network".to_string()), Value::Str("chainName".to_string()), &[defaultNetwork.clone()]);
network = self.safe_string(networks.clone(), network.clone(), &[network.clone()]);
if is_equal(&network, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchDepositAddress() requires a network parameter".to_string()))));
} else {
add_element_to_object(&mut request, &Value::Str("chainName".to_string()), network.clone());
params = self.omit(params.clone(), Value::Str("network".to_string()), &[]);
}
let __ws_arg_42 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_exchange_wallets_v2_deposit_address(&[__ws_arg_42]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "address": "tb1qxel5wq5gumt",
// "tag": "",
// "notice": false,
// "accountType": 1,
// "contractName": null,
// "chainTokenUrl": null,
// "sign": null
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut address: Value = self.safe_string_k(data.clone(), "address", &[]);
let mut tag: Value = self.safe_string_k(data.clone(), "tag", &[]);
self.check_address(&[address.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("currency".to_string(), code.clone());
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), address.clone());
m.insert("tag".to_string(), tag.clone());
m
});
Value::Null
}
/*
* @method
* @name phemex#fetchDeposits
* @description fetch all deposits made to an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
}
let mut response: Value = self.private_get_exchange_wallets_deposit_list(&[params.clone()]).await;
//
// {
// "code":0,
// "msg":"OK",
// "data":[
// {
// "id":29200,
// "currency":"USDT",
// "currencyCode":3,
// "txHash":"0x0bdbdc47807769a03b158d5753f54dfc58b92993d2f5e818db21863e01238e5d",
// "address":"0x5bfbf60e0fa7f63598e6cfd8a7fd3ffac4ccc6ad",
// "amountEv":3000000000,
// "confirmations":13,
// "type":"Deposit",
// "status":"Success",
// "createdAt":1592722565000
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_transactions(data.clone(), &[currency.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
}
let mut response: Value = self.private_get_exchange_wallets_withdraw_list(&[params.clone()]).await;
//
// {
// "code":0,
// "msg":"OK",
// "data":[
// {
// "address": "1Lxxxxxxxxxxx"
// "amountEv": 200000
// "currency": "BTC"
// "currencyCode": 1
// "expiredTime": 0
// "feeEv": 50000
// "rejectReason": null
// "status": "Succeed"
// "txHash": "44exxxxxxxxxxxxxxxxxxxxxx"
// "withdrawStatus: ""
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_transactions(data.clone(), &[currency.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Success".to_string(), Value::Str("ok".to_string()));
m.insert("Succeed".to_string(), Value::Str("ok".to_string()));
m.insert("Rejected".to_string(), Value::Str("failed".to_string()));
m.insert("Security check failed".to_string(), Value::Str("failed".to_string()));
m.insert("SecurityCheckFailed".to_string(), Value::Str("failed".to_string()));
m.insert("Expired".to_string(), Value::Str("failed".to_string()));
m.insert("Address Risk".to_string(), Value::Str("failed".to_string()));
m.insert("Security Checking".to_string(), Value::Str("pending".to_string()));
m.insert("SecurityChecking".to_string(), Value::Str("pending".to_string()));
m.insert("Pending Review".to_string(), Value::Str("pending".to_string()));
m.insert("Pending Transfer".to_string(), Value::Str("pending".to_string()));
m.insert("AmlCsApporve".to_string(), Value::Str("pending".to_string()));
m.insert("New".to_string(), Value::Str("pending".to_string()));
m.insert("Confirmed".to_string(), Value::Str("pending".to_string()));
m.insert("Cancelled".to_string(), Value::Str("canceled".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// withdraw
//
// {
// "id": "10000001",
// "freezeId": null,
// "address": "44exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
// "amountRv": "100",
// "chainCode": "11",
// "chainName": "TRX",
// "currency": "USDT",
// "currencyCode": 3,
// "email": "abc@gmail.com",
// "expiredTime": "0",
// "feeRv": "1",
// "nickName": null,
// "phone": null,
// "rejectReason": "",
// "submitedAt": "1670000000000",
// "submittedAt": "1670000000000",
// "txHash": null,
// "userId": "10000001",
// "status": "Success"
//
// fetchDeposits
//
// {
// "id": "29200",
// "currency": "USDT",
// "currencyCode": "3",
// "chainName": "ETH",
// "chainCode": "4",
// "txHash": "0x0bdbdc47807769a03b158d5753f54dfc58b92993d2f5e818db21863e01238e5d",
// "address": "0x5bfbf60e0fa7f63598e6cfd8a7fd3ffac4ccc6ad",
// "amountEv": "3000000000",
// "confirmations": "13",
// "type": "Deposit",
// "status": "Success",
// "createdAt": "1592722565000",
// }
//
// fetchWithdrawals
//
// {
// "id": "10000001",
// "userId": "10000001",
// "freezeId": "10000002",
// "phone": null,
// "email": "abc@gmail.com",
// "nickName": null,
// "currency": "USDT",
// "currencyCode": "3",
// "status": "Succeed",
// "withdrawStatus": "Succeed",
// "amountEv": "8800000000",
// "feeEv": "1200000000",
// "address": "0x5xxxad",
// "txHash: "0x0xxxx5d",
// "submitedAt": "1702571922000",
// "submittedAt": "1702571922000",
// "expiredTime": "0",
// "rejectReason": null,
// "chainName": "ETH",
// "chainCode": "4",
// "proxyAddress": null
// }
//
let mut id: Value = self.safe_string_k(transaction.clone(), "id", &[]);
let mut address: Value = self.safe_string_k(transaction.clone(), "address", &[]);
let mut tag: Value = Value::Null;
let mut txid: Value = self.safe_string_k(transaction.clone(), "txHash", &[]);
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "currency", &[]);
currency = self.safe_currency(currencyId.clone(), &[currency.clone()]);
let mut code: Value = get_value(¤cy, &Value::Str("code".to_string()));
let mut networkId: Value = self.safe_string_k(transaction.clone(), "chainName", &[]);
let mut timestamp: Value = self.safe_integer_n(transaction.clone(), Value::List(vec![Value::Str("createdAt".to_string()), Value::Str("submitedAt".to_string()), Value::Str("submittedAt".to_string())]), &[]);
let mut type_var: Value = self.safe_string_lower(transaction.clone(), Value::Str("type".to_string()), &[]);
let mut feeCost: Value = self.parse_number(self.from_en(self.safe_string_k(transaction.clone(), "feeEv", &[]), self.safe_value_k(currency.clone(), "valueScale", &[])), &[]);
if is_equal(&feeCost, &Value::Null) {
feeCost = self.safe_number_k(transaction.clone(), "feeRv", &[]);
}
let mut fee: Value = Value::Null;
if !is_equal(&feeCost, &Value::Null) {
type_var = Value::Str("withdrawal".to_string());
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), code.clone());
m
});
}
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
let mut amount: Value = self.parse_number(self.from_en(self.safe_string_k(transaction.clone(), "amountEv", &[]), self.safe_value_k(currency.clone(), "valueScale", &[])), &[]);
if is_equal(&amount, &Value::Null) {
amount = self.safe_number_k(transaction.clone(), "amountRv", &[]);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), id.clone());
m.insert("txid".to_string(), txid.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("network".to_string(), self.network_id_to_code(&[networkId.clone(), code.clone()]));
m.insert("address".to_string(), address.clone());
m.insert("addressTo".to_string(), address.clone());
m.insert("addressFrom".to_string(), Value::Null);
m.insert("tag".to_string(), tag.clone());
m.insert("tagTo".to_string(), tag.clone());
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), type_var.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("currency".to_string(), code.clone());
m.insert("status".to_string(), status.clone());
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m.insert("fee".to_string(), fee.clone());
m
});
Value::Null
}
/*
* @method
* @name phemex#fetchPositions
* @description fetch all open positions
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#query-trading-account-and-positions
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#query-account-positions
* @see https://phemex-docs.github.io/#query-account-positions-with-unrealized-pnl
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.code] the currency code to fetch positions for, USD, BTC or USDT, USDT is the default
* @param {string} [params.method] *USDT contracts only* 'privateGetGAccountsAccountPositions' or 'privateGetGAccountsPositions' default is 'privateGetGAccountsAccountPositions'
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut subType: Value = Value::Null;
let mut code: Value = self.safe_string2(params.clone(), Value::Str("currency".to_string()), Value::Str("code".to_string()), &[Value::Str("USDT".to_string())]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("currency".to_string()), Value::Str("code".to_string())]), &[]);
let mut settle: Value = Value::Null;
let mut market: Value = Value::Null;
let mut firstSymbol: Value = self.safe_string(symbols.clone(), Value::Int(0), &[]);
if !is_equal(&firstSymbol, &Value::Null) {
market = self.market(firstSymbol.clone());
settle = get_value(&market, &Value::Str("settle".to_string()));
code = get_value(&market, &Value::Str("settle".to_string()));
} else {
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositions".to_string()), Value::Str("settle".to_string()), &[code.clone()]); settle = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
}
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("fetchPositions".to_string()), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isUSDTSettled: bool = is_equal(&settle, &Value::Str("USDT".to_string()));
if is_true(&isUSDTSettled) {
code = Value::Str("USDT".to_string());
} else if is_equal(&settle, &Value::Str("BTC".to_string())) {
code = Value::Str("BTC".to_string());
} else if is_equal(&code, &Value::Null) {
code = ternary(is_true(&(is_equal(&subType, &Value::Str("linear".to_string())))), Value::Str("USD".to_string()), Value::Str("BTC".to_string()));
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
if is_true(&isUSDTSettled) {
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositions".to_string()), Value::Str("method".to_string()), &[Value::Str("privateGetGAccountsAccountPositions".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&method, &Value::Str("privateGetGAccountsAccountPositions".to_string())) {
let __ws_arg_43 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_accounts_account_positions(&[__ws_arg_43]).await;
} else {
let __ws_arg_44 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_accounts_positions(&[__ws_arg_44]).await;
}
} else {
let __ws_arg_45 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_accounts_account_positions(&[__ws_arg_45]).await;
}
//
// {
// "code":0,"msg":"",
// "data":{
// "account":{
// "accountId":6192120001,
// "currency":"BTC",
// "accountBalanceEv":1254744,
// "totalUsedBalanceEv":0,
// "bonusBalanceEv":1254744
// },
// "positions":[
// {
// "accountID":6192120001,
// "symbol":"BTCUSD",
// "currency":"BTC",
// "side":"None",
// "positionStatus":"Normal",
// "crossMargin":false,
// "leverageEr":100000000,
// "leverage":1.00000000,
// "initMarginReqEr":100000000,
// "initMarginReq":1.00000000,
// "maintMarginReqEr":500000,
// "maintMarginReq":0.00500000,
// "riskLimitEv":10000000000,
// "riskLimit":100.00000000,
// "size":0,
// "value":0E-8,
// "valueEv":0,
// "avgEntryPriceEp":0,
// "avgEntryPrice":0E-8,
// "posCostEv":0,
// "posCost":0E-8,
// "assignedPosBalanceEv":0,
// "assignedPosBalance":0E-8,
// "bankruptCommEv":0,
// "bankruptComm":0E-8,
// "bankruptPriceEp":0,
// "bankruptPrice":0E-8,
// "positionMarginEv":0,
// "positionMargin":0E-8,
// "liquidationPriceEp":0,
// "liquidationPrice":0E-8,
// "deleveragePercentileEr":0,
// "deleveragePercentile":0E-8,
// "buyValueToCostEr":100225000,
// "buyValueToCost":1.00225000,
// "sellValueToCostEr":100075000,
// "sellValueToCost":1.00075000,
// "markPriceEp":135736070,
// "markPrice":13573.60700000,
// "markValueEv":0,
// "markValue":null,
// "unRealisedPosLossEv":0,
// "unRealisedPosLoss":null,
// "estimatedOrdLossEv":0,
// "estimatedOrdLoss":0E-8,
// "usedBalanceEv":0,
// "usedBalance":0E-8,
// "takeProfitEp":0,
// "takeProfit":null,
// "stopLossEp":0,
// "stopLoss":null,
// "cumClosedPnlEv":0,
// "cumFundingFeeEv":0,
// "cumTransactFeeEv":0,
// "realisedPnlEv":0,
// "realisedPnl":null,
// "cumRealisedPnlEv":0,
// "cumRealisedPnl":null
// }
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positions: Value = self.safe_value_k(data.clone(), "positions", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1049: bool = true;
while { if !__for_first_1049 { i = add(&i, &Value::Int(1)); } __for_first_1049 = false; is_less_than(&i, &get_array_length(&positions)) } {
let mut position: Value = get_value(&positions, &i);
let mut position: Value = get_value(&positions, &i);
append_to_array(&mut result, self.parse_position(position.clone(), &[]));
}
}
return self.filter_by_array_positions(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
Value::Null
}
/*
* @method
* @name phemex#fetchPositionHistory
* @description fetches historical positions
* @see https://phemex-docs.github.io/#query-closed-positions
* @param {string} symbol unified contract symbol
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum amount of records to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch positions for
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position_history(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
symbol = get_value(&market, &Value::Str("symbol".to_string()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), crate::runtime::Math::min(&Value::Int(200), &limit));
}
let __ws_arg_46 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_api_data_g_futures_closed_position(&[__ws_arg_46]).await;
//
// {
// "code": "0",
// "msg": "OK",
// "data": [
// {
// "symbol": "ETHUSDT",
// "currency": "USDT",
// "term": "0",
// "closedSizeRq": "0.09",
// "side": "1",
// "cumEntryValueRv": null,
// "closedPnlRv": "-0.1385",
// "exchangeFeeRv": "0.2561889",
// "fundingFeeRv": "0",
// "realizedPnlRv": "-0.3946889",
// "finished": "0",
// "openedTimeNs": "1777998771316",
// "updatedTimeNs": "1777998802592",
// "openPrice": "2372.88888889",
// "closePrice": "2371.35000000",
// "roi": "-0.09702738",
// "leverage": "-52.5"
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut positions: Value = self.parse_positions(data.clone(), &[Value::List(vec![symbol.clone()])]);
return self.filter_by_symbol_since_limit(positions.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "userID": "811370",
// "accountID": "8113700002",
// "symbol": "ETHUSD",
// "currency": "USD",
// "side": "Buy",
// "positionStatus": "Normal",
// "crossMargin": false,
// "leverageEr": "200000000",
// "leverage": "2.00000000",
// "initMarginReqEr": "50000000",
// "initMarginReq": "0.50000000",
// "maintMarginReqEr": "1000000",
// "maintMarginReq": "0.01000000",
// "riskLimitEv": "5000000000",
// "riskLimit": "500000.00000000",
// "size": "1",
// "value": "22.22370000",
// "valueEv": "222237",
// "avgEntryPriceEp": "44447400",
// "avgEntryPrice": "4444.74000000",
// "posCostEv": "111202",
// "posCost": "11.12020000",
// "assignedPosBalanceEv": "111202",
// "assignedPosBalance": "11.12020000",
// "bankruptCommEv": "84",
// "bankruptComm": "0.00840000",
// "bankruptPriceEp": "22224000",
// "bankruptPrice": "2222.40000000",
// "positionMarginEv": "111118",
// "positionMargin": "11.11180000",
// "liquidationPriceEp": "22669000",
// "liquidationPrice": "2266.90000000",
// "deleveragePercentileEr": "0",
// "deleveragePercentile": "0E-8",
// "buyValueToCostEr": "50112500",
// "buyValueToCost": "0.50112500",
// "sellValueToCostEr": "50187500",
// "sellValueToCost": "0.50187500",
// "markPriceEp": "31332499",
// "markPrice": "3133.24990000",
// "markValueEv": "0",
// "markValue": null,
// "unRealisedPosLossEv": "0",
// "unRealisedPosLoss": null,
// "estimatedOrdLossEv": "0",
// "estimatedOrdLoss": "0E-8",
// "usedBalanceEv": "111202",
// "usedBalance": "11.12020000",
// "takeProfitEp": "0",
// "takeProfit": null,
// "stopLossEp": "0",
// "stopLoss": null,
// "cumClosedPnlEv": "-1546",
// "cumFundingFeeEv": "1605",
// "cumTransactFeeEv": "8438",
// "realisedPnlEv": "0",
// "realisedPnl": null,
// "cumRealisedPnlEv": "0",
// "cumRealisedPnl": null,
// "transactTimeNs": "1641571200001885324",
// "takerFeeRateEr": "0",
// "makerFeeRateEr": "0",
// "term": "6",
// "lastTermEndTimeNs": "1607711882505745356",
// "lastFundingTimeNs": "1641571200000000000",
// "curTermRealisedPnlEv": "-1567",
// "execSeq": "12112761561"
// }
//
//
// fetchPositionsHistory
//
// {
// "symbol": "ETHUSDT",
// "currency": "USDT",
// "term": "0",
// "closedSizeRq": "0.09",
// "side": "1",
// "cumEntryValueRv": null,
// "closedPnlRv": "-0.1385",
// "exchangeFeeRv": "0.2561889",
// "fundingFeeRv": "0",
// "realizedPnlRv": "-0.3946889",
// "finished": "0",
// "openedTimeNs": "1777998771316",
// "updatedTimeNs": "1777998802592",
// "openPrice": "2372.88888889",
// "closePrice": "2371.35000000",
// "roi": "-0.09702738", // todo: check if percentage or not
// "leverage": "-52.5"
// },
//
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut collateral: Value = self.safe_string2(position.clone(), Value::Str("positionMargin".to_string()), Value::Str("positionMarginRv".to_string()), &[]);
let mut notionalString: Value = self.safe_string2(position.clone(), Value::Str("value".to_string()), Value::Str("valueRv".to_string()), &[]);
let mut maintenanceMarginPercentageString: Value = self.safe_string2(position.clone(), Value::Str("maintMarginReq".to_string()), Value::Str("maintMarginReqRr".to_string()), &[]);
let mut maintenanceMarginString: Value = crate::precise::Precise::stringMul(¬ionalString, &maintenanceMarginPercentageString);
let mut initialMarginString: Value = self.safe_string2(position.clone(), Value::Str("assignedPosBalance".to_string()), Value::Str("assignedPosBalanceRv".to_string()), &[]);
let mut initialMarginPercentageString: Value = crate::precise::Precise::stringDiv(&initialMarginString, ¬ionalString);
let mut liquidationPrice: Value = self.safe_number2(position.clone(), Value::Str("liquidationPrice".to_string()), Value::Str("liquidationPriceRp".to_string()), &[]);
let mut markPriceString: Value = self.safe_string2(position.clone(), Value::Str("markPrice".to_string()), Value::Str("markPriceRp".to_string()), &[]);
let mut contracts: Value = self.safe_string_n(position.clone(), Value::List(vec![Value::Str("size".to_string()), Value::Str("sizeRq".to_string()), Value::Str("closedSizeRq".to_string())]), &[]);
let mut contractSize: Value = self.safe_value_k(market.clone(), "contractSize", &[]);
let mut contractSizeString: Value = self.number_to_string(contractSize.clone());
let mut leverage: Value = self.parse_number(crate::precise::Precise::stringAbs(&(self.safe_string2(position.clone(), Value::Str("leverage".to_string()), Value::Str("leverageRr".to_string()), &[]))), &[]);
let mut entryPriceString: Value = self.safe_string_n(position.clone(), Value::List(vec![Value::Str("avgEntryPrice".to_string()), Value::Str("avgEntryPriceRp".to_string()), Value::Str("openPrice".to_string())]), &[]);
let mut rawSide: Value = self.safe_string_k(position.clone(), "side", &[]);
let mut side: Value = Value::Null;
if !is_equal(&rawSide, &Value::Null) {
let mut isLong: bool = is_equal(&rawSide, &Value::Str("Buy".to_string())) || is_equal(&rawSide, &Value::Str("1".to_string()));
side = ternary(is_true(&isLong), Value::Str("long".to_string()), Value::Str("short".to_string()));
}
// Inverse long contract: unRealizedPnl = (posSize * contractSize) / avgEntryPrice - (posSize * contractSize) / markPrice
// Inverse short contract: unRealizedPnl = (posSize *contractSize) / markPrice - (posSize * contractSize) / avgEntryPrice
// Linear long contract: unRealizedPnl = (posSize * contractSize) * markPrice - (posSize * contractSize) * avgEntryPrice
// Linear short contract: unRealizedPnl = (posSize * contractSize) * avgEntryPrice - (posSize * contractSize) * markPrice
let mut priceDiff: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)) {
if is_equal(&side, &Value::Str("long".to_string())) {
priceDiff = crate::precise::Precise::stringSub(&markPriceString, &entryPriceString);
} else {
priceDiff = crate::precise::Precise::stringSub(&entryPriceString, &markPriceString);
}
} else {
// inverse
if is_equal(&side, &Value::Str("long".to_string())) {
priceDiff = crate::precise::Precise::stringSub(&crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &entryPriceString), &crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &markPriceString));
} else {
priceDiff = crate::precise::Precise::stringSub(&crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &markPriceString), &crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &entryPriceString));
}
}
let mut unrealizedPnl: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&priceDiff, &contracts), &contractSizeString);
// the unrealizedPnl is only available in a specific endpoint which much higher RL limits
let mut apiUnrealizedPnl: Value = self.safe_string_k(position.clone(), "unRealisedPnlRv", &[unrealizedPnl.clone()]);
let mut marginRatio: Value = crate::precise::Precise::stringDiv(&maintenanceMarginString, &collateral);
let mut isCross: Value = self.safe_value_k(position.clone(), "crossMargin", &[]);
let mut timestamp: Value = self.safe_integer_k(position.clone(), "openedTimeNs", &[]);
let mut lastUpdateTimestamp: Value = self.safe_integer_k(position.clone(), "updatedTimeNs", &[self.safe_integer_product(position.clone(), Value::Str("transactTimeNs".to_string()), Value::Float(0.000001), &[])]);
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "execSeq", &[]));
m.insert("symbol".to_string(), symbol.clone());
m.insert("contracts".to_string(), self.parse_number(contracts.clone(), &[]));
m.insert("contractSize".to_string(), contractSize.clone());
m.insert("realizedPnl".to_string(), self.safe_number2(position.clone(), Value::Str("curTermRealisedPnlRv".to_string()), Value::Str("realizedPnlRv".to_string()), &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(apiUnrealizedPnl.clone(), &[]));
m.insert("leverage".to_string(), leverage.clone());
m.insert("liquidationPrice".to_string(), liquidationPrice.clone());
m.insert("collateral".to_string(), self.parse_number(collateral.clone(), &[]));
m.insert("notional".to_string(), self.parse_number(notionalString.clone(), &[]));
m.insert("markPrice".to_string(), self.parse_number(markPriceString.clone(), &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.parse_number(entryPriceString.clone(), &[]));
m.insert("exitPrice".to_string(), self.safe_number_k(position.clone(), "closePrice", &[]));
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp.clone());
m.insert("initialMargin".to_string(), self.parse_number(initialMarginString.clone(), &[]));
m.insert("initialMarginPercentage".to_string(), self.parse_number(initialMarginPercentageString.clone(), &[]));
m.insert("maintenanceMargin".to_string(), self.parse_number(maintenanceMarginString.clone(), &[]));
m.insert("maintenanceMarginPercentage".to_string(), self.parse_number(maintenanceMarginPercentageString.clone(), &[]));
m.insert("marginRatio".to_string(), self.parse_number(marginRatio.clone(), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("marginMode".to_string(), ternary(is_true(&(is_equal(&isCross, &Value::Bool(true)))), Value::Str("cross".to_string()), Value::Str("isolated".to_string())));
m.insert("side".to_string(), side.clone());
m.insert("hedged".to_string(), Value::Bool(is_equal(&self.safe_string_k(position.clone(), "posMode", &[]), &Value::Str("Hedged".to_string()))));
m.insert("percentage".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name phemex#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#futureDataFundingFeesHist
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding history structure]{@link https://docs.ccxt.com/?id=funding-history-structure}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchFundingHistory() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&limit, &Value::Null) {
if is_greater_than(&limit, &Value::Int(200)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchFundingHistory() limit argument cannot exceed 200".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut response: Value = Value::Null;
let mut isStableSettled: bool = is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()));
if is_true(&isStableSettled) {
let __ws_arg_47 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_api_data_g_futures_funding_fees(&[__ws_arg_47]).await;
} else {
let __ws_arg_48 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_api_data_futures_funding_fees(&[__ws_arg_48]).await;
}
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "rows": [
// {
// "symbol": "BTCUSD",
// "currency": "BTC",
// "execQty": 18, // "execQty" regular, but "execQtyRq" in hedge
// "side": "Buy",
// "execPriceEp": 360086455, // "execPriceEp" regular, but "execPriceRp" in hedge
// "execValueEv": 49987, // "execValueEv" regular, but "execValueRv" in hedge
// "fundingRateEr": 10000, // "fundingRateEr" regular, but "fundingRateRr" in hedge
// "feeRateEr": 10000, // "feeRateEr" regular, but "feeRateRr" in hedge
// "execFeeEv": 5, // "execFeeEv" regular, but "execFeeRv" in hedge
// "createTime": 1651881600000
// }
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rows: Value = self.safe_value_k(data.clone(), "rows", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1050: bool = true;
while { if !__for_first_1050 { i = add(&i, &Value::Int(1)); } __for_first_1050 = false; is_less_than(&i, &get_array_length(&rows)) } {
let mut entry: Value = get_value(&rows, &i);
let mut entry: Value = get_value(&rows, &i);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "createTime", &[]);
let mut execFee: Value = self.safe_string2(entry.clone(), Value::Str("execFeeEv".to_string()), Value::Str("execFeeRv".to_string()), &[]);
let mut currencyCode: Value = self.safe_currency_code(self.safe_string_k(entry.clone(), "currency", &[]), &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), self.safe_string_k(entry.clone(), "symbol", &[]));
m.insert("code".to_string(), currencyCode.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("id".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_funding_fee_to_precision(execFee.clone(), &[market.clone(), currencyCode.clone()]));
m
}));
}
}
return result;
Value::Null
}
pub fn parse_funding_fee_to_precision(&self, mut value: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut currencyCode = get_arg(optional_args, 1, Value::Null);
if is_equal(&value, &Value::Null) || is_equal(¤cyCode, &Value::Null) || is_equal(&market, &Value::Null) {
return value;
}
// it was confirmed by phemex support, that USDT contracts use direct amounts in funding fees, while USD & INVERSE needs 'valueScale'
let mut isStableSettled: bool = is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()));
if !is_true(&isStableSettled) {
let mut currency: Value = self.safe_currency(currencyCode.clone(), &[]);
let mut scale: Value = self.safe_string(get_value(¤cy, &Value::Str("info".to_string())), Value::Str("valueScale".to_string()), &[]);
let mut tickPrecision: Value = self.parse_precision(&[scale.clone()]);
value = crate::precise::Precise::stringMul(&value, &tickPrecision);
}
return value;
Value::Null
}
/*
* @method
* @name phemex#fetchFundingRate
* @description fetch the current funding rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" fetchFundingRate() supports swap contracts only".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)) {
let __ws_arg_49 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_md_ticker24hr(&[__ws_arg_49]).await;
} else {
let __ws_arg_50 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_get_md_v2_ticker24hr(&[__ws_arg_50]).await;
}
//
// {
// "error": null,
// "id": 0,
// "result": {
// "askEp": 2332500,
// "bidEp": 2331000,
// "fundingRateEr": 10000,
// "highEp": 2380000,
// "indexEp": 2329057,
// "lastEp": 2331500,
// "lowEp": 2274000,
// "markEp": 2329232,
// "openEp": 2337500,
// "openInterest": 1298050,
// "predFundingRateEr": 19921,
// "symbol": "ETHUSD",
// "timestamp": 1592474241582701416,
// "turnoverEv": 47228362330,
// "volume": 4053863
// }
// }
//
let mut result: Value = self.safe_value_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(result.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "askEp": 2332500,
// "bidEp": 2331000,
// "fundingRateEr": 10000,
// "highEp": 2380000,
// "indexEp": 2329057,
// "lastEp": 2331500,
// "lowEp": 2274000,
// "markEp": 2329232,
// "openEp": 2337500,
// "openInterest": 1298050,
// "predFundingRateEr": 19921,
// "symbol": "ETHUSD",
// "timestamp": 1592474241582701416,
// "turnoverEv": 47228362330,
// "volume": 4053863
// }
//
// linear swap v2
//
// {
// "closeRp":"16820.5",
// "fundingRateRr":"0.0001",
// "highRp":"16962.1",
// "indexPriceRp":"16830.15651565",
// "lowRp":"16785",
// "markPriceRp":"16830.97534951",
// "openInterestRv":"1323.596",
// "openRp":"16851.7",
// "predFundingRateRr":"0.0001",
// "symbol":"BTCUSDT",
// "timestamp":"1672142789065593096",
// "turnoverRv":"124835296.0538",
// "volumeRq":"7406.95"
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut timestamp: Value = self.safe_integer_product(contract.clone(), Value::Str("timestamp".to_string()), Value::Float(0.000001), &[]);
let mut markEp: Value = self.from_ep(self.safe_string_k(contract.clone(), "markEp", &[]), &[market.clone()]);
let mut indexEp: Value = self.from_ep(self.safe_string_k(contract.clone(), "indexEp", &[]), &[market.clone()]);
let mut fundingRateEr: Value = self.from_er(self.safe_string_k(contract.clone(), "fundingRateEr", &[]), &[market.clone()]);
let mut nextFundingRateEr: Value = self.from_er(self.safe_string_k(contract.clone(), "predFundingRateEr", &[]), &[market.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "markPriceRp", &[markEp.clone()]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract.clone(), "indexPriceRp", &[indexEp.clone()]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("fundingRate".to_string(), self.safe_number_k(contract.clone(), "fundingRateRr", &[fundingRateEr.clone()]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), self.safe_number_k(contract.clone(), "predFundingRateRr", &[nextFundingRateEr.clone()]));
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name phemex#setMargin
* @description Either adds or reduces margin in an isolated position in order to set the margin to a specific value
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Contract-API-en.md#assign-position-balance-in-isolated-marign-mode
* @param {string} symbol unified market symbol of the market to set margin in
* @param {float} amount the amount to set the margin to
* @param {object} [params] parameters specific to the exchange API endpoint
* @returns {object} A [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn set_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("posBalanceEv".to_string(), self.to_ev(amount.clone(), &[market.clone()]));
m
});
let __ws_arg_51 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_positions_assign(&[__ws_arg_51]).await;
let __ws_arg_52 = self.parse_margin_modification(response.clone(), &[market.clone()]);
return self.extend(__ws_arg_52, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amount.clone());
m
})]);
Value::Null
}
pub fn parse_margin_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("ok".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "code": 0,
// "msg": "",
// "data": "OK"
// }
//
market = self.safe_market(&[Value::Null, market.clone()]);
let mut inverse: Value = self.safe_value_k(market.clone(), "inverse", &[]);
let mut codeCurrency: Value = ternary(is_true(&(is_equal(&inverse, &Value::Bool(true)))), Value::Str("base".to_string()), Value::Str("quote".to_string()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("type".to_string(), Value::Str("set".to_string()));
m.insert("marginMode".to_string(), Value::Str("isolated".to_string()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), get_value(&market, &codeCurrency));
m.insert("status".to_string(), self.parse_margin_status(self.safe_string_k(data.clone(), "code", &[])));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name phemex#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://phemex-docs.github.io/#set-leverage
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setMarginMode() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" setMarginMode() supports swap contracts only".to_string()))));
}
marginMode = to_lower(&marginMode);
if !is_equal(&marginMode, &Value::Str("isolated".to_string())) && !is_equal(&marginMode, &Value::Str("cross".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" setMarginMode() marginMode argument should be isolated or cross".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut isCross: bool = is_equal(&marginMode, &Value::Str("cross".to_string()));
if is_true(&self.in_array(get_value(&market, &Value::Str("settle".to_string())), Value::List(vec![Value::Str("USDT".to_string()), Value::Str("USDC".to_string())]))) {
let mut currentLeverage: Value = self.safe_string_k(params.clone(), "leverage", &[]);
if is_equal(¤tLeverage, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setMarginMode() requires a \"leverage\" parameter for USDT markets".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("leverageRr".to_string()), ternary(is_true(&isCross), crate::precise::Precise::stringNeg(&crate::precise::Precise::stringAbs(¤tLeverage)), crate::precise::Precise::stringAbs(¤tLeverage)));
let __ws_arg_53 = self.extend(request.clone(), &[params.clone()]);
return self.private_put_g_positions_leverage(&[__ws_arg_53]).await;
}
let mut leverage: Value = self.safe_integer_k(params.clone(), "leverage", &[]);
if is_equal(&marginMode, &Value::Str("cross".to_string())) {
leverage = Value::Int(0);
}
if is_equal(&leverage, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setMarginMode() requires a leverage parameter".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("leverage".to_string()), leverage.clone());
let __ws_arg_54 = self.extend(request.clone(), &[params.clone()]);
return self.private_put_positions_leverage(&[__ws_arg_54]).await;
Value::Null
}
/*
* @method
* @name phemex#setPositionMode
* @description set hedged to true or false for a market
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#switch-position-mode-synchronously
* @param {bool} hedged set to true to use dualSidePosition
* @param {string} symbol not used by setPositionMode ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_position_mode(&mut self, mut hedged: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_argument(Value::Str("setPositionMode".to_string()), symbol.clone(), Value::Str("symbol".to_string()), &[]);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" setPositionMode() supports USDT settled markets only".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if is_true(&hedged) {
add_element_to_object(&mut request, &Value::Str("targetPosMode".to_string()), Value::Str("Hedged".to_string()));
} else {
add_element_to_object(&mut request, &Value::Str("targetPosMode".to_string()), Value::Str("OneWay".to_string()));
}
let __ws_arg_55 = self.extend(request.clone(), &[params.clone()]);
return self.private_put_g_positions_switch_pos_mode_sync(&[__ws_arg_55]).await;
Value::Null
}
/*
* @method
* @name phemex#fetchLeverageTiers
* @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [leverage tiers structures]{@link https://docs.ccxt.com/?id=leverage-tiers-structure}, indexed by market symbols
*/
pub async fn fetch_leverage_tiers(&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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if !is_equal(&symbols, &Value::Null) {
let mut first: Value = self.safe_value(symbols.clone(), Value::Int(0), &[]);
let mut market: Value = self.market(first.clone());
if !is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USD".to_string())) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" fetchLeverageTiers() supports USD settled markets only".to_string()))));
}
}
let mut response: Value = self.public_get_cfg_v2_products(&[params.clone()]).await;
//
// {
// "code":0,
// "msg":"OK",
// "data":{
// "ratioScale":8,
// "currencies":[
// {"currency":"BTC","valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"name":"Bitcoin"},
// {"currency":"USD","valueScale":4,"minValueEv":1,"maxValueEv":500000000000000,"name":"USD"},
// {"currency":"USDT","valueScale":8,"minValueEv":1,"maxValueEv":5000000000000000000,"name":"TetherUS"},
// ],
// "products":[
// {
// "symbol":"BTCUSD",
// "displaySymbol":"BTC / USD",
// "indexSymbol":".BTC",
// "markSymbol":".MBTC",
// "fundingRateSymbol":".BTCFR",
// "fundingRate8hSymbol":".BTCFR8H",
// "contractUnderlyingAssets":"USD",
// "settleCurrency":"BTC",
// "quoteCurrency":"USD",
// "contractSize":1.0,
// "lotSize":1,
// "tickSize":0.5,
// "priceScale":4,
// "ratioScale":8,
// "pricePrecision":1,
// "minPriceEp":5000,
// "maxPriceEp":10000000000,
// "maxOrderQty":1000000,
// "type":"Perpetual"
// },
// {
// "symbol":"sBTCUSDT",
// "displaySymbol":"BTC / USDT",
// "quoteCurrency":"USDT",
// "pricePrecision":2,
// "type":"Spot",
// "baseCurrency":"BTC",
// "baseTickSize":"0.000001 BTC",
// "baseTickSizeEv":100,
// "quoteTickSize":"0.01 USDT",
// "quoteTickSizeEv":1000000,
// "minOrderValue":"10 USDT",
// "minOrderValueEv":1000000000,
// "maxBaseOrderSize":"1000 BTC",
// "maxBaseOrderSizeEv":100000000000,
// "maxOrderValue":"5,000,000 USDT",
// "maxOrderValueEv":500000000000000,
// "defaultTakerFee":"0.001",
// "defaultTakerFeeEr":100000,
// "defaultMakerFee":"0.001",
// "defaultMakerFeeEr":100000,
// "baseQtyPrecision":6,
// "quoteQtyPrecision":2
// },
// ],
// "riskLimits":[
// {
// "symbol":"BTCUSD",
// "steps":"50",
// "riskLimits":[
// {"limit":100,"initialMargin":"1.0%","initialMarginEr":1000000,"maintenanceMargin":"0.5%","maintenanceMarginEr":500000},
// {"limit":150,"initialMargin":"1.5%","initialMarginEr":1500000,"maintenanceMargin":"1.0%","maintenanceMarginEr":1000000},
// {"limit":200,"initialMargin":"2.0%","initialMarginEr":2000000,"maintenanceMargin":"1.5%","maintenanceMarginEr":1500000},
// ]
// },
// ],
// "leverages":[
// {"initialMargin":"1.0%","initialMarginEr":1000000,"options":[1,2,3,5,10,25,50,100]},
// {"initialMargin":"1.5%","initialMarginEr":1500000,"options":[1,2,3,5,10,25,50,66]},
// {"initialMargin":"2.0%","initialMarginEr":2000000,"options":[1,2,3,5,10,25,33,50]},
// ]
// }
// }
//
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut riskLimits: Value = self.safe_list_k(data.clone(), "riskLimits", &[]);
return self.parse_leverage_tiers(riskLimits.clone(), &[symbols.clone(), Value::Str("symbol".to_string())]);
Value::Null
}
pub fn parse_market_leverage_tiers(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
/*
* @param {object} info Exchange market response for 1 market
* @param {object} market CCXT market
*/
//
// {
// "symbol":"BTCUSD",
// "steps":"50",
// "riskLimits":[
// {"limit":100,"initialMargin":"1.0%","initialMarginEr":1000000,"maintenanceMargin":"0.5%","maintenanceMarginEr":500000},
// {"limit":150,"initialMargin":"1.5%","initialMarginEr":1500000,"maintenanceMargin":"1.0%","maintenanceMarginEr":1000000},
// {"limit":200,"initialMargin":"2.0%","initialMarginEr":2000000,"maintenanceMargin":"1.5%","maintenanceMarginEr":1500000},
// ]
// },
//
let mut marketId: Value = self.safe_string_k(info.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut riskLimits: Value = (get_value(&get_value(&market, &Value::Str("info".to_string())), &Value::Str("riskLimits".to_string())));
let mut tiers: Value = Value::List(vec![]);
let mut minNotional: Value = Value::Int(0);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1051: bool = true;
while { if !__for_first_1051 { i = add(&i, &Value::Int(1)); } __for_first_1051 = false; is_less_than(&i, &get_array_length(&riskLimits)) } {
let mut tier: Value = get_value(&riskLimits, &i);
let mut tier: Value = get_value(&riskLimits, &i);
let mut maxNotional: Value = self.safe_integer_k(tier.clone(), "limit", &[]);
let mut minNotionalResponse: Value = minNotional.clone(); // java req
append_to_array(&mut tiers, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tier".to_string(), self.sum(&[i.clone(), Value::Int(1)]));
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("currency".to_string(), get_value(&market, &Value::Str("settle".to_string())));
m.insert("minNotional".to_string(), minNotionalResponse.clone());
m.insert("maxNotional".to_string(), maxNotional.clone());
m.insert("maintenanceMarginRate".to_string(), self.safe_number_k(tier.clone(), "maintenanceMargin", &[]));
m.insert("maxLeverage".to_string(), Value::Null);
m.insert("info".to_string(), tier.clone());
m
}));
minNotional = maxNotional.clone();
}
}
return tiers;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
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 query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut requestPath: Value = add(&Value::Str("/".to_string()), &self.implode_params(path.clone(), params.clone()));
let mut url: Value = requestPath.clone();
let mut queryString: Value = Value::Str("".to_string());
if is_true(&(is_equal(&method, &Value::Str("GET".to_string())))) || is_true(&(is_equal(&method, &Value::Str("DELETE".to_string())))) || is_true(&(is_equal(&method, &Value::Str("PUT".to_string())))) || is_true(&(is_equal(&url, &Value::Str("/positions/assign".to_string())))) {
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
queryString = self.urlencode_with_array_repeat(query.clone());
url = add(&url, &add(&Value::Str("?".to_string()), &queryString));
}
}
if is_equal(&api, &Value::Str("private".to_string())) {
self.check_required_credentials(&[]);
let mut timestamp: Value = self.seconds();
let mut xPhemexRequestExpiry: Value = self.safe_integer_k(self.options.clone(), "x-phemex-request-expiry", &[Value::Int(60)]);
let mut expiry: Value = self.sum(&[timestamp.clone(), xPhemexRequestExpiry.clone()]);
let mut expiryString: Value = to_string_val(&expiry);
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("x-phemex-access-token".to_string(), self.apiKey.clone());
m.insert("x-phemex-request-expiry".to_string(), expiryString.clone());
m
});
let mut payload: Value = Value::Str("".to_string());
if is_equal(&method, &Value::Str("POST".to_string())) {
let mut isOrderPlacement: bool = is_true(&(is_equal(&path, &Value::Str("g-orders".to_string())))) || is_true(&(is_equal(&path, &Value::Str("spot/orders".to_string())))) || is_true(&(is_equal(&path, &Value::Str("orders".to_string()))));
if is_true(&isOrderPlacement) {
if is_equal(&self.safe_string_k(params.clone(), "clOrdID", &[]), &Value::Null) {
let mut id: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("CCXT123456".to_string())]);
add_element_to_object(&mut params, &Value::Str("clOrdID".to_string()), add(&id, &self.uuid16(&[])));
}
}
payload = self.json(params.clone());
body = payload.clone();
add_element_to_object(&mut headers, &Value::Str("Content-Type".to_string()), Value::Str("application/json".to_string()));
}
let mut auth: Value = add(&add(&add(&requestPath, &queryString), &expiryString), &payload);
add_element_to_object(&mut headers, &Value::Str("x-phemex-request-signature".to_string()), self.hmac(self.encode(auth.clone()), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), &[]));
}
url = add(&self.implode_hostname(get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &api)), &url);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
/*
* @method
* @name phemex#setLeverage
* @description set the level of leverage for a market
* @see https://github.com/phemex/phemex-api-docs/blob/master/Public-Hedged-Perpetual-API.md#set-leverage
* @param {float} leverage the rate of leverage, 100 > leverage > -100 excluding numbers between -1 to 1
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.hedged] set to true if hedged position mode is enabled (by default long and short leverage are set to the same value)
* @param {float} [params.longLeverageRr] *hedged mode only* set the leverage for long positions
* @param {float} [params.shortLeverageRr] *hedged mode only* set the leverage for short positions
* @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
}));
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setLeverage() requires a symbol argument".to_string()))));
}
if is_true(&(is_less_than(&leverage, &negate(&Value::Int(100))))) || is_true(&(is_greater_than(&leverage, &Value::Int(100)))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" setLeverage() leverage should be between -100 and 100".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut isHedged: Value = self.safe_bool_k(params.clone(), "hedged", &[Value::Bool(false)]);
let mut longLeverageRr: Value = self.safe_integer_k(params.clone(), "longLeverageRr", &[]);
let mut shortLeverageRr: Value = self.safe_integer_k(params.clone(), "shortLeverageRr", &[]);
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string())) {
if is_true(&(!is_equal(&isHedged, &Value::Bool(true)))) && is_equal(&longLeverageRr, &Value::Null) && is_equal(&shortLeverageRr, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("leverageRr".to_string()), leverage.clone());
} else {
let mut longVar: Value = ternary(is_true(&(!is_equal(&longLeverageRr, &Value::Null))), longLeverageRr.clone(), leverage.clone());
let mut shortVar: Value = ternary(is_true(&(!is_equal(&shortLeverageRr, &Value::Null))), shortLeverageRr.clone(), leverage.clone());
add_element_to_object(&mut request, &Value::Str("longLeverageRr".to_string()), longVar.clone());
add_element_to_object(&mut request, &Value::Str("shortLeverageRr".to_string()), shortVar.clone());
}
let __ws_arg_56 = self.extend(request.clone(), &[params.clone()]);
response = self.private_put_g_positions_leverage(&[__ws_arg_56]).await;
} else {
add_element_to_object(&mut request, &Value::Str("leverage".to_string()), leverage.clone());
let __ws_arg_57 = self.extend(request.clone(), &[params.clone()]);
response = self.private_put_positions_leverage(&[__ws_arg_57]).await;
}
return response;
Value::Null
}
/*
* @method
* @name phemex#transfer
* @description transfer currency internally between wallets on the same account
* @see https://phemex-docs.github.io/#transfer-between-spot-and-futures
* @see https://phemex-docs.github.io/#universal-transfer-main-account-only-transfer-between-sub-to-main-main-to-sub-or-sub-to-sub
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from
* @param {string} toAccount account to transfer to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.bizType] for transferring between main and sub-acounts either 'SPOT' or 'PERPETUAL' default is 'SPOT'
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut accountsByType: Value = self.safe_value_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType.clone(), toAccount.clone(), &[toAccount.clone()]);
let mut scaledAmmount: Value = self.to_ev(amount.clone(), &[currency.clone()]);
let mut direction: Value = Value::Null;
let mut transfer: Value = Value::Null;
if is_equal(&fromId, &Value::Str("spot".to_string())) && is_equal(&toId, &Value::Str("future".to_string())) {
direction = Value::Int(2);
} else if is_equal(&fromId, &Value::Str("future".to_string())) && is_equal(&toId, &Value::Str("spot".to_string())) {
direction = Value::Int(1);
}
if !is_equal(&direction, &Value::Null) {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m.insert("moveOp".to_string(), direction.clone());
m.insert("amountEv".to_string(), scaledAmmount.clone());
m
});
let __ws_arg_58 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_assets_transfer(&[__ws_arg_58]).await;
//
// {
// "code": "0",
// "msg": "OK",
// "data": {
// "linkKey": "8564eba4-c9ec-49d6-9b8c-2ec5001a0fb9",
// "userId": "4018340",
// "currency": "USD",
// "amountEv": "10",
// "side": "2",
// "status": "10"
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
transfer = self.parse_transfer(data.clone(), &[currency.clone()]);
} else {
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fromUserId".to_string(), fromId.clone());
m.insert("toUserId".to_string(), toId.clone());
m.insert("amountEv".to_string(), scaledAmmount.clone());
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m.insert("bizType".to_string(), self.safe_string_k(params.clone(), "bizType", &[Value::Str("SPOT".to_string())]));
m
});
let __ws_arg_59 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_assets_universal_transfer(&[__ws_arg_59]).await;
//
// {
// "code": "0",
// "msg": "OK",
// "data": "API-923db826-aaaa-aaaa-aaaa-4d98c3a7c9fd"
// }
//
transfer = self.parse_transfer(response.clone(), &[]);
}
let mut transferOptions: Value = self.safe_value_k(self.options.clone(), "transfer", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fillResponseFromRequest: Value = self.safe_bool_k(transferOptions.clone(), "fillResponseFromRequest", &[Value::Bool(true)]);
if is_equal(&fillResponseFromRequest, &Value::Bool(true)) {
if is_equal(&get_value(&transfer, &Value::Str("fromAccount".to_string())), &Value::Null) {
add_element_to_object(&mut transfer, &Value::Str("fromAccount".to_string()), fromAccount.clone());
}
if is_equal(&get_value(&transfer, &Value::Str("toAccount".to_string())), &Value::Null) {
add_element_to_object(&mut transfer, &Value::Str("toAccount".to_string()), toAccount.clone());
}
if is_equal(&get_value(&transfer, &Value::Str("amount".to_string())), &Value::Null) {
add_element_to_object(&mut transfer, &Value::Str("amount".to_string()), amount.clone());
}
if is_equal(&get_value(&transfer, &Value::Str("currency".to_string())), &Value::Null) {
add_element_to_object(&mut transfer, &Value::Str("currency".to_string()), code.clone());
}
}
return transfer;
Value::Null
}
/*
* @method
* @name phemex#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://phemex-docs.github.io/#query-transfer-history
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchTransfers() requires a code argument".to_string()))));
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_60 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_assets_transfer(&[__ws_arg_60]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "rows": [
// {
// "linkKey": "87c071a3-8628-4ac2-aca1-6ce0d1fad66c",
// "userId": 4148428,
// "currency": "BTC",
// "amountEv": 67932,
// "side": 2,
// "status": 10,
// "createTime": 1652832467000,
// "bizType": 10
// }
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut transfers: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
return self.parse_transfers(transfers.clone(), &[currency.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// transfer
//
// {
// "linkKey": "8564eba4-c9ec-49d6-9b8c-2ec5001a0fb9",
// "userId": "4018340",
// "currency": "USD",
// "amountEv": "10",
// "side": "2",
// "status": "10"
// }
//
// fetchTransfers
//
// {
// "linkKey": "87c071a3-8628-4ac2-aca1-6ce0d1fad66c",
// "userId": 4148428,
// "currency": "BTC",
// "amountEv": 67932,
// "side": 2,
// "status": 10,
// "createTime": 1652832467000,
// "bizType": 10
// }
//
let mut id: Value = self.safe_string_k(transfer.clone(), "linkKey", &[]);
let mut status: Value = self.safe_string_k(transfer.clone(), "status", &[]);
let mut amountEv: Value = self.safe_string_k(transfer.clone(), "amountEv", &[]);
let mut amountTransfered: Value = self.from_ev(amountEv.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
let mut side: Value = self.safe_integer_k(transfer.clone(), "side", &[]);
let mut fromId: Value = Value::Null;
let mut toId: Value = Value::Null;
if is_equal(&side, &Value::Int(1)) {
fromId = Value::Str("swap".to_string());
toId = Value::Str("spot".to_string());
} else if is_equal(&side, &Value::Int(2)) {
fromId = Value::Str("spot".to_string());
toId = Value::Str("swap".to_string());
}
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "createTime", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), id.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), amountTransfered.clone());
m.insert("fromAccount".to_string(), fromId.clone());
m.insert("toAccount".to_string(), toId.clone());
m.insert("status".to_string(), self.parse_transfer_status(status.clone()));
m
});
Value::Null
}
pub fn parse_transfer_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("3".to_string(), Value::Str("rejected".to_string()));
m.insert("6".to_string(), Value::Str("canceled".to_string()));
m.insert("10".to_string(), Value::Str("ok".to_string()));
m.insert("11".to_string(), Value::Str("failed".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://phemex-docs.github.io/#query-funding-rate-history-2
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {int} [params.until] timestamp in ms of the latest funding rate
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchFundingRateHistory() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut isUsdtSettled: bool = is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDT".to_string())) || is_equal(&get_value(&market, &Value::Str("settle".to_string())), &Value::Str("USDC".to_string()));
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchFundingRateHistory() supports swap contracts only".to_string()))));
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchFundingRateHistory".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchFundingRateHistory".to_string()), &[symbol.clone(), since.clone(), limit.clone(), Value::Str("8h".to_string()), params.clone(), Value::Int(100)]).await;
}
let mut customSymbol: Value = Value::Null;
if is_true(&isUsdtSettled) {
customSymbol = add(&add(&Value::Str(".".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str("FR8H".to_string())); // phemex requires a custom symbol for funding rate history
} else {
customSymbol = add(&add(&Value::Str(".".to_string()), &get_value(&market, &Value::Str("baseId".to_string()))), &Value::Str("FR8H".to_string()));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), customSymbol.clone());
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut response: Value = Value::Null;
if is_true(&isUsdtSettled) {
let __ws_arg_61 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_get_api_data_public_data_funding_rate_history(&[__ws_arg_61]).await;
} else {
let __ws_arg_62 = self.extend(request.clone(), &[params.clone()]);
response = self.v1_get_api_data_public_data_funding_rate_history(&[__ws_arg_62]).await;
}
//
// {
// "code":"0",
// "msg":"OK",
// "data":{
// "rows":[
// {
// "symbol":".BTCUSDTFR8H",
// "fundingRate":"0.0001",
// "fundingTime":"1682064000000",
// "intervalSeconds":"28800"
// }
// ]
// }
// }
//
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rates: Value = self.safe_value_k(data.clone(), "rows", &[]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1052: bool = true;
while { if !__for_first_1052 { i = add(&i, &Value::Int(1)); } __for_first_1052 = false; is_less_than(&i, &get_array_length(&rates)) } {
let mut item: Value = get_value(&rates, &i);
let mut item: Value = get_value(&rates, &i);
let mut timestamp: Value = self.safe_integer_k(item.clone(), "fundingTime", &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("fundingRate".to_string(), self.safe_number_k(item.clone(), "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
}));
}
}
let mut sorted: Value = self.sort_by(result.clone(), Value::Str("timestamp".to_string()), &[]);
return self.filter_by_symbol_since_limit(sorted.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name phemex#withdraw
* @description make a withdrawal
* @see https://phemex-docs.github.io/#create-withdraw-request
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] unified network code
* @returns {object} a [transaction structure]{@link https://github.com/ccxt/ccxt/wiki/Manual#transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
{ let __destr_tmp = self.handle_withdraw_tag_and_params(tag.clone(), params.clone()); tag = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.check_address(&[address.clone()]);
let mut currency: Value = self.currency(code.clone());
let mut networkCode: Value = Value::Null;
{ let __destr_tmp = self.handle_network_code_and_params(params.clone()); networkCode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut networkId: Value = Value::Null;
if !is_equal(&networkCode, &Value::Null) {
networkId = self.network_code_to_id(networkCode.clone(), &[code.clone()]);
}
let mut stableCoins: Value = self.safe_value_k(self.options.clone(), "stableCoins", &[]);
if is_equal(&networkId, &Value::Null) {
if !is_true(&(self.in_array(code.clone(), stableCoins.clone()))) {
networkId = get_value(¤cy, &Value::Str("id".to_string()));
} else {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" withdraw () requires an extra argument params[\"network\"]".to_string()))));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m.insert("address".to_string(), address.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("chainName".to_string(), to_upper(&networkId));
m
});
if !is_equal(&tag, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("addressTag".to_string()), tag.clone());
}
let __ws_arg_63 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_phemex_withdraw_wallets_api_create_withdraw(&[__ws_arg_63]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "id": "10000001",
// "freezeId": null,
// "address": "44exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
// "amountRv": "100",
// "chainCode": "11",
// "chainName": "TRX",
// "currency": "USDT",
// "currencyCode": 3,
// "email": "abc@gmail.com",
// "expiredTime": "0",
// "feeRv": "1",
// "nickName": null,
// "phone": null,
// "rejectReason": "",
// "submitedAt": "1670000000000",
// "submittedAt": "1670000000000",
// "txHash": null,
// "userId": "10000001",
// "status": "Success"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data.clone(), &[currency.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchOpenInterest
* @description retrieves the open interest of a trading pair
* @see https://phemex-docs.github.io/#query-24-hours-ticker
* @param {string} symbol unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("contract".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchOpenInterest is only supported for contract markets.".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_64 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.v2_get_md_v2_ticker24hr(&[__ws_arg_64]).await;
//
// {
// error: null,
// id: '0',
// result: {
// closeRp: '67550.1',
// fundingRateRr: '0.0001',
// highRp: '68400',
// indexPriceRp: '67567.15389794',
// lowRp: '66096.4',
// markPriceRp: '67550.1',
// openInterestRv: '1848.1144186',
// openRp: '66330',
// predFundingRateRr: '0.0001',
// symbol: 'BTCUSDT',
// timestamp: '1729114315443343001',
// turnoverRv: '228863389.3237532',
// volumeRq: '3388.5600312'
// }
// }
//
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[]);
return self.parse_open_interest(result.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// closeRp: '67550.1',
// fundingRateRr: '0.0001',
// highRp: '68400',
// indexPriceRp: '67567.15389794',
// lowRp: '66096.4',
// markPriceRp: '67550.1',
// openInterestRv: '1848.1144186',
// openRp: '66330',
// predFundingRateRr: '0.0001',
// symbol: 'BTCUSDT',
// timestamp: '1729114315443343001',
// turnoverRv: '228863389.3237532',
// volumeRq: '3388.5600312'
// }
//
let mut timestamp: Value = divide(&self.safe_integer_k(interest.clone(), "timestamp", &[]), &Value::Int(1000000));
let mut id: Value = self.safe_string_k(interest.clone(), "symbol", &[]);
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), interest.clone());
m.insert("symbol".to_string(), self.safe_symbol(id.clone(), &[market.clone()]));
m.insert("baseVolume".to_string(), self.safe_string_k(interest.clone(), "volumeRq", &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("openInterestAmount".to_string(), self.safe_string_k(interest.clone(), "openInterestRv", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchConvertQuote
* @description fetch a quote for converting from one currency to another
* @see https://phemex-docs.github.io/#rfq-quote
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} amount how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_quote(&mut self, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut fromCurrency: Value = self.currency(fromCode.clone());
let mut toCurrency: Value = self.currency(toCode.clone());
let mut valueScale: Value = self.safe_integer_k(fromCurrency.clone(), "valueScale", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fromCurrency".to_string(), fromCode.clone());
m.insert("toCurrency".to_string(), toCode.clone());
m.insert("fromAmountEv".to_string(), self.to_en(amount.clone(), valueScale.clone()));
m
});
let __ws_arg_65 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_assets_quote(&[__ws_arg_65]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "code": "GIF...AAA",
// "quoteArgs": {
// "origin": 10,
// "price": "0.00000939",
// "proceeds": "0.00000000",
// "ttlMs": 7000,
// "expireAt": 1739875826009,
// "requestAt": 1739875818009,
// "quoteAt": 1739875816594
// }
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data.clone(), &[fromCurrency.clone(), toCurrency.clone()]);
Value::Null
}
/*
* @method
* @name phemex#createConvertTrade
* @description convert from one currency to another
* @see https://phemex-docs.github.io/#convert
* @param {string} id the id of the trade that you want to make
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} [amount] how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn create_convert_trade(&mut self, mut id: Value, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut fromCurrency: Value = self.currency(fromCode.clone());
let mut toCurrency: Value = self.currency(toCode.clone());
let mut valueScale: Value = self.safe_integer_k(fromCurrency.clone(), "valueScale", &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("code".to_string(), id.clone());
m.insert("fromCurrency".to_string(), fromCode.clone());
m.insert("toCurrency".to_string(), toCode.clone());
m
});
if !is_equal(&amount, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("fromAmountEv".to_string()), self.to_en(amount.clone(), valueScale.clone()));
}
let __ws_arg_66 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_assets_convert(&[__ws_arg_66]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "moveOp": 0,
// "fromCurrency": "USDT",
// "toCurrency": "BTC",
// "fromAmountEv": 4000000000,
// "toAmountEv": 41511,
// "linkKey": "45c8ed8e-d3f4-472d-8262-e464e8c46247",
// "status": 10
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromCurrencyId: Value = self.safe_string_k(data.clone(), "fromCurrency", &[]);
let mut fromResult: Value = self.safe_currency(fromCurrencyId.clone(), &[fromCurrency.clone()]);
let mut toCurrencyId: Value = self.safe_string_k(data.clone(), "toCurrency", &[]);
let mut to: Value = self.safe_currency(toCurrencyId.clone(), &[toCurrency.clone()]);
return self.parse_conversion(data.clone(), &[fromResult.clone(), to.clone()]);
Value::Null
}
/*
* @method
* @name phemex#fetchConvertTradeHistory
* @description fetch the users history of conversion trades
* @see https://phemex-docs.github.io/#query-convert-history
* @param {string} [code] the unified currency code
* @param {int} [since] the earliest time in ms to fetch conversions for
* @param {int} [limit] the maximum number of conversion structures to retrieve, default 20, max 200
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.until] the end time in ms
* @param {string} [params.fromCurrency] the currency that you sold and converted from
* @param {string} [params.toCurrency] the currency that you bought and converted into
* @returns {object[]} a list of [conversion structures]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_trade_history(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("fromCurrency".to_string()), code.clone());
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
{ let __destr_tmp = self.handle_until_option(Value::Str("endTime".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_67 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_assets_convert(&[__ws_arg_67]).await;
//
// {
// "code": 0,
// "msg": "OK",
// "data": {
// "total": 2,
// "rows": [
// {
// "linkKey": "45c8ed8e-d3f4-472d-8262-e464e8c46247",
// "createTime": 1739882294000,
// "fromCurrency": "USDT",
// "toCurrency": "BTC",
// "fromAmountEv": 4000000000,
// "toAmountEv": 41511,
// "status": 10,
// "conversionRate": 1037,
// "errorCode": 0
// },
// ]
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rows: Value = self.safe_list_k(data.clone(), "rows", &[Value::List(vec![])]);
return self.parse_conversions(rows.clone(), &[code.clone(), Value::Str("fromCurrency".to_string()), Value::Str("toCurrency".to_string()), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_conversion(&self, mut conversion: Value, optional_args: &[Value]) -> Value {
let mut fromCurrency = get_arg(optional_args, 0, Value::Null);
let mut toCurrency = get_arg(optional_args, 1, Value::Null);
//
// fetchConvertQuote
//
// {
// "code": "GIF...AAA",
// "quoteArgs": {
// "origin": 10,
// "price": "0.00000939",
// "proceeds": "0.00000000",
// "ttlMs": 7000,
// "expireAt": 1739875826009,
// "requestAt": 1739875818009,
// "quoteAt": 1739875816594
// }
// }
//
// createConvertTrade
//
// {
// "moveOp": 0,
// "fromCurrency": "USDT",
// "toCurrency": "BTC",
// "fromAmountEv": 4000000000,
// "toAmountEv": 41511,
// "linkKey": "45c8ed8e-d3f4-472d-8262-e464e8c46247",
// "status": 10
// }
//
// fetchConvertTradeHistory
//
// {
// "linkKey": "45c8ed8e-d3f4-472d-8262-e464e8c46247",
// "createTime": 1739882294000,
// "fromCurrency": "USDT",
// "toCurrency": "BTC",
// "fromAmountEv": 4000000000,
// "toAmountEv": 41511,
// "status": 10,
// "conversionRate": 1037,
// "errorCode": 0
// }
//
let mut quoteArgs: Value = self.safe_dict_k(conversion.clone(), "quoteArgs", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut requestTime: Value = self.safe_integer_k(quoteArgs.clone(), "requestAt", &[]);
let mut timestamp: Value = self.safe_integer_k(conversion.clone(), "createTime", &[requestTime.clone()]);
let mut fromCoin: Value = self.safe_string_k(conversion.clone(), "fromCurrency", &[self.safe_string(fromCurrency.clone(), Value::Str("code".to_string()), &[])]);
let mut fromCode: Value = self.safe_currency_code(fromCoin.clone(), &[fromCurrency.clone()]);
let mut toCoin: Value = self.safe_string_k(conversion.clone(), "toCurrency", &[self.safe_string(toCurrency.clone(), Value::Str("code".to_string()), &[])]);
let mut toCode: Value = self.safe_currency_code(toCoin.clone(), &[toCurrency.clone()]);
let mut fromValueScale: Value = self.safe_integer_k(fromCurrency.clone(), "valueScale", &[]);
let mut toValueScale: Value = self.safe_integer_k(toCurrency.clone(), "valueScale", &[]);
let mut fromAmount: Value = self.from_en(self.safe_string_k(conversion.clone(), "fromAmountEv", &[]), fromValueScale.clone());
if is_equal(&fromAmount, &Value::Null) && !is_equal("eArgs, &Value::Null) {
fromAmount = self.from_en(self.safe_string_k(quoteArgs.clone(), "origin", &[]), fromValueScale.clone());
}
let mut toAmount: Value = self.from_en(self.safe_string_k(conversion.clone(), "toAmountEv", &[]), toValueScale.clone());
if is_equal(&toAmount, &Value::Null) && !is_equal("eArgs, &Value::Null) {
toAmount = self.from_en(self.safe_string_k(quoteArgs.clone(), "proceeds", &[]), toValueScale.clone());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), conversion.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("id".to_string(), self.safe_string_k(conversion.clone(), "code", &[]));
m.insert("fromCurrency".to_string(), fromCode.clone());
m.insert("fromAmount".to_string(), self.parse_number(fromAmount.clone(), &[]));
m.insert("toCurrency".to_string(), toCode.clone());
m.insert("toAmount".to_string(), self.parse_number(toAmount.clone(), &[]));
m.insert("price".to_string(), self.safe_number_k(quoteArgs.clone(), "price", &[]));
m.insert("fee".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name phemex#fetchPositionsADLRank
* @description fetches the auto deleveraging rank and risk percentage for a list of symbols
* @see https://phemex-docs.github.io/#query-account-positions
* @see https://phemex-docs.github.io/#query-trading-account-and-positions
* @see https://phemex-docs.github.io/#query-account-positions-with-unrealized-pnl
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.code] the currency code to fetch ranks for, USD, BTC or USDT, USDT is the default
* @param {string} [params.method] *USDT contracts only* 'privateGetGAccountsAccountPositions' or 'privateGetGAccountsPositions' default is 'privateGetGAccountsAccountPositions'
* @returns {object} an array of [auto de leverage structures]{@link https://docs.ccxt.com/?id=auto-de-leverage-structure}
*/
pub async fn fetch_positions_adl_rank(&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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut subType: Value = Value::Null;
let mut code: Value = self.safe_string2(params.clone(), Value::Str("currency".to_string()), Value::Str("code".to_string()), &[Value::Str("USDT".to_string())]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("currency".to_string()), Value::Str("code".to_string())]), &[]);
let mut settle: Value = Value::Null;
let mut market: Value = Value::Null;
let mut firstSymbol: Value = self.safe_string(symbols.clone(), Value::Int(0), &[]);
if !is_equal(&firstSymbol, &Value::Null) {
market = self.market(firstSymbol.clone());
settle = get_value(&market, &Value::Str("settle".to_string()));
code = get_value(&market, &Value::Str("settle".to_string()));
} else {
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositionsADLRank".to_string()), Value::Str("settle".to_string()), &[code.clone()]); settle = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
}
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("fetchPositionsADLRank".to_string()), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isUSDTSettled: bool = is_equal(&settle, &Value::Str("USDT".to_string()));
if is_true(&isUSDTSettled) {
code = Value::Str("USDT".to_string());
} else if is_equal(&settle, &Value::Str("BTC".to_string())) {
code = Value::Str("BTC".to_string());
} else if is_equal(&code, &Value::Null) {
code = ternary(is_true(&(is_equal(&subType, &Value::Str("linear".to_string())))), Value::Str("USD".to_string()), Value::Str("BTC".to_string()));
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
if is_true(&isUSDTSettled) {
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositionsADLRank".to_string()), Value::Str("method".to_string()), &[Value::Str("privateGetGAccountsAccountPositions".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&method, &Value::Str("privateGetGAccountsAccountPositions".to_string())) {
let __ws_arg_68 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_accounts_account_positions(&[__ws_arg_68]).await;
} else {
let __ws_arg_69 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_g_accounts_positions(&[__ws_arg_69]).await;
}
} else {
let __ws_arg_70 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_accounts_account_positions(&[__ws_arg_70]).await;
}
let mut data: Value = self.safe_value_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ranks: Value = self.safe_value_k(data.clone(), "positions", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1053: bool = true;
while { if !__for_first_1053 { i = add(&i, &Value::Int(1)); } __for_first_1053 = false; is_less_than(&i, &get_array_length(&ranks)) } {
let mut rank: Value = get_value(&ranks, &i);
let mut rank: Value = get_value(&ranks, &i);
append_to_array(&mut result, self.parse_adl_rank(rank.clone(), &[]));
}
}
return self.filter_by_array_adl_ranks(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
Value::Null
}
pub fn parse_adl_rank(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPositionADLRank: linear
//
// {
// "userID": 940666,
// "accountID": 9406660003,
// "symbol": "BTCUSDT",
// "currency": "USDT",
// "side": "Buy",
// "positionStatus": "Normal",
// "crossMargin": true,
// "leverageRr": "-10",
// "initMarginReqRr": "0.1",
// "maintMarginReqRr": "0.005",
// "riskLimitRv": "20000000",
// "size": "0.01",
// "valueRv": "887.531",
// "avgEntryPriceRp": "88753.1",
// "avgEntryPrice": "88753.1",
// "posCostRv": "89.22502732",
// "assignedPosBalanceRv": "89.29802732",
// "bankruptCommRv": "0.529812426",
// "bankruptPriceRp": "44783.79",
// "positionMarginRv": "88.695214894",
// "liquidationPriceRp": "45009",
// "deleveragePercentileRr": "0",
// "buyValueToCostRr": "0.10114",
// "sellValueToCostRr": "0.10126",
// "markPriceRp": "88747.2",
// "estimatedOrdLossRv": "0",
// "usedBalanceRv": "89.22502732",
// "cumClosedPnlRv": "425.97796",
// "cumFundingFeeRv": "54.892930099379",
// "cumTransactFeeRv": "1.288782144",
// "transactTimeNs": 1767176685241254818,
// "takerFeeRateRr": "-1",
// "makerFeeRateRr": "-1",
// "term": 6,
// "lastTermEndTimeNs": 1759835547751667598,
// "lastFundingTimeNs": 1759824000000000000,
// "curTermRealisedPnlRv": "-0.5325186",
// "execSeq": 47732822790,
// "posSide": "Long",
// "posMode": "Hedged",
// "buyLeavesValueRv": "0",
// "buyLeavesQtyRq": "0",
// "sellLeavesValueRv": "0",
// "sellLeavesQtyRq": "0"
// }
//
// fetchPositionADLRank: inverse
//
// {
// "userID": 940666,
// "accountID": 9406660001,
// "symbol": "BTCUSD",
// "currency": "BTC",
// "side": "Buy",
// "positionStatus": "Normal",
// "crossMargin": false,
// "leverageEr": -2000000000,
// "leverage": -20.00000000,
// "initMarginReqEr": 5000000,
// "initMarginReq": 0.05000000,
// "maintMarginReqEr": 500000,
// "maintMarginReq": 0.00500000,
// "riskLimitEv": 150000000000,
// "riskLimit": 1500.00000000,
// "size": 1,
// "value": 0.00001128,
// "valueEv": 1128,
// "avgEntryPriceEp": 886524823,
// "avgEntryPrice": 88652.48230000,
// "posCostEv": 58,
// "posCost": 5.8E-7,
// "assignedPosBalanceEv": 58,
// "assignedPosBalance": 5.8E-7,
// "bankruptCommEv": 1,
// "bankruptComm": 1E-8,
// "bankruptPriceEp": 100000,
// "bankruptPrice": 10.00000000,
// "positionMarginEv": 57,
// "positionMargin": 5.7E-7,
// "liquidationPriceEp": 100000,
// "liquidationPrice": 10.00000000,
// "deleveragePercentileEr": 0,
// "deleveragePercentile": 0E-8,
// "buyValueToCostEr": 5123000,
// "buyValueToCost": 0.05123000,
// "sellValueToCostEr": 5117000,
// "sellValueToCost": 0.05117000,
// "markPriceEp": 886028000,
// "markPrice": 88602.80000000,
// "estimatedOrdLossEv": 0,
// "estimatedOrdLoss": 0E-8,
// "usedBalanceEv": 58,
// "usedBalance": 5.8E-7,
// "cumClosedPnlEv": 127,
// "cumFundingFeeEv": -146,
// "cumTransactFeeEv": 3,
// "transactTimeNs": 1767177964554892106,
// "takerFeeRateEr": 60000,
// "makerFeeRateEr": 10000,
// "term": 2,
// "lastTermEndTimeNs": 1716225275381802994,
// "lastFundingTimeNs": 1767168000000000000,
// "curTermRealisedPnlEv": -1,
// "execSeq": 1104909332,
// "freeQty": -1,
// "freeCostEv": 0,
// "buyLeavesValueEv": 0,
// "sellLeavesValueEv": 0,
// "buyLeavesQty": 0,
// "sellLeavesQty": 0
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone(), Value::Null, Value::Str("contract".to_string())]));
m.insert("rank".to_string(), Value::Null);
m.insert("rating".to_string(), Value::Null);
m.insert("percentage".to_string(), self.safe_number2(info.clone(), Value::Str("deleveragePercentileRr".to_string()), Value::Str("deleveragePercentileEr".to_string()), &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
//
// {"code":30018,"msg":"phemex.data.size.uplimt","data":null}
// {"code":412,"msg":"Missing parameter - resolution","data":null}
// {"code":412,"msg":"Missing parameter - to","data":null}
// {"error":{"code":6001,"message":"invalid argument"},"id":null,"result":null}
//
let mut error: Value = self.safe_value_k(response.clone(), "error", &[response.clone()]);
let mut errorCode: Value = self.safe_string_k(error.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(error.clone(), "msg", &[]);
if is_true(&(!is_equal(&errorCode, &Value::Null))) && is_true(&(!is_equal(&errorCode, &Value::Str("0".to_string())))) {
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), message.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}