// 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 BitmexCore {
pub exchange: crate::exchange::Exchange,
}
impl BitmexCore {
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 = BitmexCore::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 BitmexCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_ticker(self, ticker, &[market.clone()])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_trade(self, trade, &[market.clone()])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_order(self, order, &[market.clone()])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_ohlcv(self, ohlcv, &[market.clone()])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::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 BitmexCore.
BitmexCore::parse_funding_rate(self, rate, &[market.clone()])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_ledger_entry(self, entry, &[currency.clone()])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_open_interest(self, interest, &[market.clone()])
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_liquidation(self, liquidation, &[market.clone()])
}
fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_funding_rate_history(self, entry, &[market.clone()])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::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 BitmexCore.
BitmexCore::parse_adl_rank(self, info, &[market.clone()])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_leverage(self, leverage, &[market.clone()])
}
fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BitmexCore.
BitmexCore::parse_deposit_withdraw_fee(self, fee, &[currency.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 BitmexCore.
BitmexCore::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 BitmexCore.
BitmexCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BitmexCore {
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 {
"amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"calculate_rate_limiter_cost" => self.calculate_rate_limiter_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]),
"cancel_all_orders" => self.cancel_all_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).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,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"convert_from_raw_cost" => self.convert_from_raw_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"convert_from_raw_quantity" => self.convert_from_raw_quantity(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()[..]),
"convert_from_real_amount" => self.convert_from_real_amount(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"convert_to_real_amount" => self.convert_to_real_amount(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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,
"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_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_deposit_withdraw_fees" => self.fetch_deposit_withdraw_fees(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ledger" => self.fetch_ledger(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_leverages" => self.fetch_leverages(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_liquidations" => self.fetch_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).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_interests" => self.fetch_open_interests(&args.get(0..).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_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_settlement_history" => self.fetch_settlement_history(&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,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"nonce" => self.nonce(),
"parse_adl_rank" => self.parse_adl_rank(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_withdraw_fee" => self.parse_deposit_withdraw_fee(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_funding_rate_history" => self.parse_funding_rate_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry_type" => self.parse_ledger_entry_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_liquidation" => self.parse_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.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_status" => self.parse_order_status(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_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_settlements" => self.parse_settlements(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)),
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).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,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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 BitmexCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for BitmexCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl BitmexCore {
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("bitmex".to_string()));
m.insert("name".to_string(), Value::Str("BitMEX".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("SC".to_string())]));
m.insert("version".to_string(), Value::Str("v1".to_string()));
m.insert("userAgent".to_string(), Value::Null);
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("certified".to_string(), Value::Bool(true));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(true));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Null);
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchLeverages".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(true));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyLiquidations".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::Str("emulated".to_string()));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositionADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionHistory".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(false));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(true));
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("fetchTransactions".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("index".to_string(), Value::Bool(false));
m.insert("reduceMargin".to_string(), Value::Null);
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::Null);
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".to_string()));
m.insert("5m".to_string(), Value::Str("5m".to_string()));
m.insert("1h".to_string(), Value::Str("1h".to_string()));
m.insert("1d".to_string(), Value::Str("1d".to_string()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://testnet.bitmex.com".to_string()));
m.insert("private".to_string(), Value::Str("https://testnet.bitmex.com".to_string()));
m
}));
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/3360333d-35a6-4503-bbba-92a6bc0c174f".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://www.bitmex.com".to_string()));
m.insert("private".to_string(), Value::Str("https://www.bitmex.com".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.bitmex.com".to_string()));
m.insert("doc".to_string(), Value::List(vec![Value::Str("https://www.bitmex.com/app/apiOverview".to_string()), Value::Str("https://github.com/BitMEX/api-connectors/tree/master/official-http".to_string())]));
m.insert("fees".to_string(), Value::Str("https://www.bitmex.com/app/fees".to_string()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://www.bitmex.com/app/register/NZTR1q".to_string()));
m.insert("discount".to_string(), Value::Float(0.1));
m
}));
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("announcement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("announcement/urgent".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("chat".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("chat/channels".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("chat/connected".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("chat/pinned".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/active".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/activeAndIndices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/activeIntervals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/compositeIndex".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/indices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("instrument/usdVolume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("insurance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("leaderboard".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("liquidation".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("orderBook/L2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("porl/nonce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("quote/bucketed".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("schema".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("schema/websocketHelp".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("settlement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("stats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("stats/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("stats/historyUSD".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("trade/bucketed".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("wallet/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("wallet/networks".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("address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("apiKey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("execution".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("execution/tradeHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("globalNotification".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("leaderboard/name".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("porl/snapshots".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/affiliateStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/checkReferralCode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/commission".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/csa".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/depositAddress".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/executionHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/getWalletTransferAccounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/quoteFillRatio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/quoteValueRatio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/staking".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/staking/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/staking/tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/tradingVolume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/unstakingRequests".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/wallet".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/walletHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/walletSummary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("userAffiliates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("userEvent".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("address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("chat".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild/archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild/join".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild/kick".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild/leave".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("guild/sharesTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order/cancelAllAfter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("order/closePosition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("position/isolate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("position/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("position/riskLimit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("position/transferMargin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/addSubaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/cancelWithdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/communicationToken".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/confirmEmail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/confirmWithdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/logout".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/preferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/requestWithdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/unstakingRequests".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/updateSubaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("user/walletTransfer".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("guild".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("order/all".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/unstakingRequests".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m
}));
m
}));
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("Invalid API Key.".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("This key is disabled.".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("Access Denied".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("Duplicate clOrdID".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("orderQty is invalid".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Invalid price".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Invalid stopPx for ordType".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("Account is restricted".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Signature not valid".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("overloaded".to_string(), Value::Str("ExchangeNotAvailable".to_string()).clone());
m.insert("Account has insufficient Available Balance".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("Service unavailable".to_string(), Value::Str("ExchangeNotAvailable".to_string()).clone());
m.insert("Server Error".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("Unable to cancel order due to existing state".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("We require all new traders to verify".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("recvWindow".to_string(), Value::Int(5000));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("useOpenTimestamp".to_string(), Value::Bool(true));
m
}));
m.insert("oldPrecision".to_string(), Value::Bool(false));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BTC".to_string(), Value::Str("btc".to_string()));
m.insert("ERC20".to_string(), Value::Str("eth".to_string()));
m.insert("BEP20".to_string(), Value::Str("bsc".to_string()));
m.insert("TRC20".to_string(), Value::Str("tron".to_string()));
m.insert("AVAXC".to_string(), Value::Str("avax".to_string()));
m.insert("NEAR".to_string(), Value::Str("near".to_string()));
m.insert("XTZ".to_string(), Value::Str("xtz".to_string()));
m.insert("DOT".to_string(), Value::Str("dot".to_string()));
m.insert("SOL".to_string(), Value::Str("sol".to_string()));
m.insert("ADA".to_string(), Value::Str("ada".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(true));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m
}));
m.insert("triggerDirection".to_string(), Value::Bool(true));
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("trailing".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".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(500));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(1000000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(1000000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(1000000));
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(10000));
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.insert("createOrder".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("index".to_string(), Value::Bool(false));
m
}));
m
}));
m
}));
m.insert("derivatives".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("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("index".to_string(), Value::Bool(true));
m
}));
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("derivatives".to_string()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("derivatives".to_string()));
m
}));
m
}));
m.insert("future".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("derivatives".to_string()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("derivatives".to_string()));
m
}));
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("USDt".to_string(), Value::Str("USDT".to_string()));
m.insert("XBt".to_string(), Value::Str("BTC".to_string()));
m.insert("XBT".to_string(), Value::Str("BTC".to_string()));
m.insert("Gwei".to_string(), Value::Str("ETH".to_string()));
m.insert("GWEI".to_string(), Value::Str("ETH".to_string()));
m.insert("LAMP".to_string(), Value::Str("SOL".to_string()));
m.insert("LAMp".to_string(), Value::Str("SOL".to_string()));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name bitmex#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://www.bitmex.com/api/explorer/#!/Wallet/Wallet_getAssetsConfig
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_wallet_assets(&[params.clone()]).await;
return self.parse_currencies(response.clone());
Value::Null
}
pub fn parse_currency(&self, mut currency: Value) -> Value {
let mut asset: Value = self.safe_string_k(currency.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(asset.clone(), &[]);
let mut id: Value = self.safe_string_k(currency.clone(), "currency", &[]);
let mut name: Value = self.safe_string_k(currency.clone(), "name", &[]);
let mut chains: Value = self.safe_value_k(currency.clone(), "networks", &[Value::List(vec![])]);
let mut depositEnabled: Value = Value::Bool(false);
let mut withdrawEnabled: Value = Value::Bool(false);
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut scale: Value = self.safe_string_k(currency.clone(), "scale", &[]);
let mut precisionString: Value = self.parse_precision(&[scale.clone()]);
let mut precision: Value = self.parse_number(precisionString.clone(), &[]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_380: bool = true;
while { if !__for_first_380 { j = add(&j, &Value::Int(1)); } __for_first_380 = false; is_less_than(&j, &get_array_length(&chains)) } {
let mut chain: Value = get_value(&chains, &j);
let mut chain: Value = get_value(&chains, &j);
let mut networkId: Value = self.safe_string_k(chain.clone(), "asset", &[]);
let mut network: Value = self.network_id_to_code(&[networkId.clone(), code.clone()]);
let mut withdrawalFeeRaw: Value = self.safe_string_k(chain.clone(), "withdrawalFee", &[]);
let mut withdrawalFee: Value = self.parse_number(crate::precise::Precise::stringMul(&withdrawalFeeRaw, &precisionString), &[]);
let mut isDepositEnabled: Value = self.safe_bool_k(chain.clone(), "depositEnabled", &[Value::Bool(false)]);
let mut isWithdrawEnabled: Value = self.safe_bool_k(chain.clone(), "withdrawalEnabled", &[Value::Bool(false)]);
let mut active: Value = Value::Bool(is_true(&(is_equal(&isDepositEnabled, &Value::Bool(true)))) && is_true(&(is_equal(&isWithdrawEnabled, &Value::Bool(true)))));
if is_equal(&isDepositEnabled, &Value::Bool(true)) {
depositEnabled = Value::Bool(true);
}
if is_equal(&isWithdrawEnabled, &Value::Bool(true)) {
withdrawEnabled = Value::Bool(true);
}
if !is_equal(&network, &Value::Null) {
add_element_to_object(&mut networks, &network, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), chain.clone());
m.insert("id".to_string(), networkId.clone());
m.insert("network".to_string(), network.clone());
m.insert("active".to_string(), active.clone());
m.insert("deposit".to_string(), isDepositEnabled.clone());
m.insert("withdraw".to_string(), isWithdrawEnabled.clone());
m.insert("fee".to_string(), withdrawalFee.clone());
m.insert("precision".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m
}));
}
}
}
let mut currencyEnabled: Value = self.safe_value_k(currency.clone(), "enabled", &[]);
let mut currencyActive: Value = Value::Bool(is_true(&(is_equal(¤cyEnabled, &Value::Bool(true)))) || is_true(&(is_true(&depositEnabled) || is_true(&withdrawEnabled))));
let mut minWithdrawalString: Value = self.safe_string_k(currency.clone(), "minWithdrawalAmount", &[]);
let mut minWithdrawal: Value = self.parse_number(crate::precise::Precise::stringMul(&minWithdrawalString, &precisionString), &[]);
let mut maxWithdrawalString: Value = self.safe_string_k(currency.clone(), "maxWithdrawalAmount", &[]);
let mut maxWithdrawal: Value = self.parse_number(crate::precise::Precise::stringMul(&maxWithdrawalString, &precisionString), &[]);
let mut minDepositString: Value = self.safe_string_k(currency.clone(), "minDepositAmount", &[]);
let mut minDeposit: Value = self.parse_number(crate::precise::Precise::stringMul(&minDepositString, &precisionString), &[]);
let mut isCrypto: bool = is_equal(&self.safe_string_k(currency.clone(), "currencyType", &[]), &Value::Str("Crypto".to_string()));
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("code".to_string(), code.clone());
m.insert("info".to_string(), currency.clone());
m.insert("name".to_string(), name.clone());
m.insert("active".to_string(), currencyActive.clone());
m.insert("deposit".to_string(), depositEnabled.clone());
m.insert("withdraw".to_string(), withdrawEnabled.clone());
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(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minWithdrawal.clone());
m.insert("max".to_string(), maxWithdrawal.clone());
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minDeposit.clone());
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("networks".to_string(), networks.clone());
m.insert("type".to_string(), ternary(is_true(&isCrypto), Value::Str("crypto".to_string()), Value::Str("other".to_string())));
m
}));
Value::Null
}
pub fn convert_from_real_amount(&self, mut code: Value, mut amount: Value) -> Value {
let mut currency: Value = self.currency(code.clone());
let mut precision: Value = self.safe_string_k(currency.clone(), "precision", &[]);
let mut amountString: Value = self.number_to_string(amount.clone());
let mut finalAmount: Value = crate::precise::Precise::stringDiv(&amountString, &precision);
return self.parse_number(finalAmount.clone(), &[]);
Value::Null
}
pub fn convert_to_real_amount(&self, mut code: Value, mut amount: Value) -> Value {
if is_equal(&code, &Value::Null) {
return amount;
} else if is_equal(&amount, &Value::Null) {
return Value::Null;
}
let mut currency: Value = self.currency(code.clone());
let mut precision: Value = self.safe_string_k(currency.clone(), "precision", &[]);
return crate::precise::Precise::stringMul(&amount, &precision);
Value::Null
}
pub fn amount_to_precision(&self, mut symbol: Value, mut amount: Value) -> Value {
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut market: Value = self.market(symbol.clone());
let mut oldPrecision: Value = self.safe_value_k(self.options.clone(), "oldPrecision", &[]);
if is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))) && is_true(&(!is_equal(&oldPrecision, &Value::Bool(true)))) {
amount = self.convert_from_real_amount(get_value(&market, &Value::Str("base".to_string())), amount.clone());
}
return self.super_amount_to_precision(symbol.clone(), amount.clone());
Value::Null
}
pub fn convert_from_raw_quantity(&self, mut symbol: Value, mut rawQuantity: Value, optional_args: &[Value]) -> Value {
let mut currencySide = get_arg(optional_args, 0, Value::Str("base".to_string()));
if is_equal(&self.safe_value_k(self.options.clone(), "oldPrecision", &[]), &Value::Bool(true)) {
return self.parse_number(rawQuantity.clone(), &[]);
}
symbol = self.safe_symbol(symbol.clone(), &[]);
let mut marketExists: Value = self.in_array(symbol.clone(), self.symbols.clone());
if !is_true(&marketExists) {
return self.parse_number(rawQuantity.clone(), &[]);
}
let mut market: Value = self.market(symbol.clone());
if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
return self.parse_number(self.convert_to_real_amount(self.safe_string(market.clone(), currencySide.clone(), &[]), rawQuantity.clone()), &[]);
}
return self.parse_number(rawQuantity.clone(), &[]);
Value::Null
}
pub fn convert_from_raw_cost(&self, mut symbol: Value, mut rawQuantity: Value) -> Value {
return self.convert_from_raw_quantity(symbol.clone(), rawQuantity.clone(), &[Value::Str("quote".to_string())]);
Value::Null
}
/*
* @method
* @name bitmex#fetchMarkets
* @description retrieves data on all markets for bitmex
* @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_getActive
* @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 response: Value = self.public_get_instrument_active(&[params.clone()]).await;
return self.parse_markets(response.clone());
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "underlying", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteCurrency", &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "settlCurrency", &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
// 'positionCurrency' may be empty ("", as Bitmex currently returns for ETHUSD)
// so let's take the settlCurrency first and then adjust if needed
let mut typ: Value = self.safe_string_k(market.clone(), "typ", &[]); // type definitions at: https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_get
let mut type_var: Value = Value::Null;
let mut swap: Value = Value::Bool(false);
let mut spot: Value = Value::Bool(false);
let mut future: Value = Value::Bool(false);
if is_equal(&typ, &Value::Str("FFWCSX".to_string())) {
type_var = Value::Str("swap".to_string());
swap = Value::Bool(true);
} else if is_equal(&typ, &Value::Str("IFXXXP".to_string())) {
type_var = Value::Str("spot".to_string());
spot = Value::Bool(true);
} else if is_equal(&typ, &Value::Str("FFCCSX".to_string())) || is_equal(&typ, &Value::Str("FFMCSX".to_string())) {
type_var = Value::Str("future".to_string());
future = Value::Bool(true);
} else if is_equal(&typ, &Value::Str("FFICSX".to_string())) {
// prediction markets (without any volume)
quoteId = baseId.clone();
baseId = self.safe_string_k(market.clone(), "rootSymbol", &[]);
type_var = Value::Str("future".to_string());
future = Value::Bool(true);
} else if is_equal(&typ, &Value::Str("FFSCSX".to_string())) {
type_var = Value::Str("swap".to_string());
swap = Value::Bool(true);
}
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut contract: Value = Value::Bool(is_true(&swap) || is_true(&future));
let mut contractSize: Value = Value::Null;
let mut isInverse: Value = self.safe_value_k(market.clone(), "isInverse", &[]); // this is true when BASE and SETTLE are same, i.e. BTC/XXX:BTC
let mut isQuanto: Value = self.safe_value_k(market.clone(), "isQuanto", &[]); // this is true when BASE and SETTLE are different, i.e. AXS/XXX:BTC
let mut linear: Value = ternary(is_true(&contract), Value::Bool((is_true(&(!is_equal(&isInverse, &Value::Bool(true)))) && is_true(&(!is_equal(&isQuanto, &Value::Bool(true)))))), Value::Null);
let mut status: Value = self.safe_string_k(market.clone(), "state", &[]);
let mut active: Value = Value::Bool(is_equal(&status, &Value::Str("Open".to_string()))); // Open, Settled, Unlisted
let mut expiry: Value = Value::Null;
let mut expiryDatetime: Value = Value::Null;
let mut symbol: Value = Value::Null;
if is_true(&spot) {
symbol = add(&add(&base, &Value::Str("/".to_string())), "e);
} else if is_true(&contract) {
symbol = add(&add(&add(&add(&base, &Value::Str("/".to_string())), "e), &Value::Str(":".to_string())), &settle);
if is_equal(&linear, &Value::Bool(true)) {
let mut multiplierString: Value = self.safe_string2(market.clone(), Value::Str("underlyingToPositionMultiplier".to_string()), Value::Str("underlyingToSettleMultiplier".to_string()), &[]);
contractSize = crate::precise::Precise::stringAbs(&crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &multiplierString));
} else {
contractSize = crate::precise::Precise::stringAbs(&self.safe_string_k(market.clone(), "multiplier", &[]));
}
expiryDatetime = self.safe_string2(market.clone(), Value::Str("expiry".to_string()), Value::Str("closingTimestamp".to_string()), &[]);
expiry = self.parse8601(expiryDatetime.clone());
if !is_equal(&expiry, &Value::Null) && is_true(&future) {
symbol = add(&add(&symbol, &Value::Str("-".to_string())), &self.yymmdd(expiry.clone(), &[]));
}
} else {
// for index/exotic markets, default to id
symbol = id.clone();
}
let mut positionId: Value = self.safe_string2(market.clone(), Value::Str("positionCurrency".to_string()), Value::Str("underlying".to_string()), &[]);
let mut position: Value = self.safe_currency_code(positionId.clone(), &[]);
let mut positionIsQuote: bool = is_equal(&position, "e);
let mut maxOrderQty: Value = self.safe_number_k(market.clone(), "maxOrderQty", &[]);
let mut initMargin: Value = self.safe_string_k(market.clone(), "initMargin", &[Value::Str("1".to_string())]);
let mut maxLeverage: Value = self.parse_number(crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &initMargin), &[]);
// subtype should be undefined for spot markets
if is_true(&spot) {
isInverse = Value::Null;
isQuanto = Value::Null;
linear = Value::Null;
}
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" parseMarket() requires a symbol".to_string()))));
}
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(), symbol.clone());
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(), type_var.clone());
m.insert("spot".to_string(), spot.clone());
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), swap.clone());
m.insert("future".to_string(), future.clone());
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active.clone());
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), linear.clone());
m.insert("inverse".to_string(), isInverse.clone());
m.insert("quanto".to_string(), isQuanto.clone());
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "takerFee", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "makerFee", &[]));
m.insert("contractSize".to_string(), self.parse_number(contractSize.clone(), &[]));
m.insert("expiry".to_string(), expiry.clone());
m.insert("expiryDatetime".to_string(), expiryDatetime.clone());
m.insert("strike".to_string(), self.safe_number_k(market.clone(), "optionStrikePrice", &[]));
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_number_k(market.clone(), "lotSize", &[]));
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(), ternary(is_true(&contract), self.parse_number(Value::Str("1".to_string()), &[]), Value::Null));
m.insert("max".to_string(), ternary(is_true(&contract), maxLeverage.clone(), Value::Null));
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(), ternary(is_true(&positionIsQuote), Value::Null, maxOrderQty.clone()));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), self.safe_number_k(market.clone(), "maxPrice", &[]));
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(), ternary(is_true(&positionIsQuote), maxOrderQty.clone(), Value::Null));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market.clone());
m
})]);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// [
// {
// "account":1455728,
// "currency":"XBt",
// "riskLimit":1000000000000,
// "prevState":"",
// "state":"",
// "action":"",
// "amount":263542,
// "pendingCredit":0,
// "pendingDebit":0,
// "confirmedDebit":0,
// "prevRealisedPnl":0,
// "prevUnrealisedPnl":0,
// "grossComm":0,
// "grossOpenCost":0,
// "grossOpenPremium":0,
// "grossExecCost":0,
// "grossMarkValue":0,
// "riskValue":0,
// "taxableMargin":0,
// "initMargin":0,
// "maintMargin":0,
// "sessionMargin":0,
// "targetExcessMargin":0,
// "varMargin":0,
// "realisedPnl":0,
// "unrealisedPnl":0,
// "indicativeTax":0,
// "unrealisedProfit":0,
// "syntheticMargin":null,
// "walletBalance":263542,
// "marginBalance":263542,
// "marginBalancePcnt":1,
// "marginLeverage":0,
// "marginUsedPcnt":0,
// "excessMargin":263542,
// "excessMarginPcnt":1,
// "availableMargin":263542,
// "withdrawableMargin":263542,
// "timestamp":"2020-08-03T12:01:01.246Z",
// "grossLastValue":0,
// "commission":null
// }
// ]
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_381: bool = true;
while { if !__for_first_381 { i = add(&i, &Value::Int(1)); } __for_first_381 = false; is_less_than(&i, &get_array_length(&response)) } {
let mut balance: Value = get_value(&response, &i);
let mut balance: Value = get_value(&response, &i);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
let mut free: Value = self.safe_string_k(balance.clone(), "availableMargin", &[]);
let mut total: Value = self.safe_string_k(balance.clone(), "marginBalance", &[]);
add_element_to_object(&mut account, &Value::Str("free".to_string()), self.convert_to_real_amount(code.clone(), free.clone()));
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.convert_to_real_amount(code.clone(), total.clone()));
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &code, account.clone());
}
}
}
return self.safe_balance(result.clone());
Value::Null
}
/*
* @method
* @name bitmex#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.bitmex.com/api/explorer/#!/User/User_getMargin
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("all".to_string()));
m
});
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_user_margin(&[__ws_arg_0]).await;
return self.parse_balance(response.clone());
Value::Null
}
/*
* @method
* @name bitmex#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.bitmex.com/api/explorer/#!/OrderBook/OrderBook_getL2
* @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
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("depth".to_string()), limit.clone());
}
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_order_book_l2(&[__ws_arg_1]).await;
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("bids".to_string(), Value::List(vec![]));
m.insert("asks".to_string(), Value::List(vec![]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("nonce".to_string(), Value::Null);
m
});
let mut orders: Value = self.to_array(response.clone());
{
let mut i: Value = Value::Int(0);
let mut __for_first_382: bool = true;
while { if !__for_first_382 { i = add(&i, &Value::Int(1)); } __for_first_382 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut order: Value = get_value(&orders, &i);
let mut order: Value = get_value(&orders, &i);
let mut side: Value = ternary(is_true(&(is_equal(&get_value(&order, &Value::Str("side".to_string())), &Value::Str("Sell".to_string())))), Value::Str("asks".to_string()), Value::Str("bids".to_string()));
let mut amount: Value = self.convert_from_raw_quantity(symbol.clone(), self.safe_string_k(order.clone(), "size", &[]), &[]);
let mut price: Value = self.safe_number_k(order.clone(), "price", &[]);
// https://github.com/ccxt/ccxt/issues/4926
// https://github.com/ccxt/ccxt/issues/4927
// the exchange sometimes returns null price in the orderbook
if !is_equal(&price, &Value::Null) {
crate::runtime::append_to_object_array(&mut result, &side, Value::List(vec![price.clone(), amount.clone()]));
}
}
}
{ let __be_tmp = self.sort_by(get_value(&result, &Value::Str("bids".to_string())), Value::Int(0), &[Value::Bool(true)]); add_element_to_object(&mut result, &Value::Str("bids".to_string()), __be_tmp); };
{ let __be_tmp = self.sort_by(get_value(&result, &Value::Str("asks".to_string())), Value::Int(0), &[]); add_element_to_object(&mut result, &Value::Str("asks".to_string()), __be_tmp); };
return result;
Value::Null
}
/*
* @method
* @name bitmex#fetchOrder
* @description fetches information on an order made by the user
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_getOrders
* @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
}));
let mut filter: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("filter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderID".to_string(), id.clone());
m
}));
m
});
let mut response: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, self.deep_extend(filter.clone(), &[params.clone()])]).await;
let mut numResults: Value = get_array_length(&response);
if is_equal(&numResults, &Value::Int(1)) {
return get_value(&response, &Value::Int(0));
}
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&add(&self.id, &Value::Str(": The order ".to_string())), &id), &Value::Str(" not found.".to_string()))));
Value::Null
}
/*
* @method
* @name bitmex#fetchOrders
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_getOrders
* @description fetches information on multiple orders made by the user
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the earliest time in ms to fetch orders for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {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(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrders".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_dynamic(Value::Str("fetchOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Int(100)]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
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("startTime".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone());
}
let mut until: Value = self.safe_integer2(params.clone(), Value::Str("until".to_string()), Value::Str("endTime".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
request = self.deep_extend(request.clone(), &[params.clone()]);
// why the hassle? urlencode in python is kinda broken for nested dicts.
// E.g. self.urlencode({"filter": {"open": True}}, &[]) will return "filter={'open':+True}"
// Bitmex doesn't like that. Hence resorting to this hack.
if is_true(&Value::Bool(in_op(&request, &Value::Str("filter".to_string())))) {
{ let __be_tmp = self.json(get_value(&request, &Value::Str("filter".to_string()))); add_element_to_object(&mut request, &Value::Str("filter".to_string()), __be_tmp); };
}
let mut response: Value = self.private_get_order(&[request.clone()]).await;
return self.parse_orders(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_getOrders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("filter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("open".to_string(), Value::Bool(true));
m
}));
m
});
return self.fetch_orders(&[symbol.clone(), since.clone(), limit.clone(), self.deep_extend(request.clone(), &[params.clone()])]).await;
Value::Null
}
/*
* @method
* @name bitmex#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_getOrders
* @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_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
}));
// Bitmex barfs if you set 'open': false in the filter...
let mut orders: Value = self.fetch_orders(&[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(orders.clone(), Value::Str("status".to_string()), &[Value::List(vec![Value::Str("closed".to_string()), Value::Str("canceled".to_string())]), Value::Bool(false)]);
Value::Null
}
/*
* @method
* @name bitmex#fetchMyTrades
* @description fetch all trades made by the user
* @see https://www.bitmex.com/api/explorer/#!/Execution/Execution_getTradeHistory
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".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_dynamic(Value::Str("fetchMyTrades".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Int(100)]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
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("startTime".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), crate::runtime::Math::min(&Value::Int(500), &limit));
}
let mut until: Value = self.safe_integer2(params.clone(), Value::Str("until".to_string()), Value::Str("endTime".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
request = self.deep_extend(request.clone(), &[params.clone()]);
// why the hassle? urlencode in python is kinda broken for nested dicts.
// E.g. self.urlencode({"filter": {"open": True}}, &[]) will return "filter={'open':+True}"
// Bitmex doesn't like that. Hence resorting to this hack.
if is_true(&Value::Bool(in_op(&request, &Value::Str("filter".to_string())))) {
{ let __be_tmp = self.json(get_value(&request, &Value::Str("filter".to_string()))); add_element_to_object(&mut request, &Value::Str("filter".to_string()), __be_tmp); };
}
let mut response: Value = self.private_get_execution_trade_history(&[request.clone()]).await;
return self.parse_trades(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Withdrawal".to_string(), Value::Str("transaction".to_string()));
m.insert("RealisedPNL".to_string(), Value::Str("margin".to_string()));
m.insert("UnrealisedPNL".to_string(), Value::Str("margin".to_string()));
m.insert("Deposit".to_string(), Value::Str("transaction".to_string()));
m.insert("Transfer".to_string(), Value::Str("transfer".to_string()));
m.insert("AffiliatePayout".to_string(), Value::Str("referral".to_string()));
m.insert("SpotTrade".to_string(), Value::Str("trade".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "transactID": "69573da3-7744-5467-3207-89fd6efe7a47",
// "account": 24321,
// "currency": "XBt",
// "transactType": "Withdrawal", // "AffiliatePayout", "Transfer", "Deposit", "RealisedPNL", ...
// "amount": -1000000,
// "fee": 300000,
// "transactStatus": "Completed", // "Canceled", ...
// "address": "1Ex4fkF4NhQaQdRWNoYpqiPbDBbq18Kdd9",
// "tx": "3BMEX91ZhhKoWtsH9QRb5dNXnmnGpiEetA",
// "text": "",
// "transactTime": "2017-03-21T20:05:14.388Z",
// "walletBalance": 0, // balance after
// "marginBalance": null,
// "timestamp": "2017-03-22T13:09:23.514Z"
// }
//
// ButMEX returns the unrealized pnl from the wallet history endpoint.
// The unrealized pnl transaction has an empty timestamp.
// It is not related to historical pnl it has status set to "Pending".
// Therefore it's not a part of the history at all.
// https://github.com/ccxt/ccxt/issues/6047
//
// {
// "transactID":"00000000-0000-0000-0000-000000000000",
// "account":121210,
// "currency":"XBt",
// "transactType":"UnrealisedPNL",
// "amount":-5508,
// "fee":0,
// "transactStatus":"Pending",
// "address":"XBTUSD",
// "tx":"",
// "text":"",
// "transactTime":null, # ←---------------------------- null
// "walletBalance":139198767,
// "marginBalance":139193259,
// "timestamp":null # ←---------------------------- null
// }
//
let mut id: Value = self.safe_string_k(item.clone(), "transactID", &[]);
let mut account: Value = self.safe_string_k(item.clone(), "account", &[]);
let mut referenceId: Value = self.safe_string_k(item.clone(), "tx", &[]);
let mut referenceAccount: Value = Value::Null;
let mut type_var: Value = self.parse_ledger_entry_type(self.safe_string_k(item.clone(), "transactType", &[]));
let mut currencyId: Value = self.safe_string_k(item.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
currency = self.safe_currency(currencyId.clone(), &[currency.clone()]);
let mut amountString: Value = self.safe_string_k(item.clone(), "amount", &[]);
let mut amount: Value = self.convert_to_real_amount(code.clone(), amountString.clone());
let mut timestamp: Value = self.parse8601(self.safe_string_k(item.clone(), "transactTime", &[]));
if is_equal(×tamp, &Value::Null) {
// https://github.com/ccxt/ccxt/issues/6047
// set the timestamp to zero, 1970 Jan 1 00:00:00
// for unrealized pnl and other transactions without a timestamp
timestamp = Value::Int(0); // see comments above
}
let mut fee: Value = Value::Null;
let mut feeCost: Value = self.safe_string_k(item.clone(), "fee", &[]);
if !is_equal(&feeCost, &Value::Null) {
feeCost = self.convert_to_real_amount(code.clone(), feeCost.clone());
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCost.clone(), &[]));
m.insert("currency".to_string(), code.clone());
m
});
}
let mut after: Value = self.safe_string_k(item.clone(), "walletBalance", &[]);
if !is_equal(&after, &Value::Null) {
after = self.convert_to_real_amount(code.clone(), after.clone());
}
let mut before: Value = self.parse_number(crate::precise::Precise::stringSub(&self.number_to_string(after.clone()), &self.number_to_string(amount.clone())), &[]);
let mut direction: Value = Value::Null;
if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".to_string()))) {
direction = Value::Str("out".to_string());
amount = self.convert_to_real_amount(code.clone(), crate::precise::Precise::stringAbs(&amountString));
} else {
direction = Value::Str("in".to_string());
}
let mut status: Value = self.parse_transaction_status(self.safe_string_k(item.clone(), "transactStatus", &[]));
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), id.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("direction".to_string(), direction.clone());
m.insert("account".to_string(), account.clone());
m.insert("referenceId".to_string(), referenceId.clone());
m.insert("referenceAccount".to_string(), referenceAccount.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("before".to_string(), before.clone());
m.insert("after".to_string(), self.parse_number(after.clone(), &[]));
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[currency.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://www.bitmex.com/api/explorer/#!/User/User_getWalletHistory
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
//
// if (since !== undefined) {
// // date-based pagination not supported
// }
//
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone());
}
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
}
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_user_wallet_history(&[__ws_arg_2]).await;
return self.parse_ledger(response.clone(), &[currency.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchDepositsWithdrawals
* @description fetch history of deposits and withdrawals
* @see https://www.bitmex.com/api/explorer/#!/User/User_getWalletHistory
* @param {string} [code] unified currency code for the currency of the deposit/withdrawals, default is undefined
* @param {int} [since] timestamp in ms of the earliest deposit/withdrawal, default is undefined
* @param {int} [limit] max number of deposit/withdrawals to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits_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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("all".to_string()));
m
});
//
// if (since !== undefined) {
// // date-based pagination not supported
// }
//
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone());
}
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_user_wallet_history(&[__ws_arg_3]).await;
let mut transactions: Value = self.filter_by_array(response.clone(), Value::Str("transactType".to_string()), &[Value::List(vec![Value::Str("Withdrawal".to_string()), Value::Str("Deposit".to_string())]), Value::Bool(false)]);
return self.parse_transactions(transactions.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("Confirmed".to_string(), Value::Str("pending".to_string()));
m.insert("Canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("Completed".to_string(), Value::Str("ok".to_string()));
m.insert("Pending".to_string(), Value::Str("pending".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);
//
// {
// "transactID": "ffe699c2-95ee-4c13-91f9-0faf41daec25",
// "account": 123456,
// "currency": "XBt",
// "network":'', // "tron" for USDt, etc...
// "transactType": "Withdrawal",
// "amount": -100100000,
// "fee": 100000,
// "transactStatus": "Completed",
// "address": "385cR5DM96n1HvBDMzLHPYcw89fZAXULJP",
// "tx": "3BMEXabcdefghijklmnopqrstuvwxyz123",
// "text": '',
// "transactTime": "2019-01-02T01:00:00.000Z",
// "walletBalance": 99900000, // this field might be inexistent
// "marginBalance": None, // this field might be inexistent
// "timestamp": "2019-01-02T13:00:00.000Z"
// }
//
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "currency", &[]);
currency = self.safe_currency(currencyId.clone(), &[currency.clone()]);
// For deposits, transactTime == timestamp
// For withdrawals, transactTime is submission, timestamp is processed
let mut transactTime: Value = self.parse8601(self.safe_string_k(transaction.clone(), "transactTime", &[]));
let mut timestamp: Value = self.parse8601(self.safe_string_k(transaction.clone(), "timestamp", &[]));
let mut type_var: Value = self.safe_string_lower(transaction.clone(), Value::Str("transactType".to_string()), &[]);
// Deposits have no from address or to address, withdrawals have both
let mut address: Value = Value::Null;
let mut addressFrom: Value = Value::Null;
let mut addressTo: Value = Value::Null;
if is_equal(&type_var, &Value::Str("withdrawal".to_string())) {
address = self.safe_string_k(transaction.clone(), "address", &[]);
addressFrom = self.safe_string_k(transaction.clone(), "tx", &[]);
addressTo = address.clone();
} else if is_equal(&type_var, &Value::Str("deposit".to_string())) {
addressTo = self.safe_string_k(transaction.clone(), "address", &[]);
addressFrom = self.safe_string_k(transaction.clone(), "tx", &[]);
}
let mut amountString: Value = self.safe_string_k(transaction.clone(), "amount", &[]);
let mut amountStringAbs: Value = crate::precise::Precise::stringAbs(&amountString);
let mut amount: Value = self.convert_to_real_amount(get_value(¤cy, &Value::Str("code".to_string())), amountStringAbs.clone());
let mut feeCostString: Value = self.safe_string_k(transaction.clone(), "fee", &[]);
let mut feeCost: Value = self.convert_to_real_amount(get_value(¤cy, &Value::Str("code".to_string())), feeCostString.clone());
let mut status: Value = self.safe_string_k(transaction.clone(), "transactStatus", &[]);
if !is_equal(&status, &Value::Null) {
status = self.parse_transaction_status(status.clone());
}
let mut code: Value = get_value(¤cy, &Value::Str("code".to_string()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "transactID", &[]));
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "tx", &[]));
m.insert("type".to_string(), type_var.clone());
m.insert("currency".to_string(), code.clone());
m.insert("network".to_string(), self.network_id_to_code(&[self.safe_string_k(transaction.clone(), "network", &[]), code.clone()]));
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("status".to_string(), status.clone());
m.insert("timestamp".to_string(), transactTime.clone());
m.insert("datetime".to_string(), self.iso8601(transactTime.clone()));
m.insert("address".to_string(), address.clone());
m.insert("addressFrom".to_string(), addressFrom.clone());
m.insert("addressTo".to_string(), addressTo.clone());
m.insert("tag".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("updated".to_string(), timestamp.clone());
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("code".to_string())));
m.insert("cost".to_string(), self.parse_number(feeCost.clone(), &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
});
Value::Null
}
/*
* @method
* @name bitmex#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_get
* @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 __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_instrument(&[__ws_arg_4]).await;
let mut ticker: Value = self.safe_value(response.clone(), Value::Int(0), &[]);
if is_equal(&ticker, &Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&add(&add(&self.id, &Value::Str(" fetchTicker() symbol ".to_string())), &symbol), &Value::Str(" not found".to_string()))));
}
return self.parse_ticker(ticker.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_getActiveAndIndices
* @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;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut response: Value = self.public_get_instrument_active_and_indices(&[params.clone()]).await;
// same response as under "fetchMarkets"
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut rawTickers: Value = self.to_array(response.clone());
{
let mut i: Value = Value::Int(0);
let mut __for_first_383: bool = true;
while { if !__for_first_383 { i = add(&i, &Value::Int(1)); } __for_first_383 = false; is_less_than(&i, &get_array_length(&rawTickers)) } {
let mut ticker: Value = self.parse_ticker(get_value(&rawTickers, &i), &[]);
let mut symbol: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
if !is_equal(&symbol, &Value::Null) {
add_element_to_object(&mut result, &symbol, ticker.clone());
}
}
}
return self.filter_by_array_tickers(result.clone(), Value::Str("symbol".to_string()), &[symbols.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);
// see response sample under "fetchMarkets" because same endpoint is being used here
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(ticker.clone(), "timestamp", &[]));
let mut open: Value = self.safe_string_k(ticker.clone(), "prevPrice24h", &[]);
let mut last: Value = self.safe_string_k(ticker.clone(), "lastPrice", &[]);
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.safe_string_k(ticker.clone(), "highPrice", &[]));
m.insert("low".to_string(), self.safe_string_k(ticker.clone(), "lowPrice", &[]));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bidPrice", &[]));
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "askPrice", &[]));
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), self.safe_string_k(ticker.clone(), "vwap", &[]));
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(), self.safe_string_k(ticker.clone(), "homeNotional24h", &[]));
m.insert("quoteVolume".to_string(), self.safe_string_k(ticker.clone(), "foreignNotional24h", &[]));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "markPrice", &[]));
m.insert("info".to_string(), ticker.clone());
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "timestamp":"2015-09-25T13:38:00.000Z",
// "symbol":"XBTUSD",
// "open":237.45,
// "high":237.45,
// "low":237.45,
// "close":237.45,
// "trades":0,
// "volume":0,
// "vwap":null,
// "lastSize":null,
// "turnover":0,
// "homeNotional":0,
// "foreignNotional":0
// }
//
let mut marketId: Value = self.safe_string_k(ohlcv.clone(), "symbol", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut volume: Value = self.convert_from_raw_quantity(get_value(&market, &Value::Str("symbol".to_string())), self.safe_string_k(ohlcv.clone(), "volume", &[]), &[]);
return Value::List(vec![self.parse8601(self.safe_string_k(ohlcv.clone(), "timestamp", &[])), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), volume.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.bitmex.com/api/explorer/#!/Trade/Trade_getBucketed
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".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("fetchOHLCV".to_string()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), params.clone()]).await;
}
// send JSON key/value pairs, such as {"key": "value"}
// filter by individual fields and do advanced queries on timestamps
// let filter: Dict = { 'key': 'value' }
// send a bare series (e.g. XBU) to nearest expiring contract in that series
// you can also send a timeframe, e.g. XBU:monthly
// timeframes: daily, weekly, monthly, quarterly, and biquarterly
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("binSize".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("partial".to_string(), Value::Bool(true));
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone()); // default 100, max 500
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
let mut duration: Value = multiply(&self.parse_timeframe(timeframe.clone()), &Value::Int(1000));
let mut useOpenTimestamp: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".to_string()), Value::Str("useOpenTimestamp".to_string()), &[Value::Bool(true)]); useOpenTimestamp = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
// if since is not set, they will return candles starting from 2017-01-01
if !is_equal(&since, &Value::Null) {
let mut timestamp: Value = since.clone();
if is_true(&useOpenTimestamp) {
timestamp = self.sum(&[timestamp.clone(), duration.clone()]);
}
let mut startTime: Value = self.iso8601(timestamp.clone());
add_element_to_object(&mut request, &Value::Str("startTime".to_string()), startTime.clone()); // starting date filter for results
} else {
add_element_to_object(&mut request, &Value::Str("reverse".to_string()), Value::Bool(true));
}
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_trade_bucketed(&[__ws_arg_5]).await;
//
// [
// {"timestamp":"2015-09-25T13:38:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0},
// {"timestamp":"2015-09-25T13:39:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0},
// {"timestamp":"2015-09-25T13:40:00.000Z","symbol":"XBTUSD","open":237.45,"high":237.45,"low":237.45,"close":237.45,"trades":0,"volume":0,"vwap":null,"lastSize":null,"turnover":0,"homeNotional":0,"foreignNotional":0}
// ]
//
let mut result: Value = self.parse_ohlc_vs(self.to_array(response.clone()), &[market.clone(), timeframe.clone(), since.clone(), limit.clone()]);
if is_true(&useOpenTimestamp) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_384: bool = true;
while { if !__for_first_384 { i = add(&i, &Value::Int(1)); } __for_first_384 = false; is_less_than(&i, &get_array_length(&result)) } {
{ let __be_tmp = subtract(&self.parse_to_int(get_value(&get_value(&result, &i), &Value::Int(0))), &duration); add_element_to_object(get_value_mut(&mut result, &i), &Value::Int(0), __be_tmp); };
}
}
}
return result;
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)
//
// {
// "timestamp": "2018-08-28T00:00:02.735Z",
// "symbol": "XBTUSD",
// "side": "Buy",
// "size": 2000,
// "price": 6906.5,
// "tickDirection": "PlusTick",
// "trdMatchID": "b9a42432-0a46-6a2f-5ecc-c32e9ca4baf8",
// "grossValue": 28958000,
// "homeNotional": 0.28958,
// "foreignNotional": 2000
// }
//
// fetchMyTrades (private)
//
// {
// "execID": "string",
// "orderID": "string",
// "clOrdID": "string",
// "clOrdLinkID": "string",
// "account": 0,
// "symbol": "string",
// "side": "string",
// "lastQty": 0,
// "lastPx": 0,
// "underlyingLastPx": 0,
// "lastMkt": "string",
// "lastLiquidityInd": "string",
// "simpleOrderQty": 0,
// "orderQty": 0,
// "price": 0,
// "displayQty": 0,
// "stopPx": 0,
// "pegOffsetValue": 0,
// "pegPriceType": "string",
// "currency": "string",
// "settlCurrency": "string",
// "execType": "string",
// "ordType": "string",
// "timeInForce": "string",
// "execInst": "string",
// "contingencyType": "string",
// "exDestination": "string",
// "ordStatus": "string",
// "triggered": "string",
// "workingIndicator": true,
// "ordRejReason": "string",
// "simpleLeavesQty": 0,
// "leavesQty": 0,
// "simpleCumQty": 0,
// "cumQty": 0,
// "avgPx": 0,
// "commission": 0,
// "tradePublishIndicator": "string",
// "multiLegReportingType": "string",
// "text": "string",
// "trdMatchID": "string",
// "execCost": 0,
// "execComm": 0,
// "homeNotional": 0,
// "foreignNotional": 0,
// "transactTime": "2019-03-05T12:47:02.762Z",
// "timestamp": "2019-03-05T12:47:02.762Z"
// }
//
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(trade.clone(), "timestamp", &[]));
let mut priceString: Value = self.safe_string2(trade.clone(), Value::Str("avgPx".to_string()), Value::Str("price".to_string()), &[]);
let mut amountString: Value = self.convert_from_raw_quantity(symbol.clone(), self.safe_string2(trade.clone(), Value::Str("size".to_string()), Value::Str("lastQty".to_string()), &[]), &[]);
let mut execCost: Value = self.number_to_string(self.convert_from_raw_cost(symbol.clone(), self.safe_string_k(trade.clone(), "execCost", &[])));
let mut id: Value = self.safe_string_k(trade.clone(), "trdMatchID", &[]);
let mut order: Value = self.safe_string_k(trade.clone(), "orderID", &[]);
let mut side: Value = self.safe_string_lower(trade.clone(), Value::Str("side".to_string()), &[]);
// price * amount doesn't work for all symbols (e.g. XBT, ETH)
let mut fee: Value = Value::Null;
let mut feeCostString: Value = self.number_to_string(self.convert_from_raw_cost(symbol.clone(), self.safe_string_k(trade.clone(), "execComm", &[])));
if !is_equal(&feeCostString, &Value::Null) {
let mut currencyId: Value = self.safe_string2(trade.clone(), Value::Str("settlCurrency".to_string()), Value::Str("currency".to_string()), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCostString.clone());
m.insert("currency".to_string(), self.safe_currency_code(currencyId.clone(), &[]));
m.insert("rate".to_string(), self.safe_string_k(trade.clone(), "commission", &[]));
m
});
}
// Trade or Funding
let mut execType: Value = self.safe_string_k(trade.clone(), "execType", &[]);
let mut takerOrMaker: Value = Value::Null;
if !is_equal(&feeCostString, &Value::Null) && is_equal(&execType, &Value::Str("Trade".to_string())) {
takerOrMaker = ternary(is_true(&crate::precise::Precise::stringLt(&feeCostString, &Value::Str("0".to_string()))), Value::Str("maker".to_string()), Value::Str("taker".to_string()));
}
let mut type_var: Value = self.safe_string_lower(trade.clone(), Value::Str("ordType".to_string()), &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("symbol".to_string(), symbol.clone());
m.insert("id".to_string(), id.clone());
m.insert("order".to_string(), order.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("takerOrMaker".to_string(), takerOrMaker.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), priceString.clone());
m.insert("cost".to_string(), crate::precise::Precise::stringAbs(&execCost));
m.insert("amount".to_string(), amountString.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[market.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("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("DoneForDay".to_string(), Value::Str("open".to_string()));
m.insert("Canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("PendingCancel".to_string(), Value::Str("open".to_string()));
m.insert("PendingNew".to_string(), Value::Str("open".to_string()));
m.insert("Rejected".to_string(), Value::Str("rejected".to_string()));
m.insert("Expired".to_string(), Value::Str("expired".to_string()));
m.insert("Stopped".to_string(), Value::Str("open".to_string()));
m.insert("Untriggered".to_string(), Value::Str("open".to_string()));
m.insert("Triggered".to_string(), Value::Str("open".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.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("Day".to_string(), Value::Str("Day".to_string()));
m.insert("GoodTillCancel".to_string(), Value::Str("GTC".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_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "orderID":"56222c7a-9956-413a-82cf-99f4812c214b",
// "clOrdID":"",
// "clOrdLinkID":"",
// "account":1455728,
// "symbol":"XBTUSD",
// "side":"Sell",
// "simpleOrderQty":null,
// "orderQty":1,
// "price":40000,
// "displayQty":null,
// "stopPx":null,
// "pegOffsetValue":null,
// "pegPriceType":"",
// "currency":"USD",
// "settlCurrency":"XBt",
// "ordType":"Limit",
// "timeInForce":"GoodTillCancel",
// "execInst":"",
// "contingencyType":"",
// "exDestination":"XBME",
// "ordStatus":"New",
// "triggered":"",
// "workingIndicator":true,
// "ordRejReason":"",
// "simpleLeavesQty":null,
// "leavesQty":1,
// "simpleCumQty":null,
// "cumQty":0,
// "avgPx":null,
// "multiLegReportingType":"SingleSecurity",
// "text":"Submitted via API.",
// "transactTime":"2021-01-02T21:38:49.246Z",
// "timestamp":"2021-01-02T21:38:49.246Z"
// }
//
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 qty: Value = self.safe_string_k(order.clone(), "orderQty", &[]);
let mut cost: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut isInverse: Value = Value::Bool(false);
if is_equal(&marketId, &Value::Null) {
let mut defaultSubType: Value = self.safe_string_k(self.options.clone(), "defaultSubType", &[Value::Str("linear".to_string())]);
isInverse = Value::Bool(is_equal(&defaultSubType, &Value::Str("inverse".to_string())));
} else {
isInverse = self.safe_bool_k(market.clone(), "inverse", &[Value::Bool(false)]);
}
if is_true(&isInverse) {
cost = self.convert_from_raw_quantity(symbol.clone(), qty.clone(), &[]);
} else {
amount = self.convert_from_raw_quantity(symbol.clone(), qty.clone(), &[]);
}
let mut average: Value = self.safe_string_k(order.clone(), "avgPx", &[]);
let mut filled: Value = Value::Null;
let mut cumQty: Value = self.number_to_string(self.convert_from_raw_quantity(symbol.clone(), self.safe_string_k(order.clone(), "cumQty", &[]), &[]));
if is_true(&isInverse) {
filled = crate::precise::Precise::stringDiv(&cumQty, &average);
} else {
filled = cumQty.clone();
}
let mut execInst: Value = self.safe_string_k(order.clone(), "execInst", &[Value::Str("".to_string())]);
let mut postOnly: Value = Value::Null;
let mut reduceOnly: Value = Value::Null;
if is_greater_than(&get_array_length(&execInst), &Value::Int(0)) {
postOnly = Value::Bool(is_greater_than_or_equal(&get_index_of(&execInst, &Value::Str("ParticipateDoNotInitiate".to_string())), &Value::Int(0)));
reduceOnly = Value::Bool(is_true(&(is_greater_than_or_equal(&get_index_of(&execInst, &Value::Str("ReduceOnly".to_string())), &Value::Int(0)))) || is_true(&(is_greater_than_or_equal(&get_index_of(&execInst, &Value::Str("Close".to_string())), &Value::Int(0)))));
}
let mut timestamp: Value = self.parse8601(self.safe_string_k(order.clone(), "timestamp", &[]));
let mut triggerPrice: Value = self.safe_number_k(order.clone(), "stopPx", &[]);
let mut remaining: Value = self.safe_string_k(order.clone(), "leavesQty", &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderID", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "clOrdID", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), self.parse8601(self.safe_string_k(order.clone(), "transactTime", &[])));
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), self.safe_string_lower(order.clone(), Value::Str("ordType".to_string()), &[]));
m.insert("timeInForce".to_string(), self.parse_time_in_force(self.safe_string_k(order.clone(), "timeInForce", &[])));
m.insert("postOnly".to_string(), postOnly.clone());
m.insert("reduceOnly".to_string(), reduceOnly.clone());
m.insert("side".to_string(), self.safe_string_lower(order.clone(), Value::Str("side".to_string()), &[]));
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
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(), self.convert_from_raw_quantity(symbol.clone(), remaining.clone(), &[]));
m.insert("status".to_string(), self.parse_order_status(self.safe_string_k(order.clone(), "ordStatus", &[])));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.bitmex.com/api/explorer/#!/Trade/Trade_get
* @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
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".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_dynamic(Value::Str("fetchTrades".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).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("startTime".to_string()), self.iso8601(since.clone()));
} else {
// by default reverse=false, i.e. trades are fetched since the time of market inception (year 2015 for XBTUSD)
add_element_to_object(&mut request, &Value::Str("reverse".to_string()), Value::Bool(true));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), crate::runtime::Math::min(&limit, &Value::Int(1000))); // api maximum 1000
}
let mut until: Value = self.safe_integer2(params.clone(), Value::Str("until".to_string()), Value::Str("endTime".to_string()), &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_trade(&[__ws_arg_6]).await;
return self.parse_trades(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#createOrder
* @description create a trade order
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_new
* @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 {object} [params.triggerPrice] the price at which a trigger order is triggered at
* @param {object} [params.triggerDirection] the direction whenever the trigger happens with relation to price - 'ascending' or 'descending'
* @param {float} [params.trailingAmount] the quote amount to trail away from the current market price
* @returns {object} an [order structure]{@link https://github.com/ccxt/ccxt/wiki/Manual#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 orderType: Value = self.capitalize(type_var.clone());
let mut capitalizeOrderType: Value = orderType.clone();
let mut reduceOnly: Value = self.safe_value_k(params.clone(), "reduceOnly", &[]);
if !is_equal(&reduceOnly, &Value::Null) {
if is_true(&(!is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)))) && is_true(&(!is_equal(&get_value(&market, &Value::Str("future".to_string())), &Value::Bool(true)))) {
panic!("{}", crate::exchange_errors::invalid_order(add(&add(&add(&self.id, &Value::Str(" createOrder() does not support reduceOnly for ".to_string())), &get_value(&market, &Value::Str("type".to_string()))), &Value::Str(" orders, reduceOnly orders are supported for swap and future markets only".to_string()))));
}
}
let mut postOnly: Value = self.safe_bool_k(params.clone(), "postOnly", &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("reduceOnly".to_string()), Value::Str("postOnly".to_string())]), &[]);
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("CCXT".to_string())]);
let mut qty: Value = self.parse_to_int(self.amount_to_precision(symbol.clone(), amount.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(), self.capitalize(side.clone()));
m.insert("orderQty".to_string(), qty.clone());
m.insert("ordType".to_string(), capitalizeOrderType.clone());
m.insert("text".to_string(), brokerId.clone());
m
});
let mut execInstructions: Value = Value::List(vec![]);
if is_equal(&reduceOnly, &Value::Bool(true)) {
append_to_array(&mut execInstructions, Value::Str("ReduceOnly".to_string()));
}
if is_equal(&postOnly, &Value::Bool(true)) {
append_to_array(&mut execInstructions, Value::Str("ParticipateDoNotInitiate".to_string()));
}
let mut execInstLength: Value = get_array_length(&execInstructions);
if is_greater_than(&execInstLength, &Value::Int(0)) {
add_element_to_object(&mut request, &Value::Str("execInst".to_string()), join(&execInstructions, &Value::Str(",".to_string())));
}
// support for unified trigger format
let mut triggerPrice: Value = self.safe_number_n(params.clone(), Value::List(vec![Value::Str("triggerPrice".to_string()), Value::Str("stopPx".to_string()), Value::Str("stopPrice".to_string())]), &[]);
let mut trailingAmount: Value = self.safe_string2(params.clone(), Value::Str("trailingAmount".to_string()), Value::Str("pegOffsetValue".to_string()), &[]);
let mut isTriggerOrder: bool = !is_equal(&triggerPrice, &Value::Null);
let mut isTrailingAmountOrder: bool = !is_equal(&trailingAmount, &Value::Null);
if is_true(&isTriggerOrder) || is_true(&isTrailingAmountOrder) {
let mut triggerDirection: Value = self.safe_string_k(params.clone(), "triggerDirection", &[]);
let mut triggerAbove: bool = is_true(&(is_equal(&triggerDirection, &Value::Str("ascending".to_string())))) || is_true(&(is_equal(&triggerDirection, &Value::Str("above".to_string()))));
if is_true(&(is_equal(&type_var, &Value::Str("limit".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("market".to_string())))) {
self.check_required_argument(Value::Str("createOrder".to_string()), triggerDirection.clone(), Value::Str("triggerDirection".to_string()), &[Value::List(vec![Value::Str("above".to_string()), Value::Str("below".to_string())])]);
}
if is_equal(&type_var, &Value::Str("limit".to_string())) {
if is_equal(&side, &Value::Str("buy".to_string())) {
orderType = ternary(is_true(&triggerAbove), Value::Str("StopLimit".to_string()), Value::Str("LimitIfTouched".to_string()));
} else {
orderType = ternary(is_true(&triggerAbove), Value::Str("LimitIfTouched".to_string()), Value::Str("StopLimit".to_string()));
}
} else if is_equal(&type_var, &Value::Str("market".to_string())) {
if is_equal(&side, &Value::Str("buy".to_string())) {
orderType = ternary(is_true(&triggerAbove), Value::Str("Stop".to_string()), Value::Str("MarketIfTouched".to_string()));
} else {
orderType = ternary(is_true(&triggerAbove), Value::Str("MarketIfTouched".to_string()), Value::Str("Stop".to_string()));
}
}
if is_true(&isTrailingAmountOrder) {
let mut isStopSellOrder: bool = is_true(&(is_equal(&side, &Value::Str("sell".to_string())))) && is_true(&(is_true(&(is_equal(&orderType, &Value::Str("Stop".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("StopLimit".to_string()))))));
let mut isBuyIfTouchedOrder: bool = is_true(&(is_equal(&side, &Value::Str("buy".to_string())))) && is_true(&(is_true(&(is_equal(&orderType, &Value::Str("MarketIfTouched".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("LimitIfTouched".to_string()))))));
if is_true(&isStopSellOrder) || is_true(&isBuyIfTouchedOrder) {
trailingAmount = add(&Value::Str("-".to_string()), &trailingAmount);
}
add_element_to_object(&mut request, &Value::Str("pegOffsetValue".to_string()), self.parse_to_numeric(trailingAmount.clone()));
add_element_to_object(&mut request, &Value::Str("pegPriceType".to_string()), Value::Str("TrailingStopPeg".to_string()));
} else {
if is_equal(&triggerPrice, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&add(&add(&self.id, &Value::Str(" createOrder() requires a triggerPrice parameter for the ".to_string())), &orderType), &Value::Str(" order type".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("stopPx".to_string()), self.parse_to_numeric(self.price_to_precision(symbol.clone(), triggerPrice.clone())));
}
add_element_to_object(&mut request, &Value::Str("ordType".to_string()), orderType.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stopPx".to_string()), Value::Str("triggerDirection".to_string()), Value::Str("trailingAmount".to_string())]), &[]);
}
if is_true(&(is_equal(&orderType, &Value::Str("Limit".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("StopLimit".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("LimitIfTouched".to_string())))) {
add_element_to_object(&mut request, &Value::Str("price".to_string()), self.parse_to_numeric(self.price_to_precision(symbol.clone(), price.clone())));
}
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string()), &[]);
if !is_equal(&clientOrderId, &Value::Null) {
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 __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_order(&[__ws_arg_7]).await;
return self.parse_order(response.clone(), &[market.clone()]);
Value::Null
}
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut trailingAmount: Value = self.safe_string2(params.clone(), Value::Str("trailingAmount".to_string()), Value::Str("pegOffsetValue".to_string()), &[]);
let mut isTrailingAmountOrder: bool = !is_equal(&trailingAmount, &Value::Null);
if is_true(&isTrailingAmountOrder) {
let mut triggerDirection: Value = self.safe_string_k(params.clone(), "triggerDirection", &[]);
let mut triggerAbove: bool = is_true(&(is_equal(&triggerDirection, &Value::Str("ascending".to_string())))) || is_true(&(is_equal(&triggerDirection, &Value::Str("above".to_string()))));
if is_true(&(is_equal(&type_var, &Value::Str("limit".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("market".to_string())))) {
self.check_required_argument(Value::Str("editOrder".to_string()), triggerDirection.clone(), Value::Str("triggerDirection".to_string()), &[Value::List(vec![Value::Str("above".to_string()), Value::Str("below".to_string())])]);
}
let mut orderType: Value = Value::Null;
if is_equal(&type_var, &Value::Str("limit".to_string())) {
if is_equal(&side, &Value::Str("buy".to_string())) {
orderType = ternary(is_true(&triggerAbove), Value::Str("StopLimit".to_string()), Value::Str("LimitIfTouched".to_string()));
} else {
orderType = ternary(is_true(&triggerAbove), Value::Str("LimitIfTouched".to_string()), Value::Str("StopLimit".to_string()));
}
} else if is_equal(&type_var, &Value::Str("market".to_string())) {
if is_equal(&side, &Value::Str("buy".to_string())) {
orderType = ternary(is_true(&triggerAbove), Value::Str("Stop".to_string()), Value::Str("MarketIfTouched".to_string()));
} else {
orderType = ternary(is_true(&triggerAbove), Value::Str("MarketIfTouched".to_string()), Value::Str("Stop".to_string()));
}
}
let mut isStopSellOrder: bool = is_true(&(is_equal(&side, &Value::Str("sell".to_string())))) && is_true(&(is_true(&(is_equal(&orderType, &Value::Str("Stop".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("StopLimit".to_string()))))));
let mut isBuyIfTouchedOrder: bool = is_true(&(is_equal(&side, &Value::Str("buy".to_string())))) && is_true(&(is_true(&(is_equal(&orderType, &Value::Str("MarketIfTouched".to_string())))) || is_true(&(is_equal(&orderType, &Value::Str("LimitIfTouched".to_string()))))));
if is_true(&isStopSellOrder) || is_true(&isBuyIfTouchedOrder) {
trailingAmount = add(&Value::Str("-".to_string()), &trailingAmount);
}
add_element_to_object(&mut request, &Value::Str("pegOffsetValue".to_string()), self.parse_to_numeric(trailingAmount.clone()));
params = self.omit(params.clone(), Value::List(vec![Value::Str("triggerDirection".to_string()), Value::Str("trailingAmount".to_string())]), &[]);
}
let mut origClOrdID: Value = self.safe_string2(params.clone(), Value::Str("origClOrdID".to_string()), Value::Str("clientOrderId".to_string()), &[]);
if !is_equal(&origClOrdID, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("origClOrdID".to_string()), origClOrdID.clone());
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clOrdID", &[Value::Str("clientOrderId".to_string())]);
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdID".to_string()), clientOrderId.clone());
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("origClOrdID".to_string()), Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string())]), &[]);
} else {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), id.clone());
}
if !is_equal(&amount, &Value::Null) {
let mut qty: Value = self.parse_to_int(self.amount_to_precision(symbol.clone(), amount.clone()));
add_element_to_object(&mut request, &Value::Str("orderQty".to_string()), qty.clone());
}
if !is_equal(&price, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("price".to_string()), price.clone());
}
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("CCXT".to_string())]);
add_element_to_object(&mut request, &Value::Str("text".to_string()), brokerId.clone());
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_put_order(&[__ws_arg_8]).await;
return self.parse_order(response.clone(), &[]);
Value::Null
}
/*
* @method
* @name bitmex#cancelOrder
* @description cancels an open order
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancel
* @param {string} id order id
* @param {string} symbol not used by cancelOrder ()
* @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 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(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
// https://github.com/ccxt/ccxt/issues/6507
let mut clientOrderId: Value = self.safe_value2(params.clone(), Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), id.clone());
} 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 __ws_arg_9 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_delete_order(&[__ws_arg_9]).await;
let mut order: Value = self.safe_value(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut error: Value = self.safe_string_k(order.clone(), "error", &[]);
if !is_equal(&error, &Value::Null) {
if is_greater_than_or_equal(&get_index_of(&error, &Value::Str("Unable to cancel order due to existing state".to_string())), &Value::Int(0)) {
panic!("{}", crate::exchange_errors::order_not_found(add(&add(&self.id, &Value::Str(" cancelOrder() failed: ".to_string())), &error)));
}
}
return self.parse_order(order.clone(), &[]);
Value::Null
}
/*
* @method
* @name bitmex#cancelOrders
* @description cancel multiple orders
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancel
* @param {string[]} ids order ids
* @param {string} symbol not used by cancelOrders ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// return await this.cancelOrder (ids, symbol, params);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
// https://github.com/ccxt/ccxt/issues/6507
let mut clientOrderId: Value = self.safe_value2(params.clone(), Value::Str("clOrdID".to_string()), Value::Str("clientOrderId".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("orderID".to_string()), ids.clone());
} 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 __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_delete_order(&[__ws_arg_10]).await;
return self.parse_orders(response.clone(), &[]);
Value::Null
}
/*
* @method
* @name bitmex#cancelAllOrders
* @description cancel all open orders
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancelAll
* @param {string} [symbol] unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_delete_order_all(&[__ws_arg_11]).await;
return self.parse_orders(response.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @see https://www.bitmex.com/api/explorer/#!/Order/Order_cancelAllAfter
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&timeout, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" cancelAllOrdersAfter() missing timeout".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeout".to_string(), ternary(is_true(&(is_greater_than(&timeout, &Value::Int(0)))), self.parse_to_int(divide(&timeout, &Value::Int(1000))), Value::Int(0)));
m
});
let __ws_arg_12 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_order_cancel_all_after(&[__ws_arg_12]).await;
return response;
Value::Null
}
/*
* @method
* @name bitmex#fetchLeverages
* @description fetch the set leverage for all contract markets
* @see https://www.bitmex.com/api/explorer/#!/Position/Position_get
* @param {string[]} [symbols] a list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverages(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut leverages: Value = self.fetch_positions(&[symbols.clone(), params.clone()]).await;
return self.parse_leverages(leverages.clone(), &[symbols.clone(), Value::Str("symbol".to_string())]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(leverage.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("marginMode".to_string(), self.safe_string_lower(leverage.clone(), Value::Str("marginMode".to_string()), &[]));
m.insert("longLeverage".to_string(), self.safe_integer_k(leverage.clone(), "leverage", &[]));
m.insert("shortLeverage".to_string(), self.safe_integer_k(leverage.clone(), "leverage", &[]));
m
});
Value::Null
}
/*
* @method
* @name bitmex#fetchPositions
* @description fetch all open positions
* @see https://www.bitmex.com/api/explorer/#!/Position/Position_get
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_get_position(&[params.clone()]).await;
//
// [
// {
// "account": 0,
// "symbol": "string",
// "currency": "string",
// "underlying": "string",
// "quoteCurrency": "string",
// "commission": 0,
// "initMarginReq": 0,
// "maintMarginReq": 0,
// "riskLimit": 0,
// "leverage": 0,
// "crossMargin": true,
// "deleveragePercentile": 0,
// "rebalancedPnl": 0,
// "prevRealisedPnl": 0,
// "prevUnrealisedPnl": 0,
// "prevClosePrice": 0,
// "openingTimestamp": "2020-11-09T06:53:59.892Z",
// "openingQty": 0,
// "openingCost": 0,
// "openingComm": 0,
// "openOrderBuyQty": 0,
// "openOrderBuyCost": 0,
// "openOrderBuyPremium": 0,
// "openOrderSellQty": 0,
// "openOrderSellCost": 0,
// "openOrderSellPremium": 0,
// "execBuyQty": 0,
// "execBuyCost": 0,
// "execSellQty": 0,
// "execSellCost": 0,
// "execQty": 0,
// "execCost": 0,
// "execComm": 0,
// "currentTimestamp": "2020-11-09T06:53:59.893Z",
// "currentQty": 0,
// "currentCost": 0,
// "currentComm": 0,
// "realisedCost": 0,
// "unrealisedCost": 0,
// "grossOpenCost": 0,
// "grossOpenPremium": 0,
// "grossExecCost": 0,
// "isOpen": true,
// "markPrice": 0,
// "markValue": 0,
// "riskValue": 0,
// "homeNotional": 0,
// "foreignNotional": 0,
// "posState": "string",
// "posCost": 0,
// "posCost2": 0,
// "posCross": 0,
// "posInit": 0,
// "posComm": 0,
// "posLoss": 0,
// "posMargin": 0,
// "posMaint": 0,
// "posAllowance": 0,
// "taxableMargin": 0,
// "initMargin": 0,
// "maintMargin": 0,
// "sessionMargin": 0,
// "targetExcessMargin": 0,
// "varMargin": 0,
// "realisedGrossPnl": 0,
// "realisedTax": 0,
// "realisedPnl": 0,
// "unrealisedGrossPnl": 0,
// "longBankrupt": 0,
// "shortBankrupt": 0,
// "taxBase": 0,
// "indicativeTaxRate": 0,
// "indicativeTax": 0,
// "unrealisedTax": 0,
// "unrealisedPnl": 0,
// "unrealisedPnlPcnt": 0,
// "unrealisedRoePcnt": 0,
// "simpleQty": 0,
// "simpleCost": 0,
// "simpleValue": 0,
// "simplePnl": 0,
// "simplePnlPcnt": 0,
// "avgCostPrice": 0,
// "avgEntryPrice": 0,
// "breakEvenPrice": 0,
// "marginCallPrice": 0,
// "liquidationPrice": 0,
// "bankruptPrice": 0,
// "timestamp": "2020-11-09T06:53:59.894Z",
// "lastPrice": 0,
// "lastValue": 0
// }
// ]
//
let mut results: Value = self.parse_positions(response.clone(), &[symbols.clone()]);
return self.filter_by_array_positions(results.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "account": 9371654,
// "symbol": "ETHUSDT",
// "currency": "USDt",
// "underlying": "ETH",
// "quoteCurrency": "USDT",
// "commission": 0.00075,
// "initMarginReq": 0.3333333333333333,
// "maintMarginReq": 0.01,
// "riskLimit": 1000000000000,
// "leverage": 3,
// "crossMargin": false,
// "deleveragePercentile": 1,
// "rebalancedPnl": 0,
// "prevRealisedPnl": 0,
// "prevUnrealisedPnl": 0,
// "prevClosePrice": 2053.738,
// "openingTimestamp": "2022-05-21T04:00:00.000Z",
// "openingQty": 0,
// "openingCost": 0,
// "openingComm": 0,
// "openOrderBuyQty": 0,
// "openOrderBuyCost": 0,
// "openOrderBuyPremium": 0,
// "openOrderSellQty": 0,
// "openOrderSellCost": 0,
// "openOrderSellPremium": 0,
// "execBuyQty": 2000,
// "execBuyCost": 39260000,
// "execSellQty": 0,
// "execSellCost": 0,
// "execQty": 2000,
// "execCost": 39260000,
// "execComm": 26500,
// "currentTimestamp": "2022-05-21T04:35:16.397Z",
// "currentQty": 2000,
// "currentCost": 39260000,
// "currentComm": 26500,
// "realisedCost": 0,
// "unrealisedCost": 39260000,
// "grossOpenCost": 0,
// "grossOpenPremium": 0,
// "grossExecCost": 39260000,
// "isOpen": true,
// "markPrice": 1964.195,
// "markValue": 39283900,
// "riskValue": 39283900,
// "homeNotional": 0.02,
// "foreignNotional": -39.2839,
// "posState": "",
// "posCost": 39260000,
// "posCost2": 39260000,
// "posCross": 0,
// "posInit": 13086667,
// "posComm": 39261,
// "posLoss": 0,
// "posMargin": 13125928,
// "posMaint": 435787,
// "posAllowance": 0,
// "taxableMargin": 0,
// "initMargin": 0,
// "maintMargin": 13149828,
// "sessionMargin": 0,
// "targetExcessMargin": 0,
// "varMargin": 0,
// "realisedGrossPnl": 0,
// "realisedTax": 0,
// "realisedPnl": -26500,
// "unrealisedGrossPnl": 23900,
// "longBankrupt": 0,
// "shortBankrupt": 0,
// "taxBase": 0,
// "indicativeTaxRate": null,
// "indicativeTax": 0,
// "unrealisedTax": 0,
// "unrealisedPnl": 23900,
// "unrealisedPnlPcnt": 0.0006,
// "unrealisedRoePcnt": 0.0018,
// "simpleQty": null,
// "simpleCost": null,
// "simpleValue": null,
// "simplePnl": null,
// "simplePnlPcnt": null,
// "avgCostPrice": 1963,
// "avgEntryPrice": 1963,
// "breakEvenPrice": 1964.35,
// "marginCallPrice": 1328.5,
// "liquidationPrice": 1328.5,
// "bankruptPrice": 1308.7,
// "timestamp": "2022-05-21T04:35:16.397Z",
// "lastPrice": 1964.195,
// "lastValue": 39283900
// }
//
market = self.safe_market(&[self.safe_string_k(position.clone(), "symbol", &[]), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut datetime: Value = self.safe_string_k(position.clone(), "timestamp", &[]);
let mut crossMargin: Value = self.safe_value_k(position.clone(), "crossMargin", &[]);
let mut marginMode: Value = ternary(is_true(&(is_equal(&crossMargin, &Value::Bool(true)))), Value::Str("cross".to_string()), Value::Str("isolated".to_string()));
let mut notionalString: Value = crate::precise::Precise::stringAbs(&self.safe_string2(position.clone(), Value::Str("foreignNotional".to_string()), Value::Str("homeNotional".to_string()), &[]));
let mut settleCurrencyCode: Value = self.safe_string_k(market.clone(), "settle", &[]);
let mut maintenanceMargin: Value = self.convert_to_real_amount(settleCurrencyCode.clone(), self.safe_string_k(position.clone(), "maintMargin", &[]));
let mut unrealisedPnl: Value = self.convert_to_real_amount(settleCurrencyCode.clone(), self.safe_string_k(position.clone(), "unrealisedPnl", &[]));
let mut contracts: Value = self.parse_number(crate::precise::Precise::stringAbs(&self.safe_string_k(position.clone(), "currentQty", &[])), &[]);
let mut contractSize: Value = self.safe_number_k(market.clone(), "contractSize", &[]);
let mut side: Value = Value::Null;
let mut homeNotional: Value = self.safe_string_k(position.clone(), "homeNotional", &[]);
if !is_equal(&homeNotional, &Value::Null) {
if is_equal(&get_value(&homeNotional, &Value::Int(0)), &Value::Str("-".to_string())) {
side = Value::Str("short".to_string());
} else {
side = Value::Str("long".to_string());
}
}
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(), "account", &[]));
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("contracts".to_string(), contracts.clone());
m.insert("contractSize".to_string(), contractSize.clone());
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "avgEntryPrice", &[]));
m.insert("markPrice".to_string(), self.safe_number_k(position.clone(), "markPrice", &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("notional".to_string(), self.parse_number(notionalString.clone(), &[]));
m.insert("leverage".to_string(), self.safe_number_k(position.clone(), "leverage", &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.safe_number_k(position.clone(), "initMargin", &[]));
m.insert("initialMarginPercentage".to_string(), self.safe_number_k(position.clone(), "initMarginReq", &[]));
m.insert("maintenanceMargin".to_string(), maintenanceMargin.clone());
m.insert("maintenanceMarginPercentage".to_string(), self.safe_number_k(position.clone(), "maintMarginReq", &[]));
m.insert("unrealizedPnl".to_string(), unrealisedPnl.clone());
m.insert("liquidationPrice".to_string(), self.safe_number_k(position.clone(), "liquidationPrice", &[]));
m.insert("marginMode".to_string(), marginMode.clone());
m.insert("marginRatio".to_string(), Value::Null);
m.insert("percentage".to_string(), self.safe_number_k(position.clone(), "unrealisedPnlPcnt", &[]));
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name bitmex#withdraw
* @description make a withdrawal
* @see https://www.bitmex.com/api/explorer/#!/User/User_requestWithdrawal
* @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
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut 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)); }
self.check_address(&[address.clone()]);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut qty: Value = self.convert_from_real_amount(code.clone(), amount.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 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("amount".to_string(), qty.clone());
m.insert("address".to_string(), address.clone());
m.insert("network".to_string(), self.network_code_to_id(networkCode.clone(), &[get_value(¤cy, &Value::Str("code".to_string()))]));
m
});
if !is_equal(&self.twofa, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("otpToken".to_string()), totp(self.twofa.clone()));
}
let __ws_arg_13 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_user_request_withdrawal(&[__ws_arg_13]).await;
return self.parse_transaction(response.clone(), &[currency.clone()]);
Value::Null
}
/*
* @method
* @name bitmex#fetchFundingRates
* @description fetch the funding rate for multiple markets
* @see https://www.bitmex.com/api/explorer/#!/Instrument/Instrument_getActiveAndIndices
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rates-structure}, indexed by market symbols
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.public_get_instrument_active_and_indices(&[params.clone()]).await;
// same response as under "fetchMarkets"
let mut filteredResponse: Value = Value::List(vec![]);
let mut rawItems: Value = self.to_array(response.clone());
{
let mut i: Value = Value::Int(0);
let mut __for_first_385: bool = true;
while { if !__for_first_385 { i = add(&i, &Value::Int(1)); } __for_first_385 = false; is_less_than(&i, &get_array_length(&rawItems)) } {
let mut item: Value = get_value(&rawItems, &i);
let mut item: Value = get_value(&rawItems, &i);
let mut marketId: Value = self.safe_string_k(item.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut swap: Value = self.safe_bool_k(market.clone(), "swap", &[Value::Bool(false)]);
if is_equal(&swap, &Value::Bool(true)) {
append_to_array(&mut filteredResponse, item.clone());
}
}
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut result: Value = self.parse_funding_rates(filteredResponse.clone(), &[]);
return self.filter_by_array(result.clone(), Value::Str("symbol".to_string()), &[symbols.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);
// see response sample under "fetchMarkets" because same endpoint is being used here
let mut datetime: Value = self.safe_string_k(contract.clone(), "timestamp", &[]);
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut fundingDatetime: Value = self.safe_string_k(contract.clone(), "fundingTimestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "markPrice", &[]));
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), self.safe_number_k(contract.clone(), "indicativeSettlePrice", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("fundingRate".to_string(), self.safe_number_k(contract.clone(), "fundingRate", &[]));
m.insert("fundingTimestamp".to_string(), self.parse8601(fundingDatetime.clone()));
m.insert("fundingDatetime".to_string(), fundingDatetime.clone());
m.insert("nextFundingRate".to_string(), self.safe_number_k(contract.clone(), "indicativeFundingRate", &[]));
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 bitmex#fetchFundingRateHistory
* @description Fetches the history of funding rates
* @see https://www.bitmex.com/api/explorer/#!/Funding/Funding_get
* @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 {int} [params.until] timestamp in ms for ending date filter
* @param {bool} [params.reverse] if true, will sort results newest first
* @param {int} [params.start] starting point for results
* @param {string} [params.columns] array of column names to fetch in info, if omitted, will return all columns
* @param {string} [params.filter] generic table filter, send json key/value pairs, such as {"key": "value"}, you can key on individual fields, and do more advanced querying on timestamps, see the [timestamp docs]{@link https://www.bitmex.com/app/restAPI#Timestamp-Filters} for more details
* @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(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if 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_true(&Value::Bool(in_op(&self.currencies, &symbol))) {
let mut code: Value = self.currency(symbol.clone());
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), get_value(&code, &Value::Str("id".to_string())));
} else if !is_equal(&symbol, &Value::Null) {
let mut splitSymbol: Value = split(&symbol, &Value::Str(":".to_string()));
let mut splitSymbolLength: Value = get_array_length(&splitSymbol);
let mut timeframes: Value = Value::List(vec![Value::Str("nearest".to_string()), Value::Str("daily".to_string()), Value::Str("weekly".to_string()), Value::Str("monthly".to_string()), Value::Str("quarterly".to_string()), Value::Str("biquarterly".to_string()), Value::Str("perpetual".to_string())]);
if is_true(&(is_greater_than(&splitSymbolLength, &Value::Int(1)))) && is_true(&self.in_array(get_value(&splitSymbol, &Value::Int(1)), timeframes.clone())) {
let mut code: Value = self.currency(get_value(&splitSymbol, &Value::Int(0)));
symbol = add(&add(&get_value(&code, &Value::Str("id".to_string())), &Value::Str(":".to_string())), &get_value(&splitSymbol, &Value::Int(1)));
add_element_to_object(&mut request, &Value::Str("symbol".to_string()), symbol.clone());
} else {
market = self.market(symbol.clone());
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("startTime".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
if is_true(&(is_equal(&since, &Value::Null))) && is_true(&(is_equal(&until, &Value::Null))) {
add_element_to_object(&mut request, &Value::Str("reverse".to_string()), Value::Bool(true));
}
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_funding(&[__ws_arg_14]).await;
return self.parse_funding_rate_histories(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_funding_rate_history(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "timestamp": "2016-05-07T12:00:00.000Z",
// "symbol": "ETHXBT",
// "fundingInterval": "2000-01-02T00:00:00.000Z",
// "fundingRate": 0.0010890000000000001,
// "fundingRateDaily": 0.0010890000000000001
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "symbol", &[]);
let mut datetime: Value = self.safe_string_k(info.clone(), "timestamp", &[]);
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()]));
m.insert("fundingRate".to_string(), self.safe_number_k(info.clone(), "fundingRate", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m
});
Value::Null
}
/*
* @method
* @name bitmex#setLeverage
* @description set the level of leverage for a market
* @see https://www.bitmex.com/api/explorer/#!/Position/Position_updateLeverage
* @param {float} leverage the rate of leverage
* @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_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if 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, &Value::Float(0.01)))) || is_true(&(is_greater_than(&leverage, &Value::Int(100)))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" leverage should be between 0.01 and 100".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("type".to_string())), &Value::Str("swap".to_string())) && !is_equal(&get_value(&market, &Value::Str("type".to_string())), &Value::Str("future".to_string())) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" setLeverage() supports future and 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.insert("leverage".to_string(), leverage.clone());
m
});
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
return self.private_post_position_leverage(&[__ws_arg_15]).await;
Value::Null
}
/*
* @method
* @name bitmex#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://www.bitmex.com/api/explorer/#!/Position/Position_isolateMargin
* @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()))));
}
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()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if is_true(&(!is_equal(&get_value(&market, &Value::Str("type".to_string())), &Value::Str("swap".to_string())))) && is_true(&(!is_equal(&get_value(&market, &Value::Str("type".to_string())), &Value::Str("future".to_string())))) {
panic!("{}", crate::exchange_errors::bad_symbol(add(&self.id, &Value::Str(" setMarginMode() supports swap and future contracts only".to_string()))));
}
let mut enabled: Value = ternary(is_true(&(is_equal(&marginMode, &Value::Str("cross".to_string())))), Value::Bool(false), Value::Bool(true));
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("enabled".to_string(), enabled.clone());
m
});
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
return self.private_post_position_isolate(&[__ws_arg_16]).await;
Value::Null
}
/*
* @method
* @name bitmex#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://www.bitmex.com/api/explorer/#!/User/User_getDepositAddress
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] deposit chain, can view all chains via this.publicGetWalletAssets, default is eth, unless the currency has a default chain within this.options['networks']
* @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 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)); }
if is_equal(&networkCode, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchDepositAddress requires params[\"network\"]".to_string()))));
}
let mut currency: Value = self.currency(code.clone());
params = self.omit(params.clone(), Value::Str("network".to_string()), &[]);
let mut parsedNetwork: Value = self.network_code_to_id(networkCode.clone(), &[get_value(¤cy, &Value::Str("code".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("network".to_string(), parsedNetwork.clone());
m
});
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_user_deposit_address(&[__ws_arg_17]).await;
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(), networkCode.clone());
m.insert("address".to_string(), replace_str(&replace_str(&response, &Value::Str("\"".to_string()), &Value::Str("".to_string())), &Value::Str("\"".to_string()), &Value::Str("".to_string())));
m.insert("tag".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_deposit_withdraw_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "asset": "XBT",
// "currency": "XBt",
// "majorCurrency": "XBT",
// "name": "Bitcoin",
// "currencyType": "Crypto",
// "scale": "8",
// "enabled": true,
// "isMarginCurrency": true,
// "minDepositAmount": "10000",
// "minWithdrawalAmount": "1000",
// "maxWithdrawalAmount": "100000000000000",
// "networks": [
// {
// "asset": "btc",
// "tokenAddress": '',
// "depositEnabled": true,
// "withdrawalEnabled": true,
// "withdrawalFee": "20000",
// "minFee": "20000",
// "maxFee": "10000000"
// }
// ]
// }
//
let mut networks: Value = self.safe_value_k(fee.clone(), "networks", &[Value::List(vec![])]);
let mut networksLength: Value = get_array_length(&networks);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
});
if !is_equal(&networksLength, &Value::Int(0)) {
let mut scale: Value = self.safe_string_k(fee.clone(), "scale", &[]);
let mut precision: Value = self.parse_precision(&[scale.clone()]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_386: bool = true;
while { if !__for_first_386 { i = add(&i, &Value::Int(1)); } __for_first_386 = false; is_less_than(&i, &networksLength) } {
let mut network: Value = get_value(&networks, &i);
let mut network: Value = get_value(&networks, &i);
let mut networkId: Value = self.safe_string_k(network.clone(), "asset", &[]);
let mut currencyCode: Value = self.safe_string_k(currency.clone(), "code", &[]);
let mut networkCode: Value = self.network_id_to_code(&[networkId.clone(), currencyCode.clone()]);
let mut withdrawalFeeId: Value = self.safe_string_k(network.clone(), "withdrawalFee", &[]);
let mut withdrawalFee: Value = self.parse_number(crate::precise::Precise::stringMul(&withdrawalFeeId, &precision), &[]);
if !is_equal(&networkCode, &Value::Null) {
add_element_to_object(get_value_mut(&mut result, &Value::Str("networks".to_string())), &networkCode, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), withdrawalFee.clone());
m.insert("percentage".to_string(), Value::Bool(false));
m
}));
m
}));
}
if is_equal(&networksLength, &Value::Int(1)) {
add_element_to_object(get_value_mut(&mut result, &Value::Str("withdraw".to_string())), &Value::Str("fee".to_string()), withdrawalFee.clone());
add_element_to_object(get_value_mut(&mut result, &Value::Str("withdraw".to_string())), &Value::Str("percentage".to_string()), Value::Bool(false));
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name bitmex#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://www.bitmex.com/api/explorer/#!/Wallet/Wallet_getAssetsConfig
* @param {string[]|undefined} codes list of unified currency codes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_deposit_withdraw_fees(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut assets: Value = self.public_get_wallet_assets(&[params.clone()]).await;
return self.parse_deposit_withdraw_fees(assets.clone(), &[codes.clone(), Value::Str("asset".to_string())]);
Value::Null
}
/*
* @method
* @name bitmex#fetchOpenInterests
* @description Retrieves the open interest for a list of symbols
* @see https://docs.bitmex.com/api-explorer/get-stats
* @param {string[]} [symbols] a list of unified CCXT market symbols
* @param {object} [params] exchange specific parameters
* @returns {object[]} a list of [open interest structures]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interests(&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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_stats(&[__ws_arg_18]).await;
//
// [
// {
// currency: 'XBt',
// openInterest: '0',
// openValue: '323890820079',
// rootSymbol: 'Total',
// turnover24h: '447088001322',
// volume24h: '0'
// }
// ...
// ]
//
symbols = self.market_symbols(&[symbols.clone()]);
return self.parse_open_interests(response.clone(), &[symbols.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);
//
// fetchOpenInterest
//
// {
// currency: 'XBt',
// openInterest: '0',
// openValue: '323890820079',
// rootSymbol: 'Total',
// turnover24h: '447088001322',
// volume24h: '0'
// }
//
let mut quoteId: Value = self.safe_string_k(interest.clone(), "currency", &[]);
let mut baseId: Value = self.safe_string_k(interest.clone(), "rootSymbol", &[]);
let mut quoteSymbol: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut baseSymbol: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut symbol: Value = baseSymbol.clone();
if !is_equal("eSymbol, &Value::Null) {
symbol = add(&add(&add(&add(&baseSymbol, &Value::Str("/".to_string())), "eSymbol), &Value::Str(":".to_string())), "eSymbol);
}
let mut openInterest: Value = self.safe_number_k(interest.clone(), "openInterest", &[]);
let mut openValue: Value = self.safe_number_k(interest.clone(), "openValue", &[]);
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(), symbol.clone());
m.insert("baseVolume".to_string(), openInterest.clone());
m.insert("quoteVolume".to_string(), openValue.clone());
m.insert("openInterestAmount".to_string(), openInterest.clone());
m.insert("openInterestValue".to_string(), openValue.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
pub fn calculate_rate_limiter_cost(&self, mut api: Value, mut method: Value, mut path: Value, mut params: Value, optional_args: &[Value]) -> Value {
let mut config = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut isAuthenticated: Value = self.check_required_credentials(&[Value::Bool(false)]);
let mut cost: Value = self.safe_value_k(config.clone(), "cost", &[Value::Int(1)]);
if !is_equal(&cost, &Value::Int(1)) {
if is_true(&isAuthenticated) {
return cost;
} else {
return Value::Int(20);
}
}
return cost;
Value::Null
}
/*
* @method
* @name bitmex#fetchLiquidations
* @description retrieves the public liquidations of a trading pair
* @see https://www.bitmex.com/api/explorer/#!/Liquidation/Liquidation_get
* @param {string} symbol unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the bitmex api endpoint
* @param {int} [params.until] timestamp in ms of the latest liquidation
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/?id=liquidation-structure}
*/
pub async fn fetch_liquidations(&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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchLiquidations".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_dynamic(Value::Str("fetchLiquidations".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).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("startTime".to_string()), since.clone());
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".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_19 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_liquidation(&[__ws_arg_19]).await;
return self.parse_liquidations(self.to_array(response.clone()), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "orderID": "string",
// "symbol": "string",
// "side": "string",
// "price": 0,
// "leavesQty": 0
// }
//
let mut marketId: Value = self.safe_string_k(liquidation.clone(), "symbol", &[]);
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("contracts".to_string(), Value::Null);
m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contractSize", &[]));
m.insert("price".to_string(), self.safe_number_k(liquidation.clone(), "price", &[]));
m.insert("side".to_string(), self.safe_string_lower(liquidation.clone(), Value::Str("side".to_string()), &[]));
m.insert("baseValue".to_string(), Value::Null);
m.insert("quoteValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
}), &[]);
Value::Null
}
/*
* @method
* @name bitmex#fetchPositionsADLRank
* @description fetches the auto deleveraging rank and risk percentage for a list of symbols
* @see https://www.bitmex.com/api/explorer/#!/Position/Position_get
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an [auto de leverage structure]{@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 response: Value = self.private_get_position(&[params.clone()]).await;
return self.parse_adl_ranks(response.clone(), &[symbols.clone()]);
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);
//
// fetchPositionsADLRank
//
// {
// "account": 395724,
// "symbol": "XBTUSDT",
// "strategy": "OneWay",
// "currency": "USDt",
// "underlying": "XBT",
// "quoteCurrency": "USDT",
// "commission": 0.0005,
// "initMarginReq": 0.01,
// "maintMarginReq": 0.005,
// "riskLimit": 1000000000000,
// "leverage": 100,
// "crossMargin": true,
// "deleveragePercentile": 1,
// "rebalancedPnl": -4319,
// "prevRealisedPnl": 0,
// "prevUnrealisedPnl": null,
// "openingQty": null,
// "openOrderBuyQty": 0,
// "openOrderBuyCost": 0,
// "openOrderBuyPremium": 0,
// "openOrderSellQty": 0,
// "openOrderSellCost": 0,
// "openOrderSellPremium": 0,
// "currentQty": 100,
// "currentCost": 8639330,
// "currentComm": 0,
// "realisedCost": 0,
// "unrealisedCost": 8639330,
// "grossOpenPremium": 0,
// "isOpen": true,
// "markPrice": 88636.92,
// "markValue": 8863692,
// "riskValue": 8863692,
// "homeNotional": 0.0001,
// "foreignNotional": -8.863692,
// "posCost": 8639330,
// "posCross": 0,
// "posComm": 0,
// "posLoss": 0,
// "posMargin": 44061,
// "posMaint": 44061,
// "posInit": 0,
// "initMargin": 0,
// "maintMargin": 44061,
// "realisedPnl": 0,
// "unrealisedPnl": 224362,
// "unrealisedPnlPcnt": 0.026,
// "unrealisedRoePcnt": 2.597,
// "avgCostPrice": 86393.3,
// "avgEntryPrice": 86393.3,
// "breakEvenPrice": 86436.5,
// "marginCallPrice": null,
// "liquidationPrice": 0,
// "bankruptPrice": 0,
// "timestamp": "2025-12-31T07:55:50.505Z",
// "positionReport": {
// "account": 395724,
// "avgCostPrice": 86393.3,
// "avgEntryPrice": 86393.3,
// "bankruptPrice": 0,
// "breakEvenPrice": 86436.5,
// "commission": 0.0005,
// "crossMargin": true,
// "currency": "USDt",
// "currentComm": 0,
// "currentCost": 8639330,
// "currentQty": 100,
// "deleveragePercentile": 1,
// "foreignNotional": -8.863692,
// "grossOpenPremium": 0,
// "homeNotional": 0.0001,
// "initMargin": 0,
// "initMarginReq": 0.01,
// "isOpen": true,
// "leverage": 100,
// "liquidationPrice": 0,
// "maintMargin": 44061,
// "maintMarginReq": 0.005,
// "markPrice": 88636.92,
// "markValue": 8863692,
// "openOrderBuyCost": 0,
// "openOrderBuyPremium": 0,
// "openOrderBuyQty": 0,
// "openOrderRealisedPnl": 0,
// "openOrderSellCost": 0,
// "openOrderSellPremium": 0,
// "openOrderSellQty": 0,
// "posComm": 0,
// "posCost": 8639330,
// "posCross": 0,
// "posInit": 0,
// "posLoss": 0,
// "posMaint": 44061,
// "posMargin": 44061,
// "prevRealisedPnl": 0,
// "quoteCurrency": "USDT",
// "realisedCost": 0,
// "realisedPnl": 0,
// "rebalancedPnl": -4319,
// "riskLimit": 1000000000000,
// "riskValue": 8863692,
// "strategy": "OneWay",
// "symbol": "XBTUSDT",
// "timestamp": "2025-12-31T07:55:50.505Z",
// "underlying": "XBT",
// "unrealisedCost": 8639330,
// "unrealisedPnl": 224362,
// "unrealisedPnlPcnt": 0.026,
// "unrealisedRoePcnt": 2.597
// }
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "symbol", &[]);
let mut datetime: Value = self.safe_string_k(info.clone(), "timestamp", &[]);
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(), self.safe_integer_k(info.clone(), "deleveragePercentile", &[]));
m.insert("rating".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m
});
Value::Null
}
/*
* @method
* @name bitmex#fetchSettlementHistory
* @description fetches historical settlement records
* @see https://docs.bitmex.com/api-explorer/get-settlements
* @param {string} symbol unified market symbol of the settlement history
* @param {int} [since] timestamp in ms
* @param {int} [limit] number of records
* @param {object} [params] exchange specific params
* @param {int} [params.until] timestamp in ms
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {string} [params.filter] generic table filter, send json key/value pairs, such as {"key": "value"}, you can key on individual fields, and do more advanced querying on timestamps, see the timestamp docs for more details, default value = {}
* @param {string} [params.columns] array of column names to fetch, if omitted, will return all columns, note that this method will always return item keys, even when not specified, so you may receive more columns that you expect
* @param {int} [params.start] possible values are >= 0 starting point for results, default value = 0
* @param {boolean} [params.reverse] if true, will sort results newest first, default value = false
* @returns {object[]} a list of [settlement history objects]{@link https://docs.ccxt.com/?id=settlement-history-structure}
*/
pub async fn fetch_settlement_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(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
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("startTime".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("count".to_string()), limit.clone());
}
let mut until: Value = self.safe_string_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(since.clone()));
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
}
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_settlement(&[__ws_arg_20]).await;
return self.parse_settlements(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_settlements(&self, mut settlements: Value, optional_args: &[Value]) -> Value {
let mut market = 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 result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_387: bool = true;
while { if !__for_first_387 { i = add(&i, &Value::Int(1)); } __for_first_387 = false; is_less_than(&i, &get_array_length(&settlements)) } {
append_to_array(&mut result, self.parse_settlement(get_value(&settlements, &i), &[market.clone()]));
}
}
let mut sorted: Value = self.sort_by(result.clone(), Value::Str("timestamp".to_string()), &[]);
let mut symbol: Value = self.safe_string_k(market.clone(), "symbol", &[]);
return self.filter_by_symbol_since_limit(sorted.clone(), &[symbol.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_settlement(&self, mut settlement: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// timestamp: '2025-03-28T12:00:00.000Z',
// symbol: 'ETHUSDH25',
// settlementType: 'Settlement',
// settledPrice: '1897.53'
// }
//
let mut datetime: Value = self.safe_string_k(settlement.clone(), "timestamp", &[]);
let mut marketId: Value = self.safe_string_k(settlement.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), settlement.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("price".to_string(), self.safe_number_k(settlement.clone(), "settledPrice", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m
});
Value::Null
}
/*
* @method
* @name bitmex#closePosition
* @description closes open positions for a market
* @see https://docs.bitmex.com/api-explorer/order-new
* @see https://docs.bitmex.com/api-explorer/order-close-position
* @param {string} symbol Unified CCXT market symbol
* @param {string} side the buy or sell side of the closing order, if the position is long set the side to sell, reduceOnly is implied
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn close_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut side = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if 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("side".to_string(), self.capitalize(side.clone()));
m.insert("execInst".to_string(), Value::Str("Close".to_string()));
m
});
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_order(&[__ws_arg_21]).await;
return self.parse_order(response.clone(), &[market.clone()]);
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
if is_equal(&code, &Value::Int(429)) {
panic!("{}", crate::exchange_errors::d_do_s_protection(add(&add(&self.id, &Value::Str(" ".to_string())), &body)));
}
if is_greater_than_or_equal(&code, &Value::Int(400)) {
let mut error: Value = self.safe_value_k(response.clone(), "error", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut message: Value = self.safe_string_k(error.clone(), "message", &[]);
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())), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), message.clone(), feedback.clone());
if is_equal(&code, &Value::Int(400)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
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 = add(&add(&add(&Value::Str("/api/".to_string()), &self.version), &Value::Str("/".to_string())), &path);
if is_equal(&method, &Value::Str("GET".to_string())) {
if is_greater_than(&get_array_length(&object_keys(¶ms)), &Value::Int(0)) {
query = add(&query, &add(&Value::Str("?".to_string()), &self.urlencode(params.clone(), &[])));
}
} else {
let mut format: Value = self.safe_string_k(params.clone(), "_format", &[]);
if !is_equal(&format, &Value::Null) {
query = add(&query, &add(&Value::Str("?".to_string()), &self.urlencode(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("_format".to_string(), format.clone());
m
}), &[])));
params = self.omit(params.clone(), Value::Str("_format".to_string()), &[]);
}
}
let mut url: Value = add(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &api), &query);
let mut isAuthenticated: Value = self.check_required_credentials(&[Value::Bool(false)]);
if is_equal(&api, &Value::Str("private".to_string())) || is_true(&(is_equal(&api, &Value::Str("public".to_string())) && is_true(&isAuthenticated))) {
self.check_required_credentials(&[]);
let mut auth: Value = add(&method, &query);
let mut apiExpires: Value = self.safe_integer_k(self.options.clone(), "api-expires", &[]); // backwards compatibility
let mut expires: Value = self.safe_integer_product(self.options.clone(), Value::Str("recvWindow".to_string()), Value::Float(0.001), &[apiExpires.clone()]);
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m.insert("api-key".to_string(), self.apiKey.clone());
m
});
expires = self.sum(&[self.seconds(), expires.clone()]);
if is_equal(&expires, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" sign() missing expires".to_string()))));
}
let mut stringExpires: Value = to_string_val(&expires);
auth = add(&auth, &stringExpires);
add_element_to_object(&mut headers, &Value::Str("api-expires".to_string()), stringExpires.clone());
if is_equal(&method, &Value::Str("POST".to_string())) || is_equal(&method, &Value::Str("PUT".to_string())) || is_equal(&method, &Value::Str("DELETE".to_string())) {
if is_greater_than(&get_array_length(&object_keys(¶ms)), &Value::Int(0)) {
body = self.json(params.clone());
auth = add(&auth, &body);
}
}
add_element_to_object(&mut headers, &Value::Str("api-signature".to_string()), self.hmac(self.encode(auth.clone()), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), &[]));
}
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
}
}