// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct BackpackCore {
pub exchange: crate::exchange::Exchange,
}
impl BackpackCore {
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 = BackpackCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for BackpackCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_funding_rate(self, rate, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_open_interest(self, interest, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_transaction(self, transaction, &[currency])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::parse_income(self, info, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on BackpackCore.
BackpackCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BackpackCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_order" => self.fetch_open_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"nonce" => self.nonce(),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_side" => self.parse_order_side(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for BackpackCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for BackpackCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl BackpackCore {
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("backpack".into()));
m.insert("name".to_string(), Value::Str("Backpack".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("JP".into())]));
m.insert("rateLimit".to_string(), Value::Int(50));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(true));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(false));
m.insert("cancelWithdraw".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createConvertTrade".to_string(), Value::Bool(false));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createLimitBuyOrder".to_string(), Value::Bool(true));
m.insert("createLimitOrder".to_string(), Value::Bool(true));
m.insert("createLimitSellOrder".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrder".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketOrder".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketSellOrder".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLossOrder".to_string(), Value::Bool(false));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(false));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(false));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(false));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(false));
m.insert("fetchClosedOrder".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchConvertCurrencies".to_string(), Value::Bool(false));
m.insert("fetchConvertQuote".to_string(), Value::Bool(false));
m.insert("fetchConvertTrade".to_string(), Value::Bool(false));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(true));
m.insert("fetchOpenOrder".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(false));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositionHistory".to_string(), Value::Bool(false));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsForSymbol".to_string(), Value::Bool(false));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("setLeverage".to_string(), Value::Bool(false));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(false));
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".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15".to_string(), Value::Str("15m".into()));
m.insert("30".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("2h".to_string(), Value::Str("2h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("6h".to_string(), Value::Str("6h".into()));
m.insert("8h".to_string(), Value::Str("8h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("3d".to_string(), Value::Str("3d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1month".into()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/7f682234-3eb1-48ab-a5ec-250a3227c985".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.backpack.exchange".into()));
m.insert("private".to_string(), Value::Str("https://api.backpack.exchange".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://backpack.exchange/".into()));
m.insert("doc".to_string(), Value::Str("https://docs.backpack.exchange/".into()));
m.insert("referral".to_string(), Value::Str("https://backpack.exchange/join/ccxt".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v1/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend/markets/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend/apy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/market".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/prediction".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/prediction/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/market-sessions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/market-holidays".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/securities".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/markPrices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/openInterest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/fundingRates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/ping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/wallets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/trades/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v1/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/account/limits/borrow".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/account/limits/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/account/limits/withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend/position/liquidationPrice".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/capital".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/capital/collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/capital/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/capital/deposit/address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/capital/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/borrowLend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/interest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/borrowLend/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/dust".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfqs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/rfq".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/rfq/fill".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/quote/fill".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/settlement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/history/strategies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/strategy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/strategies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v1/account/convertDust".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/borrowLend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("wapi/v1/capital/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfq".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfq/accept".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfq/refresh".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfq/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/rfq/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/strategy".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("api/v1/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/strategy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("api/v1/strategies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("patch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v1/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
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(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GTC".to_string(), Value::Bool(true));
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(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(true));
m.insert("selfTradePrevention".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("EXPIRE_MAKER".to_string(), Value::Bool(true));
m.insert("EXPIRE_TAKER".to_string(), Value::Bool(true));
m.insert("EXPIRE_BOTH".to_string(), Value::Bool(true));
m.insert("NONE".to_string(), Value::Bool(false));
m
}));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(20));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Null);
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(1000));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("paginate".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(1000));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instructions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("api/v1/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("accountQuery".into()));
m.insert("PATCH".to_string(), Value::Str("accountUpdate".into()));
m
}));
m.insert("api/v1/capital".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("balanceQuery".into()));
m
}));
m.insert("api/v1/account/limits/borrow".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("maxBorrowQuantity".into()));
m
}));
m.insert("api/v1/account/limits/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("maxOrderQuantity".into()));
m
}));
m.insert("api/v1/account/limits/withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("maxWithdrawalQuantity".into()));
m
}));
m.insert("api/v1/borrowLend/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("borrowLendPositionQuery".into()));
m
}));
m.insert("api/v1/borrowLend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("POST".to_string(), Value::Str("borrowLendExecute".into()));
m
}));
m.insert("wapi/v1/history/borrowLend/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("borrowPositionHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/borrowLend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("borrowHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/dust".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("dustHistoryQueryAll".into()));
m
}));
m.insert("api/v1/capital/collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("collateralQuery".into()));
m
}));
m.insert("wapi/v1/capital/deposit/address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("depositAddressQuery".into()));
m
}));
m.insert("wapi/v1/capital/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("depositQueryAll".into()));
m
}));
m.insert("wapi/v1/history/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("fillHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/funding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("fundingHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/interest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("interestHistoryQueryAll".into()));
m
}));
m.insert("api/v1/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("orderQuery".into()));
m.insert("POST".to_string(), Value::Str("orderExecute".into()));
m.insert("DELETE".to_string(), Value::Str("orderCancel".into()));
m
}));
m.insert("api/v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("orderQueryAll".into()));
m.insert("POST".to_string(), Value::Str("orderExecute".into()));
m.insert("DELETE".to_string(), Value::Str("orderCancelAll".into()));
m
}));
m.insert("wapi/v1/history/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("orderHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("pnlHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/rfq".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("rfqHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("quoteHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/history/settlement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("settlementHistoryQueryAll".into()));
m
}));
m.insert("api/v1/position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("positionQuery".into()));
m
}));
m.insert("api/v1/rfq/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("POST".to_string(), Value::Str("quoteSubmit".into()));
m
}));
m.insert("wapi/v1/history/strategies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("strategyHistoryQueryAll".into()));
m
}));
m.insert("wapi/v1/capital/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GET".to_string(), Value::Str("withdrawalQueryAll".into()));
m.insert("POST".to_string(), Value::Str("withdraw".into()));
m
}));
m
}));
m.insert("recvWindow".to_string(), Value::Int(5000));
m.insert("brokerId".to_string(), Value::Str("".into()));
m.insert("currencyIdsListForParseMarket".to_string(), Value::Null);
m.insert("broker".to_string(), Value::Str("".into()));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("APT".to_string(), Value::Str("Aptos".into()));
m.insert("ARBITRUM".to_string(), Value::Str("Arbitrum".into()));
m.insert("AVAX".to_string(), Value::Str("Avalanche".into()));
m.insert("BASE".to_string(), Value::Str("Base".into()));
m.insert("BERA".to_string(), Value::Str("Berachain".into()));
m.insert("BTC".to_string(), Value::Str("Bitcoin".into()));
m.insert("BCH".to_string(), Value::Str("BitcoinCash".into()));
m.insert("BSC".to_string(), Value::Str("Bsc".into()));
m.insert("ADA".to_string(), Value::Str("Cardano".into()));
m.insert("DOGE".to_string(), Value::Str("Dogecoin".into()));
m.insert("ECLIPSE".to_string(), Value::Str("Eclipse".into()));
m.insert("EQUALSMONEY".to_string(), Value::Str("EqualsMoney".into()));
m.insert("ERC20".to_string(), Value::Str("Ethereum".into()));
m.insert("HYP".to_string(), Value::Str("Hyperliquid".into()));
m.insert("LTC".to_string(), Value::Str("Litecoin".into()));
m.insert("OPTIMISM".to_string(), Value::Str("Optimism".into()));
m.insert("MATIC".to_string(), Value::Str("Polygon".into()));
m.insert("SEI".to_string(), Value::Str("Sei".into()));
m.insert("SUI".to_string(), Value::Str("Sui".into()));
m.insert("SOL".to_string(), Value::Str("Solana".into()));
m.insert("STORY".to_string(), Value::Str("Story".into()));
m.insert("TRC20".to_string(), Value::Str("Tron".into()));
m.insert("XRP".to_string(), Value::Str("XRP".into()));
m
}));
m.insert("networksById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("aptos".to_string(), Value::Str("APT".into()));
m.insert("arbitrum".to_string(), Value::Str("ARBITRUM".into()));
m.insert("avalanche".to_string(), Value::Str("AVAX".into()));
m.insert("base".to_string(), Value::Str("BASE".into()));
m.insert("berachain".to_string(), Value::Str("BERA".into()));
m.insert("bitcoin".to_string(), Value::Str("BTC".into()));
m.insert("bitcoincash".to_string(), Value::Str("BCH".into()));
m.insert("bsc".to_string(), Value::Str("BSC".into()));
m.insert("cardano".to_string(), Value::Str("ADA".into()));
m.insert("dogecoin".to_string(), Value::Str("DOGE".into()));
m.insert("eclipse".to_string(), Value::Str("ECLIPSE".into()));
m.insert("equalsmoney".to_string(), Value::Str("EQUALSMONEY".into()));
m.insert("ethereum".to_string(), Value::Str("ERC20".into()));
m.insert("hyperliquid".to_string(), Value::Str("HYP".into()));
m.insert("litecoin".to_string(), Value::Str("LTC".into()));
m.insert("optimism".to_string(), Value::Str("OPTIMISM".into()));
m.insert("polygon".to_string(), Value::Str("MATIC".into()));
m.insert("sei".to_string(), Value::Str("SEI".into()));
m.insert("sui".to_string(), Value::Str("SUI".into()));
m.insert("solana".to_string(), Value::Str("SOL".into()));
m.insert("story".to_string(), Value::Str("STORY".into()));
m.insert("tron".to_string(), Value::Str("TRC20".into()));
m.insert("xrp".to_string(), Value::Str("XRP".into()));
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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_CLIENT_REQUEST".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_ORDER".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("ACCOUNT_LIQUIDATING".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("BORROW_LIMIT".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("BORROW_REQUIRES_LEND_REDEEM".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("FORBIDDEN".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("INSUFFICIENT_FUNDS".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("INSUFFICIENT_MARGIN".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("INSUFFICIENT_SUPPLY".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("INVALID_ASSET".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_MARKET".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("INVALID_PRICE".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("INVALID_POSITION_ID".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_QUANTITY".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_RANGE".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_SIGNATURE".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("INVALID_SOURCE".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INVALID_SYMBOL".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("INVALID_TWO_FACTOR_CODE".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("LEND_LIMIT".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("LEND_REQUIRES_BORROW_REPAY".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("MAINTENANCE".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("MAX_LEVERAGE_REACHED".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("NOT_IMPLEMENTED".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("ORDER_LIMIT".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("POSITION_LIMIT".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("PRECONDITION_FAILED".to_string(), Value::Str("OperationFailed".into()).clone());
m.insert("RESOURCE_NOT_FOUND".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("SERVER_ERROR".to_string(), Value::Str("NetworkError".into()).clone());
m.insert("TIMEOUT".to_string(), Value::Str("RequestTimeout".into()).clone());
m.insert("TOO_MANY_REQUESTS".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("TRADING_PAUSED".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("UNAUTHORIZED".to_string(), Value::Str("AuthenticationError".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name backpack#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.backpack.exchange/#tag/Assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_api_v1_assets(&[params]).await;
return self.parse_currencies(response);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut currencyId: Value = self.safe_string_k(rawCurrency.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut networks: Value = self.safe_list_k(rawCurrency.clone(), "tokens", &[Value::from(vec![])]);
let mut parsedNetworks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_236: bool = true;
while { if !__for_first_236 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_236 = false; j.as_f64().unwrap_or(f64::NAN) < ((networks.len() as i64) as f64) } {
let mut network: Value = networks.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut networkId: Value = self.safe_string_k(network.clone(), "blockchain", &[]);
let mut networkIdLowerCase: Value = self.safe_string_lower_k(network.clone(), "blockchain", &[]);
let mut networkCode: Value = self.network_id_to_code(&[networkIdLowerCase, code.clone()]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut parsedNetworks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkCode), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), networkId);
m.insert("network".to_string(), networkCode.clone());
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(network.clone(), "minimumWithdrawal", &[]));
m.insert("max".to_string(), self.parse_number(self.omit_zero(self.safe_string_k(network.clone(), "maximumWithdrawal", &[])), &[]));
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(network.clone(), "minimumDeposit", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), self.safe_bool_k(network.clone(), "depositEnabled", &[]));
m.insert("withdraw".to_string(), self.safe_bool_k(network.clone(), "withdrawEnabled", &[]));
m.insert("fee".to_string(), self.safe_number_k(network.clone(), "withdrawalFee", &[]));
m.insert("precision".to_string(), Value::Null);
m.insert("info".to_string(), network);
m
})); }
}
}
}
let mut active: Value = Value::Null;
let mut deposit: Value = Value::Null;
let mut withdraw: Value = Value::Null;
if self.is_empty(parsedNetworks.clone()).as_bool() == Some(true) {
active = Value::Bool(false);
deposit = Value::Bool(false);
withdraw = Value::Bool(false);
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), currencyId);
m.insert("code".to_string(), code);
m.insert("precision".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("name".to_string(), self.safe_string_k(rawCurrency.clone(), "displayName", &[]));
m.insert("active".to_string(), active);
m.insert("deposit".to_string(), deposit);
m.insert("withdraw".to_string(), withdraw);
m.insert("fee".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("networks".to_string(), parsedNetworks);
m.insert("info".to_string(), rawCurrency);
m
}));
Value::Null
}
/*
* @method
* @name backpack#fetchMarkets
* @description retrieves data on all markets for bitbank
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(self.options.clone(), "adjustForTimeDifference", &[Value::Bool(false)]), Value::Bool(true)) {
self.load_time_difference(&[]).await;
}
let mut response: Value = self.public_get_api_v1_markets(&[params]).await;
return self.parse_markets(response);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
//
// [
// {
// "baseSymbol": "SOL",
// "createdAt": "2025-01-21T06:34:54.691858",
// "filters": {
// "price": {
// "borrowmarketFeeMaxMultiplier": null,
// "borrowmarketFeeMinMultiplier": null,
// "maxImpactMultiplier": "1.03",
// "maxMultiplier": "1.25",
// "maxPrice": null,
// "meanMarkPriceBand": {
// "maxMultiplier": "1.15",
// "minMultiplier": "0.9"
// },
// "meanPremiumBand": null,
// "minImpactMultiplier": "0.97",
// "minMultiplier": "0.75",
// "minPrice": "0.01",
// "tickSize": "0.01"
// },
// "quantity": {
// "maxQuantity": null,
// "minQuantity": "0.01",
// "stepSize": "0.01"
// }
// },
// "fundingInterval": 28800000,
// "fundingRateLowerBound": null,
// "fundingRateUpperBound": null,
// "imfFunction": null,
// "marketType": "SPOT",
// "mmfFunction": null,
// "openInterestLimit": "0",
// "orderBookState": "Open",
// "quoteSymbol": "USDC",
// "symbol": "SOL_USDC"
// },
// {
// "baseSymbol": "SOL",
// "createdAt": "2025-01-21T06:34:54.691858",
// "filters": {
// "price": {
// "borrowEntryFeeMaxMultiplier": null,
// "borrowEntryFeeMinMultiplier": null,
// "maxImpactMultiplier": "1.03",
// "maxMultiplier": "1.25",
// "maxPrice": "1000",
// "meanMarkPriceBand": {
// "maxMultiplier": "1.1",
// "minMultiplier": "0.9"
// },
// "meanPremiumBand": {
// "tolerancePct": "0.05"
// },
// "minImpactMultiplier": "0.97",
// "minMultiplier": "0.75",
// "minPrice": "0.01",
// "tickSize": "0.01"
// },
// "quantity": {
// "maxQuantity": null,
// "minQuantity": "0.01",
// "stepSize": "0.01"
// }
// },
// "fundingInterval": "28800000",
// "fundingRateLowerBound": "-100",
// "fundingRateUpperBound": "100",
// "imfFunction": {
// "base": "0.02",
// "factor": "0.0001275",
// "type": "sqrt"
// },
// "marketType": "PERP",
// "mmfFunction": {
// "base": "0.0125",
// "factor": "0.0000765",
// "type": "sqrt"
// },
// "openInterestLimit": "4000000",
// "orderBookState": "Open",
// "quoteSymbol": "USDC",
// "symbol": "SOL_USDC_PERP"
// }
// ]
//
let mut id: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "baseSymbol", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteSymbol", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut filters: Value = self.safe_dict_k(market.clone(), "filters", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut priceFilter: Value = self.safe_dict_k(filters.clone(), "price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut maxPrice: Value = self.safe_number_k(priceFilter.clone(), "maxPrice", &[]);
let mut minPrice: Value = self.safe_number_k(priceFilter.clone(), "minPrice", &[]);
let mut pricePrecision: Value = self.safe_number_k(priceFilter, "tickSize", &[]);
let mut quantityFilter: Value = self.safe_dict_k(filters, "quantity", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut maxQuantity: Value = self.safe_number_k(quantityFilter.clone(), "maxQuantity", &[]);
let mut minQuantity: Value = self.safe_number_k(quantityFilter.clone(), "minQuantity", &[]);
let mut amountPrecision: Value = self.safe_number_k(quantityFilter, "stepSize", &[]);
let mut type_var: Value = Value::Null;
let mut typeOfMarket: Option<String> = self.parse_market_type(self.safe_string_k(market.clone(), "marketType", &[]));
let mut linear: Value = Value::Null;
let mut inverse: Value = Value::Null;
let mut settle: Value = Value::Null;
let mut settleId: Value = Value::Null;
let mut contractSize: Value = Value::Null;
if (typeOfMarket.as_deref() == Some("spot")) {
type_var = Value::Str("spot".into());
} else if (typeOfMarket.as_deref() == Some("swap")) {
type_var = Value::Str("swap".into());
linear = Value::Bool(true);
inverse = Value::Bool(false);
settleId = self.safe_string_k(market.clone(), "quoteSymbol", &[]);
settle = self.safe_currency_code(settleId.clone(), &[]);
symbol = Value::Str(format!("{}{}", symbol, Value::Str(format!("{}{}", Value::Str(":".into()), settle).into())).into());
contractSize = Value::Int(1);
}
let mut orderBookState: Option<String> = self.safe_string_k(market.clone(), "orderBookState", &[]).as_str().map(str::to_owned);
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), Value::Bool(type_var.as_str() == Some("spot")));
m.insert("margin".to_string(), Value::Bool(type_var.as_str() == Some("spot")));
m.insert("swap".to_string(), Value::Bool(type_var.as_str() == Some("swap")));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(orderBookState.as_deref() == Some("Open")));
m.insert("contract".to_string(), Value::Bool(type_var.as_str() != Some("spot")));
m.insert("linear".to_string(), linear);
m.insert("inverse".to_string(), inverse);
m.insert("taker".to_string(), Value::Null);
m.insert("maker".to_string(), Value::Null);
m.insert("contractSize".to_string(), contractSize);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amountPrecision);
m.insert("price".to_string(), pricePrecision);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minQuantity);
m.insert("max".to_string(), maxQuantity);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), minPrice);
m.insert("max".to_string(), 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(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), self.parse8601(self.safe_string_k(market.clone(), "createdAt", &[])));
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub fn parse_market_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("SPOT".to_string(), Value::Str("spot".into()));
m.insert("PERP".to_string(), Value::Str("swap".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name backpack#fetchTickers
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_tickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_tickers(&[__ws_arg_0]).await;
let mut tickers: Value = self.parse_tickers(response, &[]);
return self.filter_by_array_tickers(tickers, Value::Str("symbol".into()), &[symbols]);
Value::Null
}
/*
* @method
* @name backpack#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_ticker
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_ticker(&[__ws_arg_1]).await;
return self.parse_ticker(response, &[market]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTicker/fetchTickers
//
// {
// "firstPrice": "327.38",
// "high": "337.99",
// "lastPrice": "317.14",
// "low": "300.01",
// "priceChange": "-10.24",
// "priceChangePercent": "-0.031279",
// "quoteVolume": "21584.32278",
// "symbol": "AAVE_USDC",
// "trades": "245",
// "volume": "65.823"
// }, ...
//
let mut marketId: Value = self.safe_string_k(ticker.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market]);
let mut symbol: Value = self.safe_symbol(marketId, &[marketResolved.clone()]);
let mut open: Value = self.safe_string_k(ticker.clone(), "firstPrice", &[]);
let mut last: Value = self.safe_string_k(ticker.clone(), "lastPrice", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "high", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "low", &[]);
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "volume", &[]);
let mut quoteVolume: Value = self.safe_string_k(ticker.clone(), "quoteVolume", &[]);
let mut percentage: Value = Value::Null;
let mut percentageNumber: Value = self.safe_float_k(ticker.clone(), "priceChangePercent", &[]);
// in some cases priceChangePercent is a non-numeric string like "N/A"
if (percentageNumber != Value::Null) {
percentage = crate::precise::Precise::stringMul(&self.safe_string_k(ticker.clone(), "priceChangePercent", &[]), &Value::Str("100".into()));
}
let mut change: Value = self.safe_string_k(ticker.clone(), "priceChange", &[]);
let mut parsedTicker: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), open);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), change);
m.insert("percentage".to_string(), percentage);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
return parsedTicker;
Value::Null
}
/*
* @method
* @name backpack#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_depth
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return (default 100, max 200)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_depth(&[__ws_arg_2]).await;
//
// {
// "asks": [
// ["118318.3","0.00633"],
// ["118567.2","0.08450"]
// ],
// "bids": [
// ["1.0","0.38647"],
// ["12.9","1.00000"]
// ],
// "lastUpdateId":"1504999670",
// "timestamp":1753102447307501
// }
//
let mut microseconds: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
if (microseconds == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderBook() missing microseconds".into()))));
}
let mut timestamp: Value = self.parse_to_int((match ((microseconds).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
let mut orderbook: Value = self.parse_order_book(response.clone(), symbol, &[timestamp]);
add_element_to_object(&mut orderbook, &Value::Str("nonce".into()), self.safe_integer_k(response, "lastUpdateId", &[]));
return orderbook;
Value::Null
}
/*
* @method
* @name backpack#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_klines
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in seconds of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch (default 100)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("interval".to_string(), interval);
m
});
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }; // convert milliseconds to seconds
}
let mut defaultLimit: Value = Value::Int(100);
let mut limitResolved: Value = limit.clone();
if (since == Value::Null) && (limit == Value::Null) {
limitResolved = defaultLimit.clone();
}
if (since == Value::Null) {
let mut endTime: Value = (if ((until != Value::Null) && (until != Value::Null) && (until.as_f64() != Some(0.0))) { self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })) } else { self.seconds() });
let mut windowLimit: Value = (if (limit == Value::Null) { defaultLimit.clone() } else { limit.clone() });
let mut startTime: Value = (match (&(endTime), &(((match (&(windowLimit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), startTime); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }; // convert milliseconds to seconds
}
if (until == Value::Null) {
let mut currentMs: Value = self.seconds(); // default to current time in seconds
let mut windowLimit: Value = (if (limit == Value::Null) { defaultLimit } else { limit });
let mut windowEnd: Value = self.sum(&[match &request { Value::Dict(__m15) => __m15.get("startTime").cloned().unwrap_or(Value::Null), _ => Value::Null }, (match (&(windowLimit), &(duration)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]); // sum (): `+` on a dict value is string concatenation in php
let mut minTimestamp: Value = crate::runtime::Math::min(¤tMs, &windowEnd);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), self.parse_to_int(minTimestamp)); }; // default to current time in seconds if until is not specified
}
let mut price: Value = self.safe_string_k(paramsUntil.clone(), "price", &[]);
let mut paramsOmitted: Value = (if (price != Value::Null) { self.omit(paramsUntil.clone(), Value::Str("price".into()), &[]) } else { paramsUntil });
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("priceType".into(), self.capitalize(price)); }
}
let __ws_arg_3 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_get_api_v1_klines(&[__ws_arg_3]).await;
let mut ohlcvs: Value = self.to_array(response);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limitResolved]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.parse8601(self.safe_string_k(ohlcv.clone(), "start", &[])), 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", &[]), self.safe_number_k(ohlcv, "volume", &[])]);
Value::Null
}
/*
* @method
* @name backpack#fetchFundingRate
* @description fetch the current funding rate
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_mark_prices
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() symbol does not support market ".into())).into()), symbol)));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_4 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_mark_prices(&[__ws_arg_4]).await;
let mut data: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(data, &[market]);
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);
//
// {
// "fundingRate": "0.0001",
// "indexPrice": "118333.18643195",
// "markPrice": "118343.51853741",
// "nextFundingTimestamp": 1753113600000,
// "symbol": "BTC_USDC_PERP"
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market]);
let mut symbol: Value = self.safe_symbol(marketId, &[marketResolved]);
let mut nextFundingTimestamp: Value = self.safe_integer_k(contract.clone(), "nextFundingTimestamp", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), self.safe_number_k(contract.clone(), "markPrice", &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(contract.clone(), "indexPrice", &[]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "fundingRate", &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), nextFundingTimestamp.clone());
m.insert("nextFundingDatetime".to_string(), self.iso8601(nextFundingTimestamp));
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Str("1h".into()));
m
});
Value::Null
}
/*
* @method
* @name backpack#fetchOpenInterest
* @description Retrieves the open interest of a derivative trading pair
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_open_interest
* @param {string} symbol Unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=interest-history-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() symbol does not support market ".into())).into()), symbol)));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_open_interest(&[__ws_arg_5]).await;
let mut interest: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_open_interest(interest, &[market]);
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// {
// "openInterest": "1273.85214",
// "symbol": "BTC_USDC_PERP",
// "timestamp":1753105735301
// }
// ]
//
let mut timestamp: Value = self.safe_integer_k(interest.clone(), "timestamp", &[]);
let mut openInterest: Value = self.safe_number_k(interest.clone(), "openInterest", &[]);
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("openInterestAmount".to_string(), Value::Null);
m.insert("openInterestValue".to_string(), openInterest);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), interest);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name backpack#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://docs.backpack.exchange/#tag/Markets/operation/get_funding_interval_rates
* @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
* @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-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
}
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.public_get_api_v1_funding_rates(&[__ws_arg_6]).await;
//
// [
// {
// "fundingRate": "0.0001",
// "intervalEndTimestamp": "2025-07-22T00:00:00",
// "symbol": "BTC_USDC_PERP"
// }
// ]
//
let mut rates: Value = Value::from(vec![]);
let mut rawRates: Value = self.to_array(response);
{
let mut i: Value = Value::Int(0);
let mut __for_first_237: bool = true;
while { if !__for_first_237 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_237 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawRates.len() as i64) as f64) } {
let mut rate: Value = rawRates.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut datetime: Value = self.safe_string_k(rate.clone(), "intervalEndTimestamp", &[]);
let mut timestamp: Value = self.parse8601(datetime.clone());
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rate.clone());
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("fundingRate".to_string(), self.safe_number_k(rate, "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m
}));
}
}
let mut sorted: Value = self.sort_by(rates, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[self.safe_string_k(market, "symbol", &[]), since, limit]);
Value::Null
}
/*
* @method
* @name backpack#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.backpack.exchange/#tag/Trades/operation/get_recent_trades
* @see https://docs.backpack.exchange/#tag/Trades/operation/get_historical_trades
* @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 {int} [params.offset] the number of trades to skip, default is 0
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(1000))); }; // api maximum 1000
}
let mut response: Value = Value::Null;
let mut offset: Option<i64> = self.safe_integer_k(params.clone(), "offset", &[]).as_i64();
if (offset.is_some()) {
let __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_api_v1_trades_history(&[__ws_arg_7]).await;
} else {
let __ws_arg_8 = self.extend(request, &[params]);
response = self.public_get_api_v1_trades(&[__ws_arg_8]).await;
}
let mut responseList: Value = self.to_array(response);
return self.parse_trades(responseList, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name backpack#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.backpack.exchange/#tag/History/operation/get_fills
* @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 (default 100, max 1000)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch trades for
* @param {string} [params.fillType] 'User' (default) 'BookLiquidation' or 'Adl' or 'Backstop' or 'Liquidation' or 'AllLiquidation' or 'CollateralConversion' or 'CollateralConversionAndSpotLiquidation'
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(params.clone(), Value::from(vec![Value::Str("until".into())]), &[]) } else { params });
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("to".into(), until); }
}
let mut fillType: Option<String> = self.safe_string_k(paramsOmitted.clone(), "fillType", &[]).as_str().map(str::to_owned);
if (fillType.is_none()) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("fillType".into(), Value::Str("User".into())); }; // default
}
let __ws_arg_9 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_get_wapi_v1_history_fills(&[__ws_arg_9]).await;
let mut responseList: Value = self.to_array(response);
return self.parse_trades(responseList, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades
// {
// "id": 8721563,
// "isBuyerMaker": false,
// "price": "117427.6",
// "quantity": "0.00016",
// "quoteQuantity": "18.788416",
// "timestamp": 1753123916819
// }
//
// fetchMyTrades
// {
// "clientId": null,
// "fee": "0.004974",
// "feeSymbol": "USDC",
// "isMaker": false,
// "orderId": "4238907375",
// "price": "3826.15",
// "quantity": "0.0026",
// "side": "Bid",
// "symbol": "ETH_USDC_PERP",
// "systemOrderType": null,
// "timestamp": "2025-07-27T17:39:00.092",
// "tradeId": 9748827
// }
//
let mut id: Value = self.safe_string2(trade.clone(), Value::Str("id".into()), Value::Str("tradeId".into()), &[]);
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "quantity", &[]);
let mut isBuyerMaker: Value = self.safe_bool_k(trade.clone(), "isBuyerMaker", &[]);
let mut side: Value = self.parse_order_side(self.safe_string_k(trade.clone(), "side", &[]));
let mut isMaker: Value = self.safe_bool_k(trade.clone(), "isMaker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (isMaker != Value::Null) {
takerOrMaker = (if isMaker.as_bool() == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
} else if (isBuyerMaker != Value::Null) {
takerOrMaker = Value::Str("taker".into());
side = (if isBuyerMaker.as_bool() == Some(true) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut orderId: Value = self.safe_string_k(trade.clone(), "orderId", &[]);
let mut fee: Value = Value::Null;
let mut feeAmount: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "timestamp", &[]);
if (feeAmount != Value::Null) {
// if fetchMyTrades
let mut datetime: Value = self.safe_string_k(trade.clone(), "timestamp", &[]);
timestamp = self.parse8601(datetime);
}
let mut feeSymbol: Value = self.safe_currency_code(self.safe_string_k(trade.clone(), "feeSymbol", &[]), &[]);
if (feeAmount != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeAmount);
m.insert("currency".to_string(), feeSymbol);
m.insert("rate".to_string(), Value::Null);
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("id".to_string(), id);
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name backpack#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://docs.backpack.exchange/#tag/System/operation/get_status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_api_v1_status(&[params]).await;
//
// {
// "message":null,
// "status":"Ok"
// }
//
let mut status: Value = self.safe_string_k(response.clone(), "status", &[]);
if (status == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchStatus() missing status".into()))));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), to_lower(&status));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name backpack#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://developer-pro.bitmart.com/en/spot/#get-system-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_api_v1_time(&[params]).await;
return self.safe_integer(response, Value::Int(0), &[self.milliseconds()]);
Value::Null
}
/*
* @method
* @name backpack#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.backpack.exchange/#tag/Capital/operation/get_balances
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_get_api_v1_capital(&[params]).await;
return self.parse_balance(response);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// {
// "USDC": {
// "available": "120",
// "locked": "0",
// "staked": "0"
// }
// }
//
let mut balanceKeys: Value = object_keys(&response);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_238: bool = true;
while { if !__for_first_238 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_238 = false; i.as_f64().unwrap_or(f64::NAN) < ((balanceKeys.len() as i64) as f64) } {
let mut id: Value = balanceKeys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut balance: Value = self.safe_dict(response.clone(), id, &[]);
let mut account: Value = self.account();
let mut locked: Value = self.safe_string_k(balance.clone(), "locked", &[]);
let mut staked: Value = self.safe_string_k(balance.clone(), "staked", &[]);
let mut used: Value = crate::precise::Precise::stringAdd(&locked, &staked);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance, "available", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), used); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name backpack#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.backpack.exchange/#tag/Capital/operation/get_deposits
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 1000
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchDeposits".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_10 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.private_get_wapi_v1_capital_deposits(&[__ws_arg_10]).await;
return self.parse_transactions(response, &[currency, since, limit]);
Value::Null
}
/*
* @method
* @name backpack#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.backpack.exchange/#tag/Capital/operation/get_withdrawals
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for (default 24 hours ago)
* @param {int} [limit] the maximum number of transfer structures to retrieve (default 50, max 200)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch transfers for (default time now)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchWithdrawals".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("to".into(), until); }
}
let __ws_arg_11 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.private_get_wapi_v1_capital_withdrawals(&[__ws_arg_11]).await;
return self.parse_transactions(response, &[currency, since, limit]);
Value::Null
}
/*
* @method
* @name backpack#withdraw
* @description make a withdrawal
* @see https://docs.backpack.exchange/#tag/Capital/operation/request_withdrawal
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @param {string} params.network the network to withdraw on (mandatory)
* @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 params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut tagparamsWithdrawTagVariable = self.handle_param_string(params, Value::Str("tag".into()), &[]);
let mut tag: Value = tagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWithdrawTag: Value = tagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("quantity".to_string(), self.number_to_string(amount));
m.insert("address".to_string(), address);
m
});
if (tag != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientId".into(), tag); }; // memo or tag
}
let mut networkCodequeryVariable = self.handle_network_code_and_params(paramsWithdrawTag);
let mut networkCode: Value = networkCodequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = networkCodequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut networkId: Value = self.network_code_to_id(networkCode, &[self.safe_string_k(currency.clone(), "code", &[])]);
if (networkId == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" withdraw() requires a network parameter".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("blockchain".into(), networkId); }
let __ws_arg_12 = self.extend(request, &[query]);
let mut response: Value = self.private_post_wapi_v1_capital_withdrawals(&[__ws_arg_12]).await;
return self.parse_transaction(response, &[currency]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// fetchDeposits
// [
// {
// "createdAt": "2025-07-23T13:55:54.267",
// "fiatAmount": null,
// "fiatCurrency": null,
// "fromAddress": "0x2e3ab3e88a7dbdc763aadf5b28c18fb085af420a",
// "id": 6695353,
// "institutionBic": null,
// "platformMemo": null,
// "quantity": "120",
// "source": "ethereum",
// "status": "confirmed",
// "symbol": "USDC",
// "toAddress": "0xfBe7CbfCde93c8a4204a4be6B56732Eb32690170",
// "transactionHash": "0x58edaac415398d617b34c6673fffcaf0024990d5700565030119db5cbf3765d1"
// }
// ]
//
// withdraw
// {
// "accountIdentifier": null,
// "bankIdentifier": null,
// "bankName": null,
// "blockchain": "Ethereum",
// "clientId": null,
// "createdAt": "2025-08-13T19:27:13.817",
// "fee": "3",
// "fiatFee": null,
// "fiatState": null,
// "fiatSymbol": null,
// "id": 5479929,
// "identifier": null,
// "isInternal": false,
// "providerId": null,
// "quantity": "10",
// "status": "pending",
// "subaccountId": null,
// "symbol": "USDC",
// "toAddress": "0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749",
// "transactionHash": null,
// "triggerAt": null
// }
//
// fetchWithdrawals
// [
// {
// "accountIdentifier": null,
// "bankIdentifier": null,
// "bankName": null,
// "blockchain": "Ethereum",
// "clientId": null,
// "createdAt": "2025-08-13T19:27:13.817",
// "fee": "3",
// "fiatFee": null,
// "fiatState": null,
// "fiatSymbol": null,
// "id": 5479929,
// "identifier": null,
// "isInternal": false,
// "providerId": null,
// "quantity": "10",
// "status": "confirmed",
// "subaccountId": null,
// "symbol": "USDC",
// "toAddress": "0x0ad42b8e602c2d3d475ae52d678cf63d84ab2749",
// "transactionHash": "0x658b6d082af4afa0d3cf85caf344ff7c19d980117726bf193b00d8850f8746a1",
// "triggerAt": null
// }
// ]
//
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
let mut id: Value = self.safe_string_k(transaction.clone(), "id", &[]);
let mut txid: Value = self.safe_string_k(transaction.clone(), "transactionHash", &[]);
let mut coin: Value = self.safe_string_k(transaction.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(coin, &[currency]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(transaction.clone(), "createdAt", &[]));
let mut amount: Value = self.safe_number_k(transaction.clone(), "quantity", &[]);
let mut networkId: Value = self.safe_string_lower2(transaction.clone(), Value::Str("source".into()), Value::Str("blockchain".into()), &[]);
let mut network: Value = self.network_id_to_code(&[networkId, code.clone()]);
let mut addressTo: Value = self.safe_string_k(transaction.clone(), "toAddress", &[]);
let mut addressFrom: Value = self.safe_string_k(transaction.clone(), "fromAddress", &[]);
let mut tag: Value = self.safe_string_k(transaction.clone(), "platformMemo", &[]);
let mut feeCost: Value = self.safe_number_k(transaction.clone(), "fee", &[]);
let mut internal: Value = self.safe_bool_k(transaction.clone(), "isInternal", &[Value::Bool(false)]);
let mut fee: Value = Value::Null;
if (feeCost != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), code.clone());
m
});
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction);
m.insert("id".to_string(), id);
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("network".to_string(), network);
m.insert("address".to_string(), Value::Null);
m.insert("addressTo".to_string(), addressTo);
m.insert("addressFrom".to_string(), addressFrom);
m.insert("tag".to_string(), tag);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("amount".to_string(), amount);
m.insert("currency".to_string(), code);
m.insert("status".to_string(), status);
m.insert("updated".to_string(), Value::Null);
m.insert("internal".to_string(), internal);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
});
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("cancelled".to_string(), Value::Str("cancelled".into()));
m.insert("confirmed".to_string(), Value::Str("ok".into()));
m.insert("declined".to_string(), Value::Str("declined".into()));
m.insert("expired".to_string(), Value::Str("expired".into()));
m.insert("initiated".to_string(), Value::Str("initiated".into()));
m.insert("pending".to_string(), Value::Str("pending".into()));
m.insert("refunded".to_string(), Value::Str("refunded".into()));
m.insert("information required".to_string(), Value::Str("pending".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
/*
* @method
* @name backpack#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.backpack.exchange/#tag/Capital/operation/get_deposit_address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.networkCode] the network to fetch the deposit address (mandatory)
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut networkCodeparamsNetworkCodeVariable = self.handle_network_code_and_params(params);
let mut networkCode: Value = networkCodeparamsNetworkCodeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsNetworkCode: Value = networkCodeparamsNetworkCodeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (networkCode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDepositAddress() requires a network parameter, see https://docs.ccxt.com/?id=network-codes".into()))));
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("blockchain".to_string(), self.network_code_to_id(networkCode, &[self.safe_string_k(currency.clone(), "code", &[])]));
m
});
let __ws_arg_13 = self.extend(request, &[paramsNetworkCode]);
let mut response: Value = self.private_get_wapi_v1_capital_deposit_address(&[__ws_arg_13]).await;
return self.parse_deposit_address(response, &[currency]);
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "address": "0xfBe7CbfCde93c8a4204a4be6B56732Eb32690170"
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "address", &[]);
let mut currencyId: Value = self.safe_string_k(depositAddress.clone(), "currency", &[]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), currencyResolved.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null));
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), address);
m.insert("tag".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name backpack#createOrder
* @description create a trade order
* @see https://docs.backpack.exchange/#tag/Order/operation/execute_order
* @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 fullfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.cost] *market orders only* the cost of the order in units of the quote currency (could be used instead of amount)
* @param {int} [params.clientOrderId] a unique id for the order
* @param {boolean} [params.postOnly] true to place a post only order
* @param {string} [params.timeInForce] 'GTC', 'IOC', 'FOK' or 'PO'
* @param {bool} [params.reduceOnly] *contract only* Indicates if this order is to reduce the size of a position
* @param {string} [params.selfTradePrevention] one of EXPIRE_MAKER, EXPIRE_TAKER or EXPIRE_BOTH
* @param {bool} [params.autoLend] *spot margin only* if true then the order can lend
* @param {bool} [params.autoLendRedeem] *spot margin only* if true then the order can redeem a lend if required
* @param {bool} [params.autoBorrow] *spot margin only* if true then the order can borrow
* @param {bool} [params.autoBorrowRepay] *spot margin only* if true then the order can repay a borrow
* @param {float} [params.triggerPrice] the price that a trigger order is triggered at
* @param {object} [params.takeProfit] *swap markets only - takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {float} [params.takeProfit.price] take profit order price (if not provided the order will be a market order)
* @param {object} [params.stopLoss] *swap markets only - stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {float} [params.stopLoss.price] stop loss order price (if not provided the order will be a market order)
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut orderRequest: Value = self.create_order_request(symbol, type_var, side, amount, &[price, params]);
let mut response: Value = self.private_post_api_v1_order(&[orderRequest]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name backpack#createOrders
* @description create a list of trade orders
* @see https://docs.backpack.exchange/#tag/Order/operation/execute_order_batch
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @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 create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_239: bool = true;
while { if !__for_first_239 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_239 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[]);
let mut side: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut extendedParams: Value = self.extend(orderParams, &[params.clone()]); // the request does not accept extra params since it's a list, so we're extending each order with the common params
let mut orderRequest: Value = self.create_order_request(marketId, type_var, side, amount, &[price, extendedParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut response: Value = self.private_post_api_v1_orders(&[ordersRequests]).await;
return self.parse_orders(response, &[]);
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), self.encode_order_side(side).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("orderType".to_string(), self.capitalize(type_var.clone()));
m
});
let mut triggerPrice: Value = self.safe_string_k(params.clone(), "triggerPrice", &[]);
let mut isTriggerOrder: bool = triggerPrice != Value::Null;
let mut quantityKey: Value = Value::Str("quantity".into());
if isTriggerOrder {
quantityKey = Value::Str("triggerQuantity".into());
}
let mut omitKeys: Value = Value::from(vec![]);
// handle basic limit/market order types
if (type_var.as_str() == Some("limit")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&quantityKey), self.amount_to_precision(symbol.clone(), amount.clone())); }
} else if (type_var.as_str() == Some("market")) {
let mut cost: Value = self.safe_string2(params.clone(), Value::Str("cost".into()), Value::Str("quoteQuantity".into()), &[]);
if (cost != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("quoteQuantity".into(), self.cost_to_precision(symbol.clone(), cost)); }
append_to_array(&mut omitKeys, Value::Str("cost".into()));
append_to_array(&mut omitKeys, Value::Str("quoteQuantity".into()));
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&quantityKey), self.amount_to_precision(symbol.clone(), amount)); }
}
}
// trigger orders
if isTriggerOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), self.price_to_precision(symbol.clone(), triggerPrice)); }
append_to_array(&mut omitKeys, Value::Str("triggerPrice".into()));
}
let mut clientOrderId: Value = self.safe_integer_k(params.clone(), "clientOrderId", &[]); // the exchange requires uint
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientId".into(), clientOrderId); }
append_to_array(&mut omitKeys, Value::Str("clientOrderId".into()));
}
let mut postOnlyparamsPostOnlyVariable = self.handle_post_only(Value::Bool(type_var.as_str() == Some("market")), Value::Bool(false), &[self.omit(params, omitKeys, &[])]);
let mut postOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&postOnly) {
add_element_to_object(&mut paramsPostOnly, &Value::Str("postOnly".into()), Value::Bool(true));
}
let mut bracketKeys: Value = Value::from(vec![]);
let mut takeProfit: Value = self.safe_dict_k(paramsPostOnly.clone(), "takeProfit", &[]);
if (takeProfit != Value::Null) {
let mut takeProfitTriggerPrice: Value = self.safe_string_k(takeProfit.clone(), "triggerPrice", &[]);
if (takeProfitTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("takeProfitTriggerPrice".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice)); }
}
let mut takeProfitPrice: Value = self.safe_string_k(takeProfit, "price", &[]);
if (takeProfitPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("takeProfitLimitPrice".into(), self.price_to_precision(symbol.clone(), takeProfitPrice)); }
}
append_to_array(&mut bracketKeys, Value::Str("takeProfit".into()));
}
let mut stopLoss: Value = self.safe_dict_k(paramsPostOnly.clone(), "stopLoss", &[]);
if (stopLoss != Value::Null) {
let mut stopLossTriggerPrice: Value = self.safe_string_k(stopLoss.clone(), "triggerPrice", &[]);
if (stopLossTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopLossTriggerPrice".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice)); }
}
let mut stopLossPrice: Value = self.safe_string_k(stopLoss, "price", &[]);
if (stopLossPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stopLossLimitPrice".into(), self.price_to_precision(symbol, stopLossPrice)); }
}
append_to_array(&mut bracketKeys, Value::Str("stopLoss".into()));
}
let mut selfTradePreventionparamsSelfTradePreventionVariable = self.handle_option_string_and_params(self.omit(paramsPostOnly, bracketKeys, &[]), Value::Str("createOrder".into()), Value::Str("selfTradePrevention".into()), &[]);
let mut selfTradePrevention: Value = selfTradePreventionparamsSelfTradePreventionVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsSelfTradePrevention: Value = selfTradePreventionparamsSelfTradePreventionVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (selfTradePrevention != Value::Null) {
if (selfTradePrevention.as_str() == Some("EXPIRE_MAKER")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("selfTradePrevention".into(), Value::Str("RejectMaker".into())); }
} else if (selfTradePrevention.as_str() == Some("EXPIRE_TAKER")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("selfTradePrevention".into(), Value::Str("RejectTaker".into())); }
} else if (selfTradePrevention.as_str() == Some("EXPIRE_BOTH")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("selfTradePrevention".into(), Value::Str("RejectBoth".into())); }
}
}
return self.extend(request, &[paramsSelfTradePrevention]);
Value::Null
}
pub fn encode_order_side(&self, mut side: Value) -> Option<String> {
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("buy".to_string(), Value::Str("Bid".into()));
m.insert("sell".to_string(), Value::Str("Ask".into()));
m
});
return self.safe_string(sides, side.clone(), &[side.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name backpack#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.backpack.exchange/#tag/Order/operation/get_open_orders
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_14 = self.extend(request, &[params]);
let mut response: Value = self.private_get_api_v1_orders(&[__ws_arg_14]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name backpack#fetchOpenOrder
* @description fetch an open order by it's id
* @see https://docs.backpack.exchange/#tag/Order/operation/get_order
* @param {string} id order id
* @param {string} symbol not used by fetchOpenOrder ()
* @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_open_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrder() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("orderId".to_string(), id);
m
});
let __ws_arg_15 = self.extend(request, &[params]);
let mut response: Value = self.private_get_api_v1_order(&[__ws_arg_15]).await;
return self.parse_order(response, &[]);
Value::Null
}
/*
* @method
* @name backpack#cancelOrder
* @description cancels an open order
* @see https://docs.backpack.exchange/#tag/Order/operation/cancel_order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_16 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_api_v1_order(&[__ws_arg_16]).await;
return self.parse_order(response, &[]);
Value::Null
}
/*
* @method
* @name backpack#cancelAllOrders
* @description cancel all open orders
* @see https://docs.backpack.exchange/#tag/Order/operation/cancel_open_orders
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_api_v1_orders(&[__ws_arg_17]).await;
return self.parse_orders(response, &[market]);
Value::Null
}
/*
* @method
* @name backpack#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.backpack.exchange/#tag/History/operation/get_order_history
* @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 (default 100, max 1000)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.private_get_wapi_v1_history_orders(&[__ws_arg_18]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "clientId": null,
// "createdAt": 1753624283415,
// "executedQuantity": "0.001",
// "executedQuoteQuantity": "3.81428",
// "id": "4227701917",
// "orderType": "Market",
// "quantity": "0.001",
// "quoteQuantity": "3.82",
// "reduceOnly": null,
// "relatedOrderId": null,
// "selfTradePrevention": "RejectTaker",
// "side": "Bid",
// "status": "Filled",
// "stopLossLimitPrice": null,
// "stopLossTriggerBy": null,
// "stopLossTriggerPrice": null,
// "strategyId": null,
// "symbol": "ETH_USDC",
// "takeProfitLimitPrice": null,
// "takeProfitTriggerBy": null,
// "takeProfitTriggerPrice": null,
// "timeInForce": "GTC",
// "triggerBy": null,
// "triggerPrice": null,
// "triggerQuantity": null,
// "triggeredAt": null
// }
//
// fetchOpenOrders
// {
// "clientId": 123456789,
// "createdAt": 1753626206762,
// "executedQuantity": "0",
// "executedQuoteQuantity": "0",
// "id": "4228978331",
// "orderType": "Limit",
// "postOnly": true,
// "price": "3000",
// "quantity": "0.001",
// "reduceOnly": null,
// "relatedOrderId": null,
// "selfTradePrevention": "RejectTaker",
// "side": "Bid",
// "status": "New",
// "stopLossLimitPrice": null,
// "stopLossTriggerBy": null,
// "stopLossTriggerPrice": null,
// "strategyId": null,
// "symbol": "ETH_USDC",
// "takeProfitLimitPrice": null,
// "takeProfitTriggerBy": null,
// "takeProfitTriggerPrice": null,
// "timeInForce": "GTC",
// "triggerBy": null,
// "triggerPrice": null,
// "triggerQuantity": null,
// "triggeredAt": null
// }
//
// fetchOrders
// {
// "clientId": null,
// "createdAt": "2025-07-27T18:05:40.897",
// "executedQuantity": "0",
// "executedQuoteQuantity": "0",
// "expiryReason": null,
// "id": "4239996998",
// "orderType": "Limit",
// "postOnly": false,
// "price": "4500",
// "quantity": null,
// "quoteQuantity": null,
// "selfTradePrevention": "RejectTaker",
// "side": "Ask",
// "status": "Cancelled",
// "stopLossLimitPrice": null,
// "stopLossTriggerBy": null,
// "stopLossTriggerPrice": null,
// "strategyId": null,
// "symbol": "ETH_USDC",
// "systemOrderType": null,
// "takeProfitLimitPrice": null,
// "takeProfitTriggerBy": null,
// "takeProfitTriggerPrice": null,
// "timeInForce": "GTC",
// "triggerBy": null,
// "triggerPrice": "4300",
// "triggerQuantity": "0.001"
// }
//
let mut timestamp: Value = self.safe_integer_k(order.clone(), "createdAt", &[]);
let mut timestamp2: Value = self.parse8601(self.safe_string_k(order.clone(), "createdAt", &[]));
if (timestamp2 != Value::Null) {
timestamp = timestamp2;
}
let mut id: Value = self.safe_string_k(order.clone(), "id", &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientId", &[]);
let mut symbol: Value = self.safe_symbol(self.safe_string_k(order.clone(), "symbol", &[]), &[market.clone()]);
let mut type_var: Value = self.safe_string_lower_k(order.clone(), "orderType", &[]);
let mut timeInForce: Value = self.safe_string_k(order.clone(), "timeInForce", &[]);
let mut side: Value = self.parse_order_side(self.safe_string_k(order.clone(), "side", &[]));
let mut amount: Value = self.safe_string2(order.clone(), Value::Str("quantity".into()), Value::Str("triggerQuantity".into()), &[]);
let mut price: Value = self.safe_string_k(order.clone(), "price", &[]);
let mut cost: Value = self.safe_string_k(order.clone(), "executedQuoteQuantity", &[]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "status", &[]));
let mut triggerPrice: Value = self.safe_string_k(order.clone(), "triggerPrice", &[]);
let mut filled: Value = self.safe_string_k(order.clone(), "executedQuantity", &[]);
let mut reduceOnly: Value = self.safe_bool_k(order.clone(), "reduceOnly", &[]);
let mut postOnly: Value = self.safe_bool_k(order.clone(), "postOnly", &[]);
let mut stopLossPrice: Value = self.safe_string2(order.clone(), Value::Str("stopLossLimitPrice".into()), Value::Str("stopLossTriggerPrice".into()), &[]);
let mut takeProfitPrice: Value = self.safe_string2(order.clone(), Value::Str("takeProfitLimitPrice".into()), Value::Str("takeProfitTriggerPrice".into()), &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), postOnly);
m.insert("reduceOnly".to_string(), reduceOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[market]);
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".into()));
m.insert("Filled".to_string(), Value::Str("closed".into()));
m.insert("Cancelled".to_string(), Value::Str("canceled".into()));
m.insert("Expired".to_string(), Value::Str("canceled".into()));
m.insert("PartiallyFilled".to_string(), Value::Str("open".into()));
m.insert("TriggerPending".to_string(), Value::Str("open".into()));
m.insert("TriggerFailed".to_string(), Value::Str("rejected".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_side(&self, mut side: Value) -> Value {
let mut sides: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Bid".to_string(), Value::Str("buy".into()));
m.insert("Ask".to_string(), Value::Str("sell".into()));
m
});
return self.safe_string(sides, side.clone(), &[side.clone()]);
Value::Null
}
/*
* @method
* @name backpack#fetchPositions
* @description fetch all open positions
* @see https://docs.backpack.exchange/#tag/Futures/operation/get_positions
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_get_api_v1_position(&[params]).await;
let mut positions: Value = self.parse_positions(response, &[]);
if self.is_empty(symbols.clone()).as_bool() == Some(true) {
return positions;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
return self.filter_by_array_positions(positions, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPositions
// {
// "breakEvenPrice": "3831.3630555555555555555555556",
// "cumulativeFundingPayment": "-0.009218",
// "cumulativeInterest": "0",
// "entryPrice": "3826.8888888888888888888888889",
// "estLiquidationPrice": "0",
// "imf": "0.02",
// "imfFunction": {
// "base": "0.02",
// "factor": "0.0000935",
// "type": "sqrt"
// },
// "markPrice": "3787.46813304",
// "mmf": "0.0125",
// "mmfFunction": {
// "base": "0.0125",
// "factor": "0.0000561",
// "type": "sqrt"
// },
// "netCost": "13.7768",
// "netExposureNotional": "13.634885278944",
// "netExposureQuantity": "0.0036",
// "netQuantity": "0.0036",
// "pnlRealized": "0",
// "pnlUnrealized": "-0.141914",
// "positionId": "4238420454",
// "subaccountId": null,
// "symbol": "ETH_USDC_PERP",
// "userId":1813870
// }
//
//
let mut id: Value = self.safe_string_k(position.clone(), "positionId", &[]);
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut entryPrice: Value = self.safe_string_k(position.clone(), "entryPrice", &[]);
let mut markPrice: Value = self.safe_string_k(position.clone(), "markPrice", &[]);
let mut netCost: Value = self.safe_string_k(position.clone(), "netCost", &[]);
let mut hedged: Value = Value::Bool(false);
let mut side: Value = Value::Str("long".into());
if is_true(&crate::precise::Precise::stringLt(&netCost, &Value::Str("0".into()))) {
side = Value::Str("short".into());
}
if (netCost == Value::Null) {
hedged = Value::Null;
side = Value::Null;
}
let mut unrealizedPnl: Value = self.safe_string_k(position.clone(), "pnlUnrealized", &[]);
let mut realizedPnl: Value = self.safe_string_k(position.clone(), "pnlRealized", &[]);
let mut liquidationPrice: Value = self.safe_string_k(position.clone(), "estLiquidationPrice", &[]);
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), self.parse8601(self.safe_string_k(position.clone(), "timestamp", &[])));
m.insert("datetime".to_string(), self.iso8601(self.parse8601(self.safe_string_k(position.clone(), "timestamp", &[]))));
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("hedged".to_string(), hedged);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.safe_string_k(position.clone(), "netExposureQuantity", &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("entryPrice".to_string(), entryPrice);
m.insert("markPrice".to_string(), markPrice);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("notional".to_string(), crate::precise::Precise::stringAbs(&netCost));
m.insert("leverage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), self.safe_string_k(position.clone(), "imf", &[]));
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), self.safe_string_k(position, "mmf", &[]));
m.insert("realizedPnl".to_string(), realizedPnl);
m.insert("unrealizedPnl".to_string(), unrealizedPnl);
m.insert("liquidationPrice".to_string(), liquidationPrice);
m.insert("marginMode".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name backpack#fetchFundingHistory
* @description fetches the history of funding payments
* @see https://docs.backpack.exchange/#tag/History/operation/get_funding_payments
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch (default 24 hours ago)
* @param {int} [limit] the maximum amount of trades to fetch (default 200, max 500)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest trade to fetch (default now)
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbol".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_19 = self.extend(request, &[params]);
let mut response: Value = self.private_get_wapi_v1_history_funding(&[__ws_arg_19]).await;
return self.parse_incomes(response, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "fundingRate": "0.0001",
// "intervalEndTimestamp": "2025-08-01T16:00:00",
// "quantity": "-0.001301",
// "subaccountId": 0,
// "symbol": "ETH_USDC_PERP",
// "userId": 1813870
// }
//
let mut marketId: Value = self.safe_string_k(income.clone(), "symbol", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut amount: Value = self.safe_number_k(income.clone(), "quantity", &[]);
let mut id: Value = self.safe_string_k(income.clone(), "userId", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(income.clone(), "intervalEndTimestamp", &[]));
let mut rate: Value = self.safe_number_k(income.clone(), "fundingRate", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income);
m.insert("symbol".to_string(), symbol);
m.insert("code".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), id);
m.insert("amount".to_string(), amount);
m.insert("rate".to_string(), rate);
m
});
Value::Null
}
pub fn nonce(&self) -> Value {
let mut timeDifference: Value = self.safe_integer_k(self.options.clone(), "timeDifference", &[]);
if (timeDifference == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" nonce() requires a numeric options[\"timeDifference\"]".into()))));
}
return (match (&(self.milliseconds()), &(timeDifference)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut endpoint: Value = Value::Str(format!("{}{}", Value::Str("/".into()), path).into());
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), api.clone(), &[]);
if (apiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = apiUrl;
let mut sortedParams: Value = (if (matches!(¶ms, Value::Arr(_))) { params.clone() } else { self.keysort(params.clone(), &[]) });
let mut headersSigned: Value = Value::Null;
let mut bodySigned: Value = Value::Null;
if (api.as_str() == Some("private")) {
self.check_required_credentials(&[]);
let mut ts: Value = to_string_val(&self.nonce());
let mut recvWindow: Value = self.safe_string2(self.options.clone(), Value::Str("recvWindow".into()), Value::Str("X-Window".into()), &[Value::Str("5000".into())]);
let mut optionInstructions: Value = self.safe_dict_k(self.options.clone(), "instructions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut optionPathInstructions: Value = self.safe_dict(optionInstructions, path.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut instruction: Value = self.safe_string(optionPathInstructions, method.clone(), &[Value::Str("".into())]);
let mut payload: Value = Value::Str("".into());
if (path.as_str() == Some("api/v1/orders")) && (method.as_str() == Some("POST")) {
payload = self.generate_batch_payload(sortedParams.clone(), ts.clone(), recvWindow.clone(), instruction.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
} else {
let mut queryString: Value = self.urlencode(sortedParams.clone(), &[]);
if ((queryString.len() as i64) as f64) > ((0i64) as f64) {
queryString = Value::Str(format!("{}{}", queryString, Value::Str("&".into())).into());
}
payload = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("instruction=".into()), instruction).into()), Value::Str("&".into())).into()), queryString).into()), Value::Str("timestamp=".into())).into()), ts).into()), Value::Str("&window=".into())).into()), recvWindow).into());
}
let mut secretBytes: Value = self.base64_to_binary(self.secret.clone(), &[]);
let mut seed: Value = self.array_slice(secretBytes, Value::Int(0), &[Value::Int(32)]);
let mut signature: Value = eddsa(self.encode(payload), seed, Value::Str("ed25519".into()));
headersSigned = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("X-Timestamp".to_string(), ts);
m.insert("X-Window".to_string(), recvWindow);
m.insert("X-API-Key".to_string(), self.apiKey.clone());
m.insert("X-Signature".to_string(), signature);
m.insert("X-Broker-Id".to_string(), Value::Str("1400".into()));
m
});
if (method.as_str() != Some("GET")) {
bodySigned = json_stringify(&sortedParams);
add_element_to_object(&mut headersSigned, &Value::Str("Content-Type".into()), Value::Str("application/json".into()));
}
}
if (method.as_str() == Some("GET")) {
let mut query: Value = self.urlencode(sortedParams, &[]);
if (Value::Int(query.len() as i64).as_f64() != Some(0.0)) {
endpoint = Value::Str(format!("{}{}", endpoint, Value::Str(format!("{}{}", Value::Str("?".into()), query).into())).into());
}
}
url = Value::Str(format!("{}{}", url, endpoint).into());
let mut headersResolved: Value = (if (api.as_str() == Some("private")) { headersSigned } else { headers });
let mut bodyResolved: Value = body;
if (api.as_str() == Some("private")) && (method.as_str() != Some("GET")) {
bodyResolved = bodySigned;
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), bodyResolved);
m.insert("headers".to_string(), headersResolved);
m
});
Value::Null
}
pub fn generate_batch_payload(&self, mut params: Value, mut ts: Value, mut recvWindow: Value, mut instruction: Value) -> Option<String> {
let mut payload: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_240: bool = true;
while { if !__for_first_240 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_240 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(¶ms).as_f64().unwrap_or(f64::NAN) } {
let mut order: Value = self.safe_dict(params.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut sortedOrder: Value = self.keysort(order, &[]);
let mut orderQuery: Value = self.urlencode(sortedOrder, &[]);
payload = Value::Str(format!("{}{}", payload, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("instruction=".into()), instruction).into()), Value::Str("&".into())).into()), orderQuery).into()), Value::Str("&".into())).into())).into());
if (i.as_f64() == (subtract(&get_array_length(¶ms), &Value::Int(1))).as_f64()) {
payload = Value::Str(format!("{}{}", payload, Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("timestamp=".into()), ts).into()), Value::Str("&window=".into())).into()), recvWindow).into())).into());
}
}
}
return payload.as_str().map(str::to_owned);
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
//
// {"code":"INVALID_ORDER","message":"Invalid order"}
// {"code":"INVALID_CLIENT_REQUEST","message":"Must specify both `triggerPrice` and `triggerQuantity` or neither"}
//
let mut errorCode: Value = self.safe_string_k(response.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(response, "message", &[]);
if (errorCode != Value::Null) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode, feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}