// 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 CoinbaseCore {
pub exchange: crate::exchange::Exchange,
}
impl CoinbaseCore {
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 = CoinbaseCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for CoinbaseCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_position(self, position, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_transfer(self, transfer, &[currency])
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_account(self, account)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_transaction(self, transaction, &[currency])
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::parse_conversion(self, conversion, &[from_currency, to_currency])
}
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 CoinbaseCore.
CoinbaseCore::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 CoinbaseCore.
CoinbaseCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for CoinbaseCore {
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_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_auth_token" => self.create_auth_token(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"create_convert_trade" => self.create_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"create_deposit_address" => self.create_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.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,
"deposit" => self.deposit(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,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_accounts" => self.fetch_accounts(&args[..]).await,
"fetch_accounts_v2" => self.fetch_accounts_v2(&args[..]).await,
"fetch_accounts_v3" => self.fetch_accounts_v3(&args[..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_bids_asks" => self.fetch_bids_asks(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_convert_quote" => self.fetch_convert_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_convert_trade" => self.fetch_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_currencies_from_cache" => self.fetch_currencies_from_cache(&args[..]).await,
"fetch_deposit" => self.fetch_deposit(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_addresses" => self.fetch_deposit_addresses(&args[..]).await,
"fetch_deposit_addresses_by_network" => self.fetch_deposit_addresses_by_network(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_method_id" => self.fetch_deposit_method_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_method_ids" => self.fetch_deposit_method_ids(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_markets_v2" => self.fetch_markets_v2(&args[..]).await,
"fetch_markets_v3" => self.fetch_markets_v3(&args[..]).await,
"fetch_my_buys" => self.fetch_my_buys(&args[..]).await,
"fetch_my_sells" => self.fetch_my_sells(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_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_orders_by_status" => self.fetch_orders_by_status(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_portfolio_details" => self.fetch_portfolio_details(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_portfolios" => self.fetch_portfolios(&args[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ticker_v2" => self.fetch_ticker_v2(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ticker_v3" => self.fetch_ticker_v3(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_tickers_v2" => self.fetch_tickers_v2(&args[..]).await,
"fetch_tickers_v3" => self.fetch_tickers_v3(&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_trading_fees" => self.fetch_trading_fees(&args[..]).await,
"fetch_transactions_with_method" => self.fetch_transactions_with_method(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"find_account_id" => self.find_account_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_account" => self.parse_account(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_contract_market" => self.parse_contract_market(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_conversion" => self.parse_conversion(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_custom_balance" => self.parse_custom_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_deposit_method_id" => self.parse_deposit_method_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_method_ids" => self.parse_deposit_method_ids(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_order_type" => self.parse_order_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_portfolio_details" => self.parse_portfolio_details(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_spot_market" => self.parse_spot_market(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[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)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"prepare_account_request" => self.prepare_account_request(&args[..]),
"prepare_account_request_with_currency_code" => self.prepare_account_request_with_currency_code(&args[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"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 CoinbaseCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for CoinbaseCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl CoinbaseCore {
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("coinbase".into()));
m.insert("name".to_string(), Value::Str("Coinbase Advanced".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("rateLimit".to_string(), Value::Int(34));
m.insert("version".to_string(), Value::Str("v2".into()));
m.insert("userAgent".to_string(), self.userAgents.as_map().and_then(|__m| __m.get("chrome")).cloned().unwrap_or(Value::Null));
m.insert("headers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CB-VERSION".to_string(), Value::Str("2018-05-30".into()));
m
}));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Bool(true));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(true));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createConvertTrade".to_string(), Value::Bool(true));
m.insert("createDepositAddress".to_string(), Value::Bool(true));
m.insert("createLimitBuyOrder".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("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrder".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(false));
m.insert("createOrderWithTakeProfitAndStopLossWs".to_string(), Value::Bool(false));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopLimitOrder".to_string(), Value::Bool(true));
m.insert("createStopMarketOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchConvertQuote".to_string(), Value::Bool(true));
m.insert("fetchConvertTrade".to_string(), Value::Bool(true));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDeposit".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(true));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(true));
m.insert("fetchDepositMethodId".to_string(), Value::Bool(true));
m.insert("fetchDepositMethodIds".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingInterval".to_string(), Value::Bool(false));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchIsolatedPositions".to_string(), Value::Bool(false));
m.insert("fetchL2OrderBook".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverages".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatio".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatioHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(false));
m.insert("fetchMarginModes".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMarkPrices".to_string(), Value::Bool(false));
m.insert("fetchMyBuys".to_string(), Value::Bool(true));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMySells".to_string(), Value::Bool(true));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchOrdersByStatus".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
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("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(false));
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::Str("emulated".into()));
m.insert("fetchTradingFees".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("repayMargin".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(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/1294454/40811661-b6eceae2-653a-11e8-829e-10bfadb078cf.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://api.coinbase.com".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.coinbase.com".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.cdp.coinbase.com/coinbase-app/introduction/welcome".into()), Value::Str("https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/api-reference".into())]));
m.insert("fees".to_string(), Value::from(vec![Value::Str("https://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-fees".into()), Value::Str("https://www.coinbase.com/advanced-fees".into())]));
m.insert("referral".to_string(), Value::Str("https://www.coinbase.com/join/58cbe25a355148797479dbd2".into()));
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("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v2".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("currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("currencies/crypto".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("exchange-rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("users/{user_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("prices/{symbol}/buy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("prices/{symbol}/sell".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("prices/{symbol}/spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
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("accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/addresses".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/addresses/{address_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/addresses/{address_id}/transactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions/{transaction_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/buys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/buys/{buy_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/sells".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/sells/{sell_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/deposits/{deposit_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/withdrawals/{withdrawal_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("payment-methods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("payment-methods/{payment_method_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("user".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("user/auth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("subscriptions/coinbase-one".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/primary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/addresses".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions/{transaction_id}/complete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions/{transaction_id}/resend".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/buys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/buys/{buy_id}/commit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/sells".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/sells/{sell_id}/commit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/deposits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/deposits/{deposit_id}/commit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/withdrawals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/withdrawals/{withdrawal_id}/commit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accounts/{account_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("user".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accounts/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m.insert("accounts/{account_id}/transactions/{transaction_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(10.6));
m
}));
m
}));
m
}));
m
}));
m.insert("v3".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("brokerage/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/market/product_book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/market/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/market/products/{product_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/market/products/{product_id}/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/market/products/{product_id}/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
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("brokerage/accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/accounts/{account_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/historical/batch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/historical/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/historical/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/products/{product_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/products/{product_id}/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/products/{product_id}/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/best_bid_ask".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/product_book".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/transaction_summary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("brokerage/portfolios".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/portfolios/{portfolio_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/convert/trade/{trade_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/balance_summary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/positions/{product_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/sweeps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/intraday/current_margin_window".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/intraday/margin_setting".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/balances/{portfolio_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/portfolio/{portfolio_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/positions/{portfolio_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/positions/{portfolio_uuid}/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/payment_methods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/payment_methods/{payment_method_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/key_permissions".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("brokerage/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/batch_cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/edit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/edit_preview".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/preview".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/portfolios".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/portfolios/move_funds".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/convert/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/convert/trade/{trade_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/sweeps/schedule".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/intraday/margin_setting".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/allocate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/intx/multi_asset_collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/orders/close_position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("brokerage/portfolios/{portfolio_uuid}".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("brokerage/portfolios/{portfolio_uuid}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("brokerage/cfm/sweeps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.012".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.006".into()), &[]));
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.006".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000".into()), &[]), self.parse_number(Value::Str("0.004".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000".into()), &[]), self.parse_number(Value::Str("0.0025".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0018".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("15000000".into()), &[]), self.parse_number(Value::Str("0.0016".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("75000000".into()), &[]), self.parse_number(Value::Str("0.0012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250000000".into()), &[]), self.parse_number(Value::Str("0.0008".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("400000000".into()), &[]), self.parse_number(Value::Str("0.0005".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.004".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000".into()), &[]), self.parse_number(Value::Str("0.0025".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000".into()), &[]), self.parse_number(Value::Str("0.0015".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0008".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("15000000".into()), &[]), self.parse_number(Value::Str("0.0006".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("75000000".into()), &[]), self.parse_number(Value::Str("0.0003".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250000000".into()), &[]), self.parse_number(Value::Str("0.0".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("400000000".into()), &[]), self.parse_number(Value::Str("0.0".into()), &[])])]));
m
}));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
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("two_factor_required".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("param_required".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("validation_error".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("invalid_request".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("personal_details_required".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("identity_verification_required".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("jumio_verification_required".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("jumio_face_match_verification_required".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("unverified_email".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("authentication_error".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("unauthorized".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("invalid_authentication_method".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("invalid_token".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("revoked_token".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("expired_token".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("invalid_scope".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("not_found".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("rate_limit_exceeded".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("resource_exhausted".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("internal_server_error".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("UNSUPPORTED_ORDER_CONFIGURATION".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("INSUFFICIENT_FUND".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("PERMISSION_DENIED".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("INVALID_ARGUMENT".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("PREVIEW_STOP_PRICE_ABOVE_LAST_TRADE_PRICE".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("PREVIEW_INSUFFICIENT_FUND".to_string(), Value::Str("InsufficientFunds".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Insufficient balance in source account".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("request timestamp expired".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("order with this orderID was not found".to_string(), Value::Str("OrderNotFound".into()).clone());
m
}));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("ONE_MINUTE".into()));
m.insert("5m".to_string(), Value::Str("FIVE_MINUTE".into()));
m.insert("15m".to_string(), Value::Str("FIFTEEN_MINUTE".into()));
m.insert("30m".to_string(), Value::Str("THIRTY_MINUTE".into()));
m.insert("1h".to_string(), Value::Str("ONE_HOUR".into()));
m.insert("2h".to_string(), Value::Str("TWO_HOUR".into()));
m.insert("6h".to_string(), Value::Str("SIX_HOUR".into()));
m.insert("1d".to_string(), Value::Str("ONE_DAY".into()));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CGLD".to_string(), Value::Str("CELO".into()));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mica".to_string(), Value::Bool(true));
m.insert("usePrivate".to_string(), Value::Bool(false));
m.insert("brokerId".to_string(), Value::Str("ccxt".into()));
m.insert("stablePairs".to_string(), Value::from(vec![Value::Str("BUSD-USD".into()), Value::Str("CBETH-ETH".into()), Value::Str("DAI-USD".into()), Value::Str("GUSD-USD".into()), Value::Str("GYEN-USD".into()), Value::Str("PAX-USD".into()), Value::Str("PAX-USDT".into()), Value::Str("USDC-EUR".into()), Value::Str("USDC-GBP".into()), Value::Str("USDT-EUR".into()), Value::Str("USDT-GBP".into()), Value::Str("USDT-USD".into()), Value::Str("USDT-USDC".into()), Value::Str("WBTC-BTC".into())]));
m.insert("fetchCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("expires".to_string(), Value::Int(5000));
m
}));
m.insert("accounts".to_string(), Value::from(vec![Value::Str("wallet".into()), Value::Str("fiat".into())]));
m.insert("v3Accounts".to_string(), Value::from(vec![Value::Str("ACCOUNT_TYPE_CRYPTO".into()), Value::Str("ACCOUNT_TYPE_FIAT".into())]));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ERC20".to_string(), Value::Str("ethereum".into()));
m.insert("XLM".to_string(), Value::Str("stellar".into()));
m
}));
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(true));
m.insert("advanced".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Str("fetchMarketsV3".into()));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Str("fetchTickerV3".into()));
m.insert("fetchTickers".to_string(), Value::Str("fetchTickersV3".into()));
m.insert("fetchAccounts".to_string(), Value::Str("fetchAccountsV3".into()));
m.insert("fetchBalance".to_string(), Value::Str("v2PrivateGetAccounts".into()));
m.insert("fetchTime".to_string(), Value::Str("v2PublicGetTime".into()));
m.insert("user_native_currency".to_string(), Value::Str("USD".into()));
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(true));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(true));
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("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(true));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(true));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(true));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Null);
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(3000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(10000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(10000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(10000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(300));
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::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
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::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name coinbase#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/time
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/get-server-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'v2PublicGetTime' or 'v3PublicGetBrokerageTime' default is 'v2PublicGetTime'
* @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 defaultMethod: Value = self.safe_string_k(self.options.clone(), "fetchTime", &[Value::Str("v2PublicGetTime".into())]);
let mut method: Option<String> = self.safe_string_k(params.clone(), "method", &[defaultMethod]).as_str().map(str::to_owned);
params = self.omit(params.clone(), Value::Str("method".into()), &[]);
let mut response: Value = Value::Null;
if (method.as_deref() == Some("v2PublicGetTime")) {
response = self.v2_public_get_time(&[params.clone()]).await;
//
// {
// "data": {
// "epoch": 1589295679,
// "iso": "2020-05-12T15:01:19Z"
// }
// }
//
response = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
response = self.v3_public_get_brokerage_time(&[params]).await;
}
return self.safe_timestamp2(response, Value::Str("epoch".into()), Value::Str("epochSeconds".into()), &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchAccounts
* @description fetch all the accounts associated with a profile
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/accounts/list-accounts
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/?id=account-structure} indexed by the account type
*/
pub async fn fetch_accounts(&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 method: Option<String> = self.safe_string_k(self.options.clone(), "fetchAccounts", &[Value::Str("fetchAccountsV3".into())]).as_str().map(str::to_owned);
if (method.as_deref() == Some("fetchAccountsV3")) {
return self.fetch_accounts_v3(&[params.clone()]).await;
}
return self.fetch_accounts_v2(&[params]).await;
Value::Null
}
pub async fn fetch_accounts_v2(&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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchAccounts".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchAccounts".into()), &[Value::Null, Value::Null, Value::Null, params.clone(), Value::Str("next_starting_after".into()), Value::Str("starting_after".into()), Value::Null, Value::Int(100)]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(100));
m
});
let __ws_arg_0 = self.extend(request, &[params.clone()]);
let mut response: Value = self.v2_private_get_accounts(&[__ws_arg_0]).await;
//
// {
// "pagination": {
// "ending_before": null,
// "starting_after": null,
// "previous_ending_before": null,
// "next_starting_after": null,
// "limit": 244,
// "order": "desc",
// "previous_uri": null,
// "next_uri": null
// },
// "data": [
// {
// "id": "XLM",
// "name": "XLM Wallet",
// "primary": false,
// "type": "wallet",
// "currency": {
// "code": "XLM",
// "name": "Stellar Lumens",
// "color": "#000000",
// "sort_index": 127,
// "exponent": 7,
// "type": "crypto",
// "address_regex": "^G[A-Z2-7]{55}$",
// "asset_id": "13b83335-5ede-595b-821e-5bcdfa80560f",
// "destination_tag_name": "XLM Memo ID",
// "destination_tag_regex": "^[ -~]{1,28}$"
// },
// "balance": {
// "amount": "0.0000000",
// "currency": "XLM"
// },
// "created_at": null,
// "updated_at": null,
// "resource": "account",
// "resource_path": "/v2/accounts/XLM",
// "allow_deposits": true,
// "allow_withdrawals": true
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
let mut pagination: Value = self.safe_dict_k(response.clone(), "pagination", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cursor: Value = self.safe_string_k(pagination, "next_starting_after", &[]);
let mut accounts: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut length: Value = Value::Int(accounts.len() as i64);
let mut lastIndex: Value = (match (&(length), &(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 });
let mut last: Value = self.safe_dict(accounts.clone(), lastIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (cursor != Value::Null) && (cursor.as_str() != Some("")) {
if let Value::Dict(__d) = &mut last { std::sync::Arc::make_mut(__d).insert("next_starting_after".into(), cursor); }
add_element_to_object(&mut accounts, &lastIndex, last);
}
return self.parse_accounts(data, &[params]);
Value::Null
}
pub async fn fetch_accounts_v3(&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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchAccounts".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchAccounts".into()), &[Value::Null, Value::Null, Value::Null, params.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(250)]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(250));
m
});
let __ws_arg_1 = self.extend(request, &[params.clone()]);
let mut response: Value = self.v3_private_get_brokerage_accounts(&[__ws_arg_1]).await;
//
// {
// "accounts": [
// {
// "uuid": "11111111-1111-1111-1111-111111111111",
// "name": "USDC Wallet",
// "currency": "USDC",
// "available_balance": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// },
// "default": true,
// "active": true,
// "created_at": "2023-01-04T06:20:06.456Z",
// "updated_at": "2023-01-04T06:20:07.181Z",
// "deleted_at": null,
// "type": "ACCOUNT_TYPE_CRYPTO",
// "ready": false,
// "hold": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// }
// },
// ...
// ],
// "has_next": false,
// "cursor": "",
// "size": 9
// }
//
let mut accounts: Value = self.safe_list_k(response.clone(), "accounts", &[Value::from(vec![])]);
let mut accountsLength: Value = Value::Int(accounts.len() as i64);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
if (accountsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) && (cursor != Value::Null) && (cursor.as_str() != Some("")) {
let mut lastIndex: Value = (match (&(accountsLength), &(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 });
let mut last: Value = self.safe_dict(accounts.clone(), lastIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut last { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor); }
add_element_to_object(&mut accounts, &lastIndex, last);
}
return self.parse_accounts(accounts, &[params]);
Value::Null
}
/*
* @method
* @name coinbase#fetchPortfolios
* @description fetch all the portfolios
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/portfolios/list-portfolios
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/?id=account-structure} indexed by the account type
*/
pub async fn fetch_portfolios(&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.v3_private_get_brokerage_portfolios(&[params]).await;
let mut portfolios: Value = self.safe_list_k(response, "portfolios", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_517: bool = true;
while { if !__for_first_517 { 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_517 = false; i.as_f64().unwrap_or(f64::NAN) < ((portfolios.len() as i64) as f64) } {
let mut portfolio: Value = portfolios.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(portfolio.clone(), "uuid", &[]));
m.insert("type".to_string(), self.safe_string_k(portfolio.clone(), "type", &[]));
m.insert("code".to_string(), Value::Null);
m.insert("info".to_string(), portfolio);
m
}));
}
}
return result;
Value::Null
}
pub fn parse_account(&self, mut account: Value) -> Value {
//
// fetchAccountsV2
//
// {
// "id": "XLM",
// "name": "XLM Wallet",
// "primary": false,
// "type": "wallet",
// "currency": {
// "code": "XLM",
// "name": "Stellar Lumens",
// "color": "#000000",
// "sort_index": 127,
// "exponent": 7,
// "type": "crypto",
// "address_regex": "^G[A-Z2-7]{55}$",
// "asset_id": "13b83335-5ede-595b-821e-5bcdfa80560f",
// "destination_tag_name": "XLM Memo ID",
// "destination_tag_regex": "^[ -~]{1,28}$"
// },
// "balance": {
// "amount": "0.0000000",
// "currency": "XLM"
// },
// "created_at": null,
// "updated_at": null,
// "resource": "account",
// "resource_path": "/v2/accounts/XLM",
// "allow_deposits": true,
// "allow_withdrawals": true
// }
//
// fetchAccountsV3
//
// {
// "uuid": "11111111-1111-1111-1111-111111111111",
// "name": "USDC Wallet",
// "currency": "USDC",
// "available_balance": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// },
// "default": true,
// "active": true,
// "created_at": "2023-01-04T06:20:06.456Z",
// "updated_at": "2023-01-04T06:20:07.181Z",
// "deleted_at": null,
// "type": "ACCOUNT_TYPE_CRYPTO",
// "ready": false,
// "hold": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// }
// }
//
let mut active: Value = self.safe_bool_k(account.clone(), "active", &[]);
let mut currencyIdV3: Value = self.safe_string_k(account.clone(), "currency", &[]);
let mut currency: Value = self.safe_dict_k(account.clone(), "currency", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currencyId: Value = self.safe_string_k(currency, "code", &[currencyIdV3]);
let mut typeV3: Value = self.safe_string_k(account.clone(), "name", &[]);
let mut typeV2: Value = self.safe_string_k(account.clone(), "type", &[]);
let mut parts: Value = split(&typeV3, &Value::Str(" ".into()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(account.clone(), Value::Str("id".into()), Value::Str("uuid".into()), &[]));
m.insert("type".to_string(), (if (active != Value::Null) { self.safe_string_lower(parts, Value::Int(1), &[]) } else { typeV2 }));
m.insert("code".to_string(), self.safe_currency_code(currencyId, &[]));
m.insert("info".to_string(), account);
m
});
Value::Null
}
/*
* @method
* @name coinbase#createDepositAddress
* @description create a currency deposit address
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/onchain-addresses
* @param {string} code unified currency code of the currency for the deposit address
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn create_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
}));
let mut accountId: Value = self.safe_string_k(params.clone(), "account_id", &[]);
params = self.omit(params.clone(), Value::Str("account_id".into()), &[]);
if (accountId == Value::Null) {
self.load_accounts(&[]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_518: bool = true;
while { if !__for_first_518 { 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_518 = false; i.as_f64().unwrap_or(f64::NAN) < ((self.accounts.len() as i64) as f64) } {
let mut account: Value = self.accounts.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (account.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null).as_str() == code.as_str()) && (account.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null).as_str() == Some("wallet")) {
accountId = account.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
break;
}
}
}
}
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createDepositAddress() could not find the account with matching currency code ".into())).into()), code).into()), Value::Str(", specify an `account_id` extra param to target specific wallet".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId);
m
});
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_post_accounts_account_id_addresses(&[__ws_arg_2]).await;
//
// {
// "data": {
// "id": "05b1ebbf-9438-5dd4-b297-2ddedc98d0e4",
// "address": "coinbasebase",
// "address_info": {
// "address": "coinbasebase",
// "destination_tag": "287594668"
// },
// "name": null,
// "created_at": "2019-07-01T14:39:29Z",
// "updated_at": "2019-07-01T14:39:29Z",
// "network": "eosio",
// "uri_scheme": "eosio",
// "resource": "address",
// "resource_path": "/v2/accounts/14cfc769-e852-52f3-b831-711c104d194c/addresses/05b1ebbf-9438-5dd4-b297-2ddedc98d0e4",
// "warnings": [
// {
// "title": "Only send EOS (EOS) to this address",
// "details": "Sending any other cryptocurrency will result in permanent loss.",
// "image_url": "https://dynamic-assets.coinbase.com/deaca3d47b10ed4a91a872e9618706eec34081127762d88f2476ac8e99ada4b48525a9565cf2206d18c04053f278f693434af4d4629ca084a9d01b7a286a7e26/asset_icons/1f8489bb280fb0a0fd643c1161312ba49655040e9aaaced5f9ad3eeaf868eadc.png"
// },
// {
// "title": "Both an address and EOS memo are required to receive EOS",
// "details": "If you send funds without an EOS memo or with an incorrect EOS memo, your funds cannot be credited to your account.",
// "image_url": "https://www.coinbase.com/assets/receive-warning-2f3269d83547a7748fb39d6e0c1c393aee26669bfea6b9f12718094a1abff155.png"
// }
// ],
// "warning_title": "Only send EOS (EOS) to this address",
// "warning_details": "Sending any other cryptocurrency will result in permanent loss.",
// "destination_tag": "287594668",
// "deposit_uri": "eosio:coinbasebase?dt=287594668",
// "callback_url": null
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tag: Value = self.safe_string_k(data.clone(), "destination_tag", &[]);
let mut address: Value = self.safe_string_k(data, "address", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code);
m.insert("tag".to_string(), tag);
m.insert("address".to_string(), address);
m.insert("network".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name coinbase#fetchMySells
* @ignore
* @description fetch sells
* @see https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/available-apis
* @param {string} symbol not used by fetchMySells ()
* @param {int} [since] timestamp in ms of the earliest sell, default is undefined
* @param {int} [limit] max number of sells to return, default is 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 fetch_my_sells(&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
}));
// v2 did't have an endpoint for all historical trades
let mut request: Value = self.prepare_account_request(&[limit.clone(), params.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
let __ws_arg_3 = self.extend(request, &[query]);
let mut sells: Value = self.v2_private_get_accounts_account_id_sells(&[__ws_arg_3]).await;
let mut sellsData: Value = self.safe_list_k(sells, "data", &[Value::from(vec![])]);
return self.parse_trades(sellsData, &[Value::Null, since, limit]);
Value::Null
}
/*
* @method
* @name coinbase#fetchMyBuys
* @ignore
* @description fetch buys
* @see https://docs.cdp.coinbase.com/coinbase-app/oauth2-integration/available-apis
* @param {string} symbol not used by fetchMyBuys ()
* @param {int} [since] timestamp in ms of the earliest buy, default is undefined
* @param {int} [limit] max number of buys to return, default is 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 fetch_my_buys(&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
}));
// v2 did't have an endpoint for all historical trades
let mut request: Value = self.prepare_account_request(&[limit.clone(), params.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
let __ws_arg_4 = self.extend(request, &[query]);
let mut buys: Value = self.v2_private_get_accounts_account_id_buys(&[__ws_arg_4]).await;
let mut buysData: Value = self.safe_list_k(buys, "data", &[Value::from(vec![])]);
return self.parse_trades(buysData, &[Value::Null, since, limit]);
Value::Null
}
pub async fn fetch_transactions_with_method(&mut self, mut method: Value, 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
}));
let mut request: Value = Value::Null;
{ let __destr_tmp = self.prepare_account_request_with_currency_code(&[code, limit.clone(), params.clone()]).await; request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("v2PrivateGetAccountsAccountIdTransactions")) {
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_private_get_accounts_account_id_transactions(&[__ws_arg_5]).await;
} else if (method.as_str() == Some("v2PrivateGetAccountsAccountIdWithdrawals")) {
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
response = self.v2_private_get_accounts_account_id_withdrawals(&[__ws_arg_6]).await;
} else {
let __ws_arg_7 = self.extend(request, &[params]);
response = self.v2_private_get_accounts_account_id_deposits(&[__ws_arg_7]).await;
}
return self.parse_transactions(response.as_map().and_then(|__m| __m.get("data")).cloned().unwrap_or(Value::Null), &[Value::Null, since, limit]);
Value::Null
}
/*
* @method
* @name coinbase#fetchWithdrawals
* @description Fetch all withdrawals made from an account. Won't return crypto withdrawals. Use fetchLedger for those.
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/withdraw-fiat
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/transactions
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.currencyType] "fiat" or "crypto"
* @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
}));
let mut currencyType: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchWithdrawals".into()), Value::Str("currencyType".into()), &[]); currencyType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (currencyType.as_str() == Some("crypto")) {
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".into()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(results, Value::Str("type".into()), &[Value::Str("withdrawal".into()), Value::Bool(false)]);
}
return self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdWithdrawals".into()), &[code, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#fetchDeposits
* @description Fetch all fiat deposits made to an account. Won't return crypto deposits or staking rewards. Use fetchLedger for those.
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/transactions
* @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 {string} [params.currencyType] "fiat" or "crypto"
* @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
}));
let mut currencyType: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchDeposits".into()), Value::Str("currencyType".into()), &[]); currencyType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (currencyType.as_str() == Some("crypto")) {
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".into()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(results, Value::Str("type".into()), &[Value::Str("deposit".into()), Value::Bool(false)]);
}
return self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdDeposits".into()), &[code, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#fetchDepositsWithdrawals
* @description fetch history of deposits and withdrawals
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/transactions
* @param {string} [code] unified currency code for the currency of the deposit/withdrawals, default is undefined
* @param {int} [since] timestamp in ms of the earliest deposit/withdrawal, default is undefined
* @param {int} [limit] max number of deposit/withdrawals to return, default = 50, Min: 1, Max: 100
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".into()), &[code, since, limit, params]).await;
return self.filter_by_array(results, Value::Str("type".into()), &[Value::from(vec![Value::Str("deposit".into()), Value::Str("withdrawal".into())]), Value::Bool(false)]);
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("created".to_string(), Value::Str("pending".into()));
m.insert("completed".to_string(), Value::Str("ok".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// fiat deposit
//
// {
// "id": "f34c19f3-b730-5e3d-9f72",
// "status": "completed",
// "payment_method": {
// "id": "a022b31d-f9c7-5043-98f2",
// "resource": "payment_method",
// "resource_path": "/v2/payment-methods/a022b31d-f9c7-5043-98f2"
// },
// "transaction": {
// "id": "04ed4113-3732-5b0c-af86-b1d2146977d0",
// "resource": "transaction",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/transactions/04ed4113-3732-5b0c-af86"
// },
// "user_reference": "2VTYTH",
// "created_at": "2017-02-09T07:01:18Z",
// "updated_at": "2017-02-09T07:01:26Z",
// "resource": "deposit",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/deposits/f34c19f3-b730-5e3d-9f72",
// "committed": true,
// "payout_at": "2017-02-12T07:01:17Z",
// "instant": false,
// "fee": { "amount": "0.00", "currency": "EUR" },
// "amount": { "amount": "114.02", "currency": "EUR" },
// "subtotal": { "amount": "114.02", "currency": "EUR" },
// "hold_until": null,
// "hold_days": 0,
// "hold_business_days": 0,
// "next_step": null
// }
//
// fiat_withdrawal
//
// {
// "id": "cfcc3b4a-eeb6-5e8c-8058",
// "status": "completed",
// "payment_method": {
// "id": "8b94cfa4-f7fd-5a12-a76a",
// "resource": "payment_method",
// "resource_path": "/v2/payment-methods/8b94cfa4-f7fd-5a12-a76a"
// },
// "transaction": {
// "id": "fcc2550b-5104-5f83-a444",
// "resource": "transaction",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/transactions/fcc2550b-5104-5f83-a444"
// },
// "user_reference": "MEUGK",
// "created_at": "2018-07-26T08:55:12Z",
// "updated_at": "2018-07-26T08:58:18Z",
// "resource": "withdrawal",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/withdrawals/cfcc3b4a-eeb6-5e8c-8058",
// "committed": true,
// "payout_at": "2018-07-31T08:55:12Z",
// "instant": false,
// "fee": { "amount": "0.15", "currency": "EUR" },
// "amount": { "amount": "13130.69", "currency": "EUR" },
// "subtotal": { "amount": "13130.84", "currency": "EUR" },
// "idem": "e549dee5-63ed-4e79-8a96",
// "next_step": null
// }
//
// withdraw
//
// {
// "id": "a1794ecf-5693-55fa-70cf-ef731748ed82",
// "type": "send",
// "status": "pending",
// "amount": {
// "amount": "-14.008308",
// "currency": "USDC"
// },
// "native_amount": {
// "amount": "-18.74",
// "currency": "CAD"
// },
// "description": null,
// "created_at": "2024-01-12T01:27:31Z",
// "updated_at": "2024-01-12T01:27:31Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/a34bgfad-ed67-538b-bffc-730c98c10da0/transactions/a1794ecf-5693-55fa-70cf-ef731748ed82",
// "instant_exchange": false,
// "network": {
// "status": "pending",
// "status_description": "Pending (est. less than 10 minutes)",
// "transaction_fee": {
// "amount": "4.008308",
// "currency": "USDC"
// },
// "transaction_amount": {
// "amount": "10.000000",
// "currency": "USDC"
// },
// "confirmations": 0
// },
// "to": {
// "resource": "ethereum_address",
// "address": "0x9...",
// "currency": "USDC",
// "address_info": {
// "address": "0x9..."
// }
// },
// "idem": "748d8591-dg9a-7831-a45b-crd61dg78762",
// "details": {
// "title": "Sent USDC",
// "subtitle": "To USDC address on Ethereum network",
// "header": "Sent 14.008308 USDC ($18.74)",
// "health": "warning"
// },
// "hide_native_amount": false
// }
//
//
// crypto deposit & withdrawal (using `/transactions` endpoint)
// {
// "amount": {
// "amount": "0.00014200", (negative for withdrawal)
// "currency": "BTC"
// },
// "created_at": "2024-03-29T15:48:30Z",
// "id": "0031a605-241d-514d-a97b-d4b99f3225d3",
// "idem": "092a979b-017e-4403-940a-2ca57811f442", // field present only in case of withdrawal
// "native_amount": {
// "amount": "9.85", (negative for withdrawal)
// "currency": "USD"
// },
// "network": {
// "status": "pending", // if status is `off_blockchain` then no more other fields are present in this object
// "hash": "5jYuvrNsvX2DZoMnzGYzVpYxJLfYu4GSK3xetG1H5LHrSovsuFCFYdFMwNRoiht3s6fBk92MM8QLLnz65xuEFTrE",
// "network_name": "solana",
// "transaction_fee": {
// "amount": "0.000100000",
// "currency": "SOL"
// }
// },
// "resource": "transaction",
// "resource_path": "/v2/accounts/dc504b1c-248e-5b68-a3b0-b991f7fa84e6/transactions/0031a605-241d-514d-a97b-d4b99f3225d3",
// "status": "completed",
// "type": "send",
// "from": { // in some cases, field might be present for deposit
// "id": "7fd10cd7-b091-5cee-ba41-c29e49a7cccf",
// "name": "Coinbase",
// "resource": "user"
// },
// "to": { // field only present for withdrawal
// "address": "5HA12BNthAvBwNYARYf9y5MqqCpB4qhCNFCs1Qw48ACE",
// "resource": "address"
// },
// "description": "C3 - One Time BTC Credit . Reference Case # 123.", // in some cases, field might be present for deposit
// }
//
let mut transactionType: Option<String> = self.safe_string_k(transaction.clone(), "type", &[]).as_str().map(str::to_owned);
let mut amountAndCurrencyObject: Value = Value::Null;
let mut feeObject: Value = Value::Null;
let mut network: Value = self.safe_dict_k(transaction.clone(), "network", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (transactionType.as_deref() == Some("send")) {
amountAndCurrencyObject = self.safe_dict_k(network.clone(), "transaction_amount", &[]);
feeObject = self.safe_dict_k(network.clone(), "transaction_fee", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
} else {
amountAndCurrencyObject = self.safe_dict_k(transaction.clone(), "subtotal", &[]);
feeObject = self.safe_dict_k(transaction.clone(), "fee", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
if (amountAndCurrencyObject == Value::Null) {
amountAndCurrencyObject = self.safe_dict_k(transaction.clone(), "amount", &[]);
}
let mut amountString: Value = self.safe_string_k(amountAndCurrencyObject.clone(), "amount", &[]);
let mut amountStringAbs: Value = crate::precise::Precise::stringAbs(&amountString);
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
if (status == Value::Null) {
let mut committed: Value = self.safe_bool_k(transaction.clone(), "committed", &[]);
status = (if (committed.as_bool() == Some(true)) { Value::Str("ok".into()) } else { Value::Str("pending".into()) });
}
let mut id: Value = self.safe_string_k(transaction.clone(), "id", &[]);
let mut currencyId: Value = self.safe_string_k(amountAndCurrencyObject, "currency", &[]);
let mut feeCurrencyId: Value = self.safe_string_k(feeObject.clone(), "currency", &[]);
let mut datetime: Value = self.safe_string_k(transaction.clone(), "created_at", &[]);
let mut resource: Value = self.safe_string_k(transaction.clone(), "resource", &[]);
let mut type_var: Value = resource;
if !(self.in_array(type_var.clone(), Value::from(vec![Value::Str("deposit".into()), Value::Str("withdrawal".into())])).as_bool() == Some(true)) {
if is_true(&crate::precise::Precise::stringGt(&amountString, &Value::Str("0".into()))) {
type_var = Value::Str("deposit".into());
} else if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".into()))) {
type_var = Value::Str("withdrawal".into());
}
}
let mut toObject: Value = self.safe_dict_k(transaction.clone(), "to", &[]);
let mut addressTo: Value = self.safe_string_k(toObject, "address", &[]);
let mut networkId: Value = self.safe_string_k(network.clone(), "network_name", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), id.clone());
m.insert("txid".to_string(), self.safe_string_k(network, "hash", &[id]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("network".to_string(), self.network_id_to_code(&[networkId, code.clone()]));
m.insert("address".to_string(), addressTo.clone());
m.insert("addressTo".to_string(), addressTo);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), type_var);
m.insert("amount".to_string(), self.parse_number(amountStringAbs, &[]));
m.insert("currency".to_string(), code);
m.insert("status".to_string(), status);
m.insert("updated".to_string(), self.parse8601(self.safe_string_k(transaction, "updated_at", &[])));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_number_k(feeObject, "amount", &[]));
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId, &[]));
m
}));
m
});
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchMyBuys, fetchMySells
//
// {
// "id": "67e0eaec-07d7-54c4-a72c-2e92826897df",
// "status": "completed",
// "payment_method": {
// "id": "83562370-3e5c-51db-87da-752af5ab9559",
// "resource": "payment_method",
// "resource_path": "/v2/payment-methods/83562370-3e5c-51db-87da-752af5ab9559"
// },
// "transaction": {
// "id": "441b9494-b3f0-5b98-b9b0-4d82c21c252a",
// "resource": "transaction",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/transactions/441b9494-b3f0-5b98-b9b0-4d82c21c252a"
// },
// "amount": { "amount": "1.00000000", "currency": "BTC" },
// "total": { "amount": "10.25", "currency": "USD" },
// "subtotal": { "amount": "10.10", "currency": "USD" },
// "created_at": "2015-01-31T20:49:02Z",
// "updated_at": "2015-02-11T16:54:02-08:00",
// "resource": "buy",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/buys/67e0eaec-07d7-54c4-a72c-2e92826897df",
// "committed": true,
// "instant": false,
// "fee": { "amount": "0.15", "currency": "USD" },
// "payout_at": "2015-02-18T16:54:00-08:00"
// }
//
// fetchTrades
//
// {
// "trade_id": "10092327",
// "product_id": "BTC-USDT",
// "price": "17488.12",
// "size": "0.0000623",
// "time": "2023-01-11T00:52:37.557001Z",
// "side": "BUY",
// "bid": "",
// "ask": ""
// }
//
// fetchMyTrades
//
// {
// "entry_id": "b88b82cc89e326a2778874795102cbafd08dd979a2a7a3c69603fc4c23c2e010",
// "trade_id": "cdc39e45-bbd3-44ec-bf02-61742dfb16a1",
// "order_id": "813a53c5-3e39-47bb-863d-2faf685d22d8",
// "trade_time": "2023-01-18T01:37:38.091377090Z",
// "trade_type": "FILL",
// "price": "21220.64",
// "size": "0.0046830664333996",
// "commission": "0.0000280983986004",
// "product_id": "BTC-USDT",
// "sequence_timestamp": "2023-01-18T01:37:38.092520Z",
// "liquidity_indicator": "UNKNOWN_LIQUIDITY_INDICATOR",
// "size_in_quote": true,
// "user_id": "1111111-1111-1111-1111-111111111111",
// "side": "BUY"
// }
//
let mut symbol: Value = Value::Null;
let mut totalObject: Value = self.safe_dict_k(trade.clone(), "total", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amountObject: Value = self.safe_dict_k(trade.clone(), "amount", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut subtotalObject: Value = self.safe_dict_k(trade.clone(), "subtotal", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut feeObject: Value = self.safe_dict_k(trade.clone(), "fee", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Value = self.safe_string_k(trade.clone(), "product_id", &[]);
market = self.safe_market(&[marketId, market.clone(), Value::Str("-".into())]);
if (market != Value::Null) {
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
} else {
let mut baseId: Value = self.safe_string_k(amountObject.clone(), "currency", &[]);
let mut quoteId: Value = self.safe_string_k(totalObject, "currency", &[]);
if (baseId != Value::Null) && (quoteId != Value::Null) {
let mut base: Value = self.safe_currency_code(baseId, &[]);
let mut quote: Value = self.safe_currency_code(quoteId, &[]);
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
}
}
let mut sizeInQuote: Value = self.safe_bool_k(trade.clone(), "size_in_quote", &[]);
let mut v3Price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut v3Cost: Value = Value::Null;
let mut v3Amount: Value = self.safe_string_k(trade.clone(), "size", &[]);
if (sizeInQuote.as_bool() == Some(true)) {
// calculate base size
v3Cost = v3Amount.clone();
v3Amount = crate::precise::Precise::stringDiv(&v3Amount, &v3Price);
}
let mut v3FeeCost: Value = self.safe_string_k(trade.clone(), "commission", &[]);
let mut amountString: Value = self.safe_string_k(amountObject, "amount", &[v3Amount]);
let mut costString: Value = self.safe_string_k(subtotalObject, "amount", &[v3Cost]);
let mut priceString: Value = Value::Null;
let mut cost: Value = Value::Null;
if (costString != Value::Null) && (amountString != Value::Null) {
priceString = crate::precise::Precise::stringDiv(&costString, &amountString);
} else {
priceString = v3Price;
}
if (priceString != Value::Null) && (amountString != Value::Null) {
cost = crate::precise::Precise::stringMul(&priceString, &amountString);
} else {
cost = costString;
}
let mut feeCurrencyId: Value = self.safe_string_k(feeObject.clone(), "currency", &[]);
let mut feeCost: Value = self.safe_number_k(feeObject, "amount", &[self.parse_number(v3FeeCost, &[])]);
if (feeCurrencyId == Value::Null) && (market != Value::Null) && (feeCost != Value::Null) {
feeCurrencyId = market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null);
}
let mut datetime: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("created_at".into()), Value::Str("trade_time".into()), Value::Str("time".into())]), &[]);
let mut side: Value = self.safe_string_lower2(trade.clone(), Value::Str("resource".into()), Value::Str("side".into()), &[]);
let mut takerOrMaker: Value = self.safe_string_lower_k(trade.clone(), "liquidity_indicator", &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string2(trade.clone(), Value::Str("id".into()), Value::Str("trade_id".into()), &[]));
m.insert("order".to_string(), self.safe_string_k(trade, "order_id", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), (if (side.as_str() == Some("unknown_order_side")) { Value::Null } else { side }));
m.insert("takerOrMaker".to_string(), (if (takerOrMaker.as_str() == Some("unknown_liquidity_indicator")) { Value::Null } else { takerOrMaker }));
m.insert("price".to_string(), priceString);
m.insert("amount".to_string(), amountString);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId, &[]));
m
}));
m
}), &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchMarkets
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/list-products
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/list-public-products
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/currencies
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/exchange-rates
* @description retrieves data on all markets for coinbase
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.usePrivate] use private endpoint for fetching markets
* @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 is_equal(&self.options.as_map().and_then(|__m| __m.get("adjustForTimeDifference")).cloned().unwrap_or(Value::Null), &Value::Bool(true)) {
self.load_time_difference(&[]).await;
}
let mut method: Option<String> = self.safe_string_k(self.options.clone(), "fetchMarkets", &[Value::Str("fetchMarketsV3".into())]).as_str().map(str::to_owned);
if (method.as_deref() == Some("fetchMarketsV3")) {
return self.fetch_markets_v3(&[params.clone()]).await;
}
return self.fetch_markets_v2(&[params]).await;
Value::Null
}
pub async fn fetch_markets_v2(&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.fetch_currencies_from_cache(&[params]).await;
let mut currencies: Value = self.safe_dict_k(response.clone(), "currencies", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut exchangeRates: Value = self.safe_dict_k(response, "exchangeRates", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_list_k(currencies, "data", &[Value::from(vec![])]);
let mut dataById: Value = self.index_by(data.clone(), Value::Str("id".into()));
let mut rates: Value = self.safe_dict(self.safe_dict_k(exchangeRates, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("rates".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseIds: Value = object_keys(&rates);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_520: bool = true;
while { if !__for_first_520 { 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_520 = false; i.as_f64().unwrap_or(f64::NAN) < ((baseIds.len() as i64) as f64) } {
let mut baseId: Value = baseIds.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 base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut type_var: Value = (if (in_op(&dataById, &baseId)) { Value::Str("fiat".into()) } else { Value::Str("crypto".into()) });
// https://github.com/ccxt/ccxt/issues/6066
if (type_var.as_str() == Some("crypto")) {
{
let mut j: Value = Value::Int(0);
let mut __for_first_519: bool = true;
while { if !__for_first_519 { 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_519 = false; j.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut quoteCurrency: Value = data.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 quoteId: Value = self.safe_string_k(quoteCurrency.clone(), "id", &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
append_to_array(&mut result, self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseId, Value::Str("-".into())).into()), quoteId).into()));
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(true));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Null);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
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(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(quoteCurrency.clone(), "min_size", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), quoteCurrency);
m
})]));
}
}
}
}
}
return result;
Value::Null
}
pub async fn fetch_markets_v3(&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 usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMarkets".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut spotUnresolvedPromises: Value = Value::from(vec![]);
if is_true(&usePrivate) {
append_to_array(&mut spotUnresolvedPromises, self.v3_private_get_brokerage_products(&[params.clone()]).await);
} else {
append_to_array(&mut spotUnresolvedPromises, self.v3_public_get_brokerage_market_products(&[params.clone()]).await);
}
//
// {
// products: [
// {
// product_id: 'BTC-USD',
// price: '67060',
// price_percentage_change_24h: '3.30054960636883',
// volume_24h: '10967.87426597',
// volume_percentage_change_24h: '141.73048325503036',
// base_increment: '0.00000001',
// quote_increment: '0.01',
// quote_min_size: '1',
// quote_max_size: '150000000',
// base_min_size: '0.00000001',
// base_max_size: '3400',
// base_name: 'Bitcoin',
// quote_name: 'US Dollar',
// watched: false,
// is_disabled: false,
// new: false,
// status: 'online',
// cancel_only: false,
// limit_only: false,
// post_only: false,
// trading_disabled: false,
// auction_mode: false,
// product_type: 'SPOT',
// quote_currency_id: 'USD',
// base_currency_id: 'BTC',
// fcm_trading_session_details: null,
// mid_market_price: '',
// alias: '',
// alias_to: [ 'BTC-USDC' ],
// base_display_symbol: 'BTC',
// quote_display_symbol: 'USD',
// view_only: false,
// price_increment: '0.01',
// display_name: 'BTC-USD',
// product_venue: 'CBE'
// },
// ...
// ],
// num_products: '646'
// }
//
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
append_to_array(&mut spotUnresolvedPromises, self.v3_private_get_brokerage_transaction_summary(&[params.clone()]).await);
}
//
// {
// total_volume: '9.995989116664404',
// total_fees: '0.07996791093331522',
// fee_tier: {
// pricing_tier: 'Advanced 1',
// usd_from: '0',
// usd_to: '1000',
// taker_fee_rate: '0.008',
// maker_fee_rate: '0.006',
// aop_from: '',
// aop_to: ''
// },
// margin_rate: null,
// goods_and_services_tax: null,
// advanced_trade_only_volume: '9.995989116664404',
// advanced_trade_only_fees: '0.07996791093331522',
// coinbase_pro_volume: '0',
// coinbase_pro_fees: '0',
// total_balance: '',
// has_promo_fee: false
// }
//
let mut promises: Value = promise_all(&spotUnresolvedPromises).await;
let mut unresolvedContractPromises: Value = Value::from(vec![]);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let __ws_arg_8 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_type".to_string(), Value::Str("FUTURE".into()));
m
})]);
unresolvedContractPromises = Value::from(vec![self.v3_public_get_brokerage_market_products(&[__ws_arg_8]).await, self.v3_public_get_brokerage_market_products(&[self.extend(params, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_type".to_string(), Value::Str("FUTURE".into()));
m.insert("contract_expiry_type".to_string(), Value::Str("PERPETUAL".into()));
m
})])]).await]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
unresolvedContractPromises = Value::from(vec![]); // the sync version of ccxt won't have the promise.all line so the request is made here. Some users can't access perpetual products
}
let mut contractPromises: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
contractPromises = promise_all(&unresolvedContractPromises).await; // some users don't have access to contracts
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
contractPromises = Value::from(vec![]);
}
let mut spot: Value = self.safe_dict(promises.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fees: Value = self.safe_dict(promises, Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut expiringFutures: Value = self.safe_dict(contractPromises.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut perpetualFutures: Value = self.safe_dict(contractPromises.clone(), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut expiringFees: Value = self.safe_dict(contractPromises.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut perpetualFees: Value = self.safe_dict(contractPromises, Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
//
// {
// "total_volume": 0,
// "total_fees": 0,
// "fee_tier": {
// "pricing_tier": "",
// "usd_from": "0",
// "usd_to": "10000",
// "taker_fee_rate": "0.006",
// "maker_fee_rate": "0.004"
// },
// "margin_rate": null,
// "goods_and_services_tax": null,
// "advanced_trade_only_volume": 0,
// "advanced_trade_only_fees": 0,
// "coinbase_pro_volume": 0,
// "coinbase_pro_fees": 0
// }
//
let mut feeTier: Value = self.safe_dict_k(fees, "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut expiringFeeTier: Value = self.safe_dict_k(expiringFees, "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); // fee tier null?
let mut perpetualFeeTier: Value = self.safe_dict_k(perpetualFees, "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); // fee tier null?
let mut data: Value = self.safe_list_k(spot, "products", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_521: bool = true;
while { if !__for_first_521 { 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_521 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_spot_market(data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), feeTier.clone()));
}
}
let mut futureData: Value = self.safe_list_k(expiringFutures, "products", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_522: bool = true;
while { if !__for_first_522 { 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_522 = false; i.as_f64().unwrap_or(f64::NAN) < ((futureData.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_contract_market(futureData.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), expiringFeeTier.clone()));
}
}
let mut perpetualData: Value = self.safe_list_k(perpetualFutures, "products", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_523: bool = true;
while { if !__for_first_523 { 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_523 = false; i.as_f64().unwrap_or(f64::NAN) < ((perpetualData.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_contract_market(perpetualData.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), perpetualFeeTier.clone()));
}
}
let mut newMarkets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_524: bool = true;
while { if !__for_first_524 { 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_524 = false; i.as_f64().unwrap_or(f64::NAN) < ((result.len() as i64) as f64) } {
let mut market: Value = result.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 info: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut realMarketIds: Value = self.safe_list_k(info, "alias_to", &[Value::from(vec![])]);
let mut length: f64 = ((realMarketIds.len() as i64) as f64);
if length > ((0i64) as f64) {
add_element_to_object(&mut market, &Value::Str("alias".into()), realMarketIds.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
} else {
add_element_to_object(&mut market, &Value::Str("alias".into()), Value::Null);
}
append_to_array(&mut newMarkets, market);
}
}
return newMarkets;
Value::Null
}
pub fn parse_spot_market(&self, mut market: Value, mut feeTier: Value) -> Value {
let __feeTier_empty = indexmap::IndexMap::new();
let feeTier = feeTier.as_map().unwrap_or(&__feeTier_empty);
//
// {
// "product_id": "TONE-USD",
// "price": "0.01523",
// "price_percentage_change_24h": "1.94109772423025",
// "volume_24h": "19773129",
// "volume_percentage_change_24h": "437.0170530929949",
// "base_increment": "1",
// "quote_increment": "0.00001",
// "quote_min_size": "1",
// "quote_max_size": "10000000",
// "base_min_size": "26.7187147229469674",
// "base_max_size": "267187147.2294696735908216",
// "base_name": "TE-FOOD",
// "quote_name": "US Dollar",
// "watched": false,
// "is_disabled": false,
// "new": false,
// "status": "online",
// "cancel_only": false,
// "limit_only": false,
// "post_only": false,
// "trading_disabled": false,
// "auction_mode": false,
// "product_type": "SPOT",
// "quote_currency_id": "USD",
// "base_currency_id": "TONE",
// "fcm_trading_session_details": null,
// "mid_market_price": ""
// }
//
let mut id: Value = self.safe_string_k(market.clone(), "product_id", &[]);
let mut baseId: Value = self.safe_string_k(market.clone(), "base_currency_id", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quote_currency_id", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut marketType: Value = self.safe_string_lower_k(market.clone(), "product_type", &[]);
let mut tradingDisabled: Value = self.safe_bool_k(market.clone(), "trading_disabled", &[]);
let mut stablePairs: Value = self.safe_list_k(self.options.clone(), "stablePairs", &[Value::from(vec![])]);
let mut defaultTakerFee: Value = self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("taker".into()), &[]);
let mut defaultMakerFee: Value = self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("maker".into()), &[]);
let mut takerFee: Value = (if self.in_array(id.clone(), stablePairs.clone()).as_bool() == Some(true) { Value::Float(0.00001) } else { (match feeTier.get("taker_fee_rate") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => defaultTakerFee }, _ => defaultTakerFee }) });
let mut makerFee: Value = (if self.in_array(id.clone(), stablePairs).as_bool() == Some(true) { Value::Int(0) } else { (match feeTier.get("maker_fee_rate") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => defaultMakerFee }, _ => defaultMakerFee }) });
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()));
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), marketType.clone());
m.insert("spot".to_string(), (Value::Bool(marketType.as_str() == Some("spot"))));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(tradingDisabled.as_bool() != Some(true)));
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("taker".to_string(), takerFee);
m.insert("maker".to_string(), makerFee);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_number_k(market.clone(), "base_increment", &[]));
m.insert("price".to_string(), self.safe_number2(market.clone(), Value::Str("price_increment".into()), Value::Str("quote_increment".into()), &[]));
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(), self.safe_number_k(market.clone(), "base_min_size", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "base_max_size", &[]));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "quote_min_size", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "quote_max_size", &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub fn parse_contract_market(&self, mut market: Value, mut feeTier: Value) -> Value {
let __feeTier_empty = indexmap::IndexMap::new();
let feeTier = feeTier.as_map().unwrap_or(&__feeTier_empty);
// expiring
//
// {
// "product_id":"BIT-26APR24-CDE",
// "price":"71145",
// "price_percentage_change_24h":"-2.36722931247427",
// "volume_24h":"108549",
// "volume_percentage_change_24h":"155.78255337197794",
// "base_increment":"1",
// "quote_increment":"0.01",
// "quote_min_size":"0",
// "quote_max_size":"100000000",
// "base_min_size":"1",
// "base_max_size":"100000000",
// "base_name":"",
// "quote_name":"US Dollar",
// "watched":false,
// "is_disabled":false,
// "new":false,
// "status":"",
// "cancel_only":false,
// "limit_only":false,
// "post_only":false,
// "trading_disabled":false,
// "auction_mode":false,
// "product_type":"FUTURE",
// "quote_currency_id":"USD",
// "base_currency_id":"",
// "fcm_trading_session_details":{
// "is_session_open":true,
// "open_time":"2024-04-08T22:00:00Z",
// "close_time":"2024-04-09T21:00:00Z"
// },
// "mid_market_price":"71105",
// "alias":"",
// "alias_to":[
// ],
// "base_display_symbol":"",
// "quote_display_symbol":"USD",
// "view_only":false,
// "price_increment":"5",
// "display_name":"BTC 26 APR 24",
// "product_venue":"FCM",
// "future_product_details":{
// "venue":"cde",
// "contract_code":"BIT",
// "contract_expiry":"2024-04-26T15:00:00Z",
// "contract_size":"0.01",
// "contract_root_unit":"BTC",
// "group_description":"Nano Bitcoin Futures",
// "contract_expiry_timezone":"Europe/London",
// "group_short_description":"Nano BTC",
// "risk_managed_by":"MANAGED_BY_FCM",
// "contract_expiry_type":"EXPIRING",
// "contract_display_name":"BTC 26 APR 24"
// }
// }
//
// perpetual
//
// {
// "product_id":"ETH-PERP-INTX",
// "price":"3630.98",
// "price_percentage_change_24h":"0.65142426292038",
// "volume_24h":"114020.1501",
// "volume_percentage_change_24h":"63.33650787154869",
// "base_increment":"0.0001",
// "quote_increment":"0.01",
// "quote_min_size":"10",
// "quote_max_size":"50000000",
// "base_min_size":"0.0001",
// "base_max_size":"50000",
// "base_name":"",
// "quote_name":"USDC",
// "watched":false,
// "is_disabled":false,
// "new":false,
// "status":"",
// "cancel_only":false,
// "limit_only":false,
// "post_only":false,
// "trading_disabled":false,
// "auction_mode":false,
// "product_type":"FUTURE",
// "quote_currency_id":"USDC",
// "base_currency_id":"",
// "fcm_trading_session_details":null,
// "mid_market_price":"3630.975",
// "alias":"",
// "alias_to":[],
// "base_display_symbol":"",
// "quote_display_symbol":"USDC",
// "view_only":false,
// "price_increment":"0.01",
// "display_name":"ETH PERP",
// "product_venue":"INTX",
// "future_product_details":{
// "venue":"",
// "contract_code":"ETH",
// "contract_expiry":null,
// "contract_size":"1",
// "contract_root_unit":"ETH",
// "group_description":"",
// "contract_expiry_timezone":"",
// "group_short_description":"",
// "risk_managed_by":"MANAGED_BY_VENUE",
// "contract_expiry_type":"PERPETUAL",
// "perpetual_details":{
// "open_interest":"0",
// "funding_rate":"0.000016",
// "funding_time":"2024-04-09T09:00:00.000008Z",
// "max_leverage":"10"
// },
// "contract_display_name":"ETH PERPETUAL"
// }
// }
//
let mut id: Value = self.safe_string_k(market.clone(), "product_id", &[]);
let mut futureProductDetails: Value = self.safe_dict_k(market.clone(), "future_product_details", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut contractExpiryType: Option<String> = self.safe_string_k(futureProductDetails.clone(), "contract_expiry_type", &[]).as_str().map(str::to_owned);
let mut contractSize: Value = self.safe_number_k(futureProductDetails.clone(), "contract_size", &[]);
let mut contractExpire: Value = self.safe_string_k(futureProductDetails.clone(), "contract_expiry", &[]);
let mut expireTimestamp: Value = self.parse8601(contractExpire);
let mut expireDateTime: Value = self.iso8601(expireTimestamp.clone());
let mut isSwap: Value = (Value::Bool(contractExpiryType.as_deref() == Some("PERPETUAL")));
let mut baseId: Value = self.safe_string_k(futureProductDetails, "contract_root_unit", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quote_currency_id", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut tradingDisabled: Value = self.safe_bool_k(market.clone(), "is_disabled", &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut type_var: Value = Value::Null;
if matches!(&isSwap, Value::Bool(true)) {
type_var = Value::Str("swap".into());
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), quote).into());
} else {
type_var = Value::Str("future".into());
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), quote).into()), Value::Str("-".into())).into()), self.yymmdd(expireTimestamp.clone(), &[])).into());
}
let mut takerFeeRate: Value = (match feeTier.get("taker_fee_rate") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => Value::Null }, _ => Value::Null });
let mut makerFeeRate: Value = (match feeTier.get("maker_fee_rate") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => Value::Null }, _ => Value::Null });
let mut taker: Value = (if ((takerFeeRate != Value::Null) && (takerFeeRate != Value::Null) && (takerFeeRate.as_f64() != Some(0.0))) { takerFeeRate } else { self.parse_number(Value::Str("0.06".into()), &[]) });
let mut maker: Value = (if ((makerFeeRate != Value::Null) && (makerFeeRate != Value::Null) && (makerFeeRate.as_f64() != Some(0.0))) { makerFeeRate } else { self.parse_number(Value::Str("0.04".into()), &[]) });
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.clone());
m.insert("settle".to_string(), quote);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), quoteId);
m.insert("type".to_string(), type_var);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), isSwap.clone());
m.insert("future".to_string(), Value::Bool(!(matches!(&isSwap, Value::Bool(true)))));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(tradingDisabled.as_bool() != Some(true)));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), contractSize);
m.insert("expiry".to_string(), expireTimestamp);
m.insert("expiryDatetime".to_string(), expireDateTime);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_number_k(market.clone(), "base_increment", &[]));
m.insert("price".to_string(), self.safe_number2(market.clone(), Value::Str("price_increment".into()), Value::Str("quote_increment".into()), &[]));
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(), self.safe_number_k(market.clone(), "base_min_size", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "base_max_size", &[]));
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "quote_min_size", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "quote_max_size", &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub async fn fetch_currencies_from_cache(&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 options: Value = self.safe_dict_k(self.options.clone(), "fetchCurrencies", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(options.clone(), "timestamp", &[]);
let mut expires: Value = self.safe_integer_k(options.clone(), "expires", &[Value::Int(1000)]);
let mut now: Value = self.milliseconds();
if (timestamp == Value::Null) || (((match (&(now), &(timestamp)) { (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 })).as_f64().unwrap_or(f64::NAN) > expires.as_f64().unwrap_or(f64::NAN)) {
let mut promises: Value = Value::from(vec![self.v2_public_get_currencies(&[params.clone()]).await, self.v2_public_get_currencies_crypto(&[params.clone()]).await]);
let mut promisesResult: Value = promise_all(&promises).await;
let mut fiatResponse: Value = self.safe_dict(promisesResult.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
//
// [
// "data": {
// id: 'IMP',
// name: 'Isle of Man Pound',
// min_size: '0.01'
// },
// ...
// ]
//
let mut cryptoResponse: Value = self.safe_dict(promisesResult, Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
//
// {
// asset_id: '9476e3be-b731-47fa-82be-347fabc573d9',
// code: 'AERO',
// name: 'Aerodrome Finance',
// color: '#0433FF',
// sort_index: '340',
// exponent: '8',
// type: 'crypto',
// address_regex: '^(?:0x)?[0-9a-fA-F]{40}$'
// }
//
let mut fiatData: Value = self.safe_list_k(fiatResponse, "data", &[Value::from(vec![])]);
let mut cryptoData: Value = self.safe_list_k(cryptoResponse, "data", &[Value::from(vec![])]);
let mut exchangeRates: Value = self.v2_public_get_exchange_rates(&[params]).await;
let __ws_arg_9 = self.array_concat(fiatData, cryptoData);
{ let __be_tmp = self.extend(options.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currencies".to_string(), __ws_arg_9);
m.insert("exchangeRates".to_string(), exchangeRates);
m.insert("timestamp".to_string(), now);
m
})]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("fetchCurrencies".into(), __be_tmp); } }
}
return self.safe_dict_k(self.options.clone(), "fetchCurrencies", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
/*
* @method
* @name coinbase#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/currencies
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/exchange-rates
* @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 promises: Value = Value::from(vec![self.v2_public_get_currencies(&[params.clone()]).await, self.v2_public_get_currencies_crypto(&[params.clone()]).await, self.v2_public_get_exchange_rates(&[params]).await]);
let mut promisesResult: Value = promise_all(&promises).await;
let mut fiatResponse: Value = self.safe_dict(promisesResult.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
//
// [
// "data": [
// {
// id: 'IMP',
// name: 'Isle of Man Pound',
// min_size: '0.01'
// },
// ...
//
let mut cryptoResponse: Value = self.safe_dict(promisesResult.clone(), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
//
// [
// "data": [
// {
// asset_id: '9476e3be-b731-47fa-82be-347fabc573d9',
// code: 'AERO',
// name: 'Aerodrome Finance',
// color: '#0433FF',
// sort_index: '340',
// exponent: '8',
// type: 'crypto',
// address_regex: '^(?:0x)?[0-9a-fA-F]{40}$'
// },
// ...
//
let mut ratesResponse: Value = self.safe_dict(promisesResult, Value::Int(2), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fiatData: Value = self.safe_list_k(fiatResponse, "data", &[Value::from(vec![])]);
let mut cryptoData: Value = self.safe_list_k(cryptoResponse, "data", &[Value::from(vec![])]);
let mut ratesData: Value = self.safe_dict_k(ratesResponse, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rates: Value = self.safe_dict_k(ratesData, "rates", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ratesIds: Value = object_keys(&rates);
let mut currencies: Value = self.array_concat(fiatData, cryptoData);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut networksById: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_525: bool = true;
while { if !__for_first_525 { 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_525 = false; i.as_f64().unwrap_or(f64::NAN) < ((currencies.len() as i64) as f64) } {
let mut currency: Value = currencies.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 assetId: Option<String> = self.safe_string_k(currency.clone(), "asset_id", &[]).as_str().map(str::to_owned);
let mut id: Value = self.safe_string2(currency.clone(), Value::Str("id".into()), Value::Str("code".into()), &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut name: Value = self.safe_string_k(currency.clone(), "name", &[]);
if (code != Value::Null) {
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("networks".into())), &code, to_lower(&name));
}
if (code != Value::Null) {
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("networksById".into())), &code, to_lower(&name));
}
let mut type_var: Value = (if (assetId.is_some()) { Value::Str("crypto".into()) } else { Value::Str("fiat".into()) });
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), currency.clone());
m.insert("id".to_string(), id);
m.insert("code".to_string(), code.clone());
m.insert("type".to_string(), type_var);
m.insert("name".to_string(), name.clone());
m.insert("active".to_string(), Value::Bool(true));
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(currency, "min_size", &[]));
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
}))); }
}
if (assetId.is_some()) {
let mut lowerCaseName: Value = to_lower(&name);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), lowerCaseName.clone()); }
}
if let Value::Dict(__d) = &mut networksById { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&lowerCaseName), code.clone()); }
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_526: bool = true;
while { if !__for_first_526 { 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_526 = false; i.as_f64().unwrap_or(f64::NAN) < ((ratesIds.len() as i64) as f64) } {
let mut currencyId: Value = ratesIds.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(currencyId.clone(), &[]);
if (code == Value::Null) || !(in_op(&result, &code)) {
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("id".to_string(), currencyId);
m.insert("code".to_string(), code.clone());
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}))); }
}
}
}
}
let __ws_arg_10 = crate::value::get_value_k(&self.options, "networks");
{ let __be_tmp = self.extend(networks, &[__ws_arg_10]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("networks".into(), __be_tmp); } }
let __ws_arg_11 = crate::value::get_value_k(&self.options, "networksById");
{ let __be_tmp = self.extend(networksById, &[__ws_arg_11]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("networksById".into(), __be_tmp); } }
return result;
Value::Null
}
/*
* @method
* @name coinbase#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/list-products
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/list-public-products
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/exchange-rates
* @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
* @param {boolean} [params.usePrivate] use private endpoint for fetching tickers
* @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
}));
let mut method: Option<String> = self.safe_string_k(self.options.clone(), "fetchTickers", &[Value::Str("fetchTickersV3".into())]).as_str().map(str::to_owned);
if (method.as_deref() == Some("fetchTickersV3")) {
return self.fetch_tickers_v3(&[symbols.clone(), params.clone()]).await;
}
return self.fetch_tickers_v2(&[symbols, params]).await;
Value::Null
}
pub async fn fetch_tickers_v2(&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;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_12 = self.extend(request, &[params]);
let mut response: Value = self.v2_public_get_exchange_rates(&[__ws_arg_12]).await;
//
// {
// "data":{
// "currency":"USD",
// "rates":{
// "AED":"3.6731",
// "AFN":"103.163942",
// "ALL":"106.973038",
// }
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rates: Value = self.safe_dict_k(data.clone(), "rates", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut quoteId: Value = self.safe_string_k(data, "currency", &[]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut baseIds: Value = object_keys(&rates);
let mut delimiter: Value = Value::Str("-".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_527: bool = true;
while { if !__for_first_527 { 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_527 = false; i.as_f64().unwrap_or(f64::NAN) < ((baseIds.len() as i64) as f64) } {
let mut baseId: Value = baseIds.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 marketId: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseId, delimiter).into()), quoteId).into());
let mut market: Value = self.safe_market(&[marketId, Value::Null, delimiter.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), self.parse_ticker(rates.as_map().and_then(|__m| baseId.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null), &[market])); }
}
}
return self.filter_by_array_tickers(result, Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub async fn fetch_tickers_v3(&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;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbols != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_ids".into(), self.market_ids(&[symbols.clone()])); }
}
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchTickers".into()), &[self.get_market_from_symbols(&[symbols.clone()]), params.clone(), Value::Str("default".into())]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (marketType != Value::Null) && (marketType.as_str() != Some("default")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_type".into(), (if (marketType.as_str() == Some("swap")) { Value::Str("FUTURE".into()) } else { Value::Str("SPOT".into()) })); }
}
let mut response: Value = Value::Null;
let mut usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTickers".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&usePrivate) {
let __ws_arg_13 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_products(&[__ws_arg_13]).await;
} else {
let __ws_arg_14 = self.extend(request, &[params]);
response = self.v3_public_get_brokerage_market_products(&[__ws_arg_14]).await;
}
//
// {
// "products": [
// {
// "product_id": "TONE-USD",
// "price": "0.01523",
// "price_percentage_change_24h": "1.94109772423025",
// "volume_24h": "19773129",
// "volume_percentage_change_24h": "437.0170530929949",
// "base_increment": "1",
// "quote_increment": "0.00001",
// "quote_min_size": "1",
// "quote_max_size": "10000000",
// "base_min_size": "26.7187147229469674",
// "base_max_size": "267187147.2294696735908216",
// "base_name": "TE-FOOD",
// "quote_name": "US Dollar",
// "watched": false,
// "is_disabled": false,
// "new": false,
// "status": "online",
// "cancel_only": false,
// "limit_only": false,
// "post_only": false,
// "trading_disabled": false,
// "auction_mode": false,
// "product_type": "SPOT",
// "quote_currency_id": "USD",
// "base_currency_id": "TONE",
// "fcm_trading_session_details": null,
// "mid_market_price": ""
// },
// ...
// ],
// "num_products": 549
// }
//
let mut data: Value = self.safe_list_k(response, "products", &[Value::from(vec![])]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_528: bool = true;
while { if !__for_first_528 { 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_528 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut marketId: Value = self.safe_string_k(entry.clone(), "product_id", &[]);
let mut market: Value = self.safe_market(&[marketId, Value::Null, Value::Str("-".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), self.parse_ticker(entry, &[market])); }
}
}
return self.filter_by_array_tickers(result, Value::Str("symbol".into()), &[symbols]);
Value::Null
}
/*
* @method
* @name coinbase#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.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-market-trades
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/get-public-market-trades
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/prices
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.usePrivate] whether to use the private endpoint for fetching the ticker
* @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
}));
let mut method: Option<String> = self.safe_string_k(self.options.clone(), "fetchTicker", &[Value::Str("fetchTickerV3".into())]).as_str().map(str::to_owned);
if (method.as_deref() == Some("fetchTickerV3")) {
return self.fetch_ticker_v3(symbol.clone(), &[params.clone()]).await;
}
return self.fetch_ticker_v2(symbol, &[params]).await;
Value::Null
}
pub async fn fetch_ticker_v2(&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 = self.extend(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
}), &[params]);
let mut spot: Value = self.v2_public_get_prices_symbol_spot(&[request.clone()]).await;
//
// {"data":{"base":"BTC","currency":"USD","amount":"48691.23"}}
//
let mut ask: Value = self.v2_public_get_prices_symbol_buy(&[request.clone()]).await;
//
// {"data":{"base":"BTC","currency":"USD","amount":"48691.23"}}
//
let mut bid: Value = self.v2_public_get_prices_symbol_sell(&[request]).await;
//
// {"data":{"base":"BTC","currency":"USD","amount":"48691.23"}}
//
let mut spotData: Value = self.safe_dict_k(spot, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut askData: Value = self.safe_dict_k(ask, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bidData: Value = self.safe_dict_k(bid, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bidAskLast: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bid".to_string(), self.safe_number_k(bidData, "amount", &[]));
m.insert("ask".to_string(), self.safe_number_k(askData, "amount", &[]));
m.insert("price".to_string(), self.safe_number_k(spotData, "amount", &[]));
m
});
return self.parse_ticker(bidAskLast, &[market]);
Value::Null
}
pub async fn fetch_ticker_v3(&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("product_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("limit".to_string(), Value::Int(1));
m
});
let mut usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTicker".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut response: Value = Value::Null;
if is_true(&usePrivate) {
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_products_product_id_ticker(&[__ws_arg_15]).await;
} else {
let __ws_arg_16 = self.extend(request, &[params]);
response = self.v3_public_get_brokerage_market_products_product_id_ticker(&[__ws_arg_16]).await;
}
//
// {
// "trades": [
// {
// "trade_id": "518078013",
// "product_id": "BTC-USD",
// "price": "28208.1",
// "size": "0.00659179",
// "time": "2023-04-04T23:05:34.492746Z",
// "side": "BUY",
// "bid": "",
// "ask": ""
// }
// ],
// "best_bid": "28208.61",
// "best_ask": "28208.62"
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "trades", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.parse_ticker(first, &[market]);
add_element_to_object(&mut ticker, &Value::Str("bid".into()), self.safe_number_k(response.clone(), "best_bid", &[]));
add_element_to_object(&mut ticker, &Value::Str("ask".into()), self.safe_number_k(response, "best_ask", &[]));
return ticker;
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTickerV2
//
// {
// "bid": 20713.37,
// "ask": 20924.65,
// "price": 20809.83
// }
//
// fetchTickerV3
//
// {
// "trade_id": "10209805",
// "product_id": "BTC-USDT",
// "price": "19381.27",
// "size": "0.1",
// "time": "2023-01-13T20:35:41.865970Z",
// "side": "BUY",
// "bid": "",
// "ask": ""
// }
//
// fetchTickersV2
//
// "48691.23"
//
// fetchTickersV3
//
// [
// {
// "product_id": "ETH-USD",
// "price": "4471.59",
// "price_percentage_change_24h": "0.14243387238731",
// "volume_24h": "87329.92990204",
// "volume_percentage_change_24h": "-60.7789801794578",
// "base_increment": "0.00000001",
// "quote_increment": "0.01",
// "quote_min_size": "1",
// "quote_max_size": "150000000",
// "base_min_size": "0.00000001",
// "base_max_size": "42000",
// "base_name": "Ethereum",
// "quote_name": "US Dollar",
// "watched": false,
// "is_disabled": false,
// "new": false,
// "status": "online",
// "cancel_only": false,
// "limit_only": false,
// "post_only": false,
// "trading_disabled": false,
// "auction_mode": false,
// "product_type": "SPOT",
// "quote_currency_id": "USD",
// "base_currency_id": "ETH",
// "fcm_trading_session_details": null,
// "mid_market_price": "",
// "alias": "",
// "alias_to": [ "ETH-USDC" ],
// "base_display_symbol": "ETH",
// "quote_display_symbol": "USD",
// "view_only": false,
// "price_increment": "0.01",
// "display_name": "ETH-USD",
// "product_venue": "CBE",
// "approximate_quote_24h_volume": "390503641.25",
// "new_at": "2023-01-01T00:00:00Z"
// },
// ...
// ]
//
// fetchBidsAsks
//
// {
// "product_id": "TRAC-EUR",
// "bids": [
// {
// "price": "0.2384",
// "size": "386.1"
// }
// ],
// "asks": [
// {
// "price": "0.2406",
// "size": "672"
// }
// ],
// "time": "2023-06-30T07:15:24.656044Z"
// }
//
let mut bid: Value = self.safe_number_k(ticker.clone(), "bid", &[]);
let mut ask: Value = self.safe_number_k(ticker.clone(), "ask", &[]);
let mut bidVolume: Value = Value::Null;
let mut askVolume: Value = Value::Null;
if (matches!(&ticker, Value::Dict(__d) if __d.contains_key("bids"))) {
let mut bids: Value = self.safe_list_k(ticker.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(ticker.clone(), "asks", &[Value::from(vec![])]);
let mut firstBid: Value = self.safe_dict(bids, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstAsk: Value = self.safe_dict(asks, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
bid = self.safe_number_k(firstBid.clone(), "price", &[]);
bidVolume = self.safe_number_k(firstBid, "size", &[]);
ask = self.safe_number_k(firstAsk.clone(), "price", &[]);
askVolume = self.safe_number_k(firstAsk, "size", &[]);
}
let mut marketId: Value = self.safe_string_k(ticker.clone(), "product_id", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut last: Value = self.safe_number_k(ticker.clone(), "price", &[]);
let mut datetime: Value = self.safe_string_k(ticker.clone(), "time", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("bid".to_string(), bid);
m.insert("ask".to_string(), ask);
m.insert("last".to_string(), last.clone());
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bidVolume".to_string(), bidVolume);
m.insert("askVolume".to_string(), askVolume);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), self.safe_number_k(ticker.clone(), "price_percentage_change_24h", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_number_k(ticker.clone(), "volume_24h", &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "approximate_quote_24h_volume", &[]));
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
pub fn parse_custom_balance(&self, mut response: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut balances: Value = self.safe_list2(response.clone(), Value::Str("data".into()), Value::Str("accounts".into()), &[Value::from(vec![])]);
let mut accounts: Value = (match params.get("type") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => self.options.as_map().and_then(|__m| __m.get("accounts")).cloned().unwrap_or(Value::Null) });
let mut v3Accounts: Value = (match params.get("type") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => self.options.as_map().and_then(|__m| __m.get("v3Accounts")).cloned().unwrap_or(Value::Null) });
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
{
let mut b: Value = Value::Int(0);
let mut __for_first_529: bool = true;
while { if !__for_first_529 { b = (match (&(b), &(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_529 = false; b.as_f64().unwrap_or(f64::NAN) < ((balances.len() as i64) as f64) } {
let mut balance: Value = balances.as_array().and_then(|__arr| match &b { 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 type_var: Value = self.safe_string_k(balance.clone(), "type", &[]);
if self.in_array(type_var.clone(), accounts.clone()).as_bool() == Some(true) {
let mut value: Value = self.safe_dict_k(balance.clone(), "balance", &[]);
if (value != Value::Null) {
let mut currencyId: Value = self.safe_string_k(value.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut total: Value = self.safe_string_k(value.clone(), "amount", &[]);
let mut free: Value = total.clone();
let mut account: Value = self.safe_dict(result.clone(), code.clone(), &[]);
if (account == Value::Null) {
account = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), free.clone());
add_element_to_object(&mut account, &Value::Str("total".into()), total.clone());
} else {
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&account, "free"), &total); add_element_to_object(&mut account, &Value::Str("free".into()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&account, "total"), &total); add_element_to_object(&mut account, &Value::Str("total".into()), __be_tmp); };
}
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account.clone()); }
}
}
} else if self.in_array(type_var, v3Accounts.clone()).as_bool() == Some(true) {
let mut available: Value = self.safe_dict_k(balance.clone(), "available_balance", &[]);
let mut hold: Value = self.safe_dict_k(balance, "hold", &[]);
if (available != Value::Null) && (hold != Value::Null) {
let mut currencyId: Value = self.safe_string_k(available.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut used: Value = self.safe_string_k(hold, "value", &[]);
let mut free: Value = self.safe_string_k(available, "value", &[]);
let mut total: Value = crate::precise::Precise::stringAdd(&used, &free);
let mut account: Value = self.safe_dict(result.clone(), code.clone(), &[]);
if (account == Value::Null) {
account = self.account();
add_element_to_object(&mut account, &Value::Str("free".into()), free.clone());
add_element_to_object(&mut account, &Value::Str("used".into()), used.clone());
add_element_to_object(&mut account, &Value::Str("total".into()), total.clone());
} else {
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&account, "free"), &free); add_element_to_object(&mut account, &Value::Str("free".into()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&account, "used"), &used); add_element_to_object(&mut account, &Value::Str("used".into()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&account, "total"), &total); add_element_to_object(&mut account, &Value::Str("total".into()), __be_tmp); };
}
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 coinbase#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/accounts/list-accounts
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/accounts
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/us-derivatives/get-futures-balance-summary
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.v3] default false, set true to use v3 api endpoint
* @param {string} [params.type] "spot" (default) or "swap" or "future"
* @param {int} [params.limit] default 250, maximum number of accounts to return
* @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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
let mut isV3: Value = self.safe_bool_k(params.clone(), "v3", &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("v3".into())]), &[]);
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params.clone()]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut method: Option<String> = self.safe_string_k(self.options.clone(), "fetchBalance", &[Value::Str("v3PrivateGetBrokerageAccounts".into())]).as_str().map(str::to_owned);
if (marketType.as_str() == Some("future")) {
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_cfm_balance_summary(&[__ws_arg_17]).await;
} else if (isV3.as_bool() == Some(true)) || (method.as_deref() == Some("v3PrivateGetBrokerageAccounts")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Int(250)); }
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_accounts(&[__ws_arg_18]).await;
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Int(250)); }
let __ws_arg_19 = self.extend(request, &[params.clone()]);
response = self.v2_private_get_accounts(&[__ws_arg_19]).await;
}
//
// v2PrivateGetAccounts
// {
// "pagination":{
// "ending_before":null,
// "starting_after":null,
// "previous_ending_before":null,
// "next_starting_after":"6b17acd6-2e68-5eb0-9f45-72d67cef578a",
// "limit":100,
// "order":"desc",
// "previous_uri":null,
// "next_uri":"/v2/accounts?limit=100\u0026starting_after=6b17acd6-2e68-5eb0-9f45-72d67cef578b"
// },
// "data":[
// {
// "id":"94ad58bc-0f15-5309-b35a-a4c86d7bad60",
// "name":"MINA Wallet",
// "primary":false,
// "type":"wallet",
// "currency":{
// "code":"MINA",
// "name":"Mina",
// "color":"#EA6B48",
// "sort_index":397,
// "exponent":9,
// "type":"crypto",
// "address_regex":"^(B62)[A-Za-z0-9]{52}$",
// "asset_id":"a4ffc575-942c-5e26-b70c-cb3befdd4229",
// "slug":"mina"
// },
// "balance":{"amount":"0.000000000","currency":"MINA"},
// "created_at":"2022-03-25T00:36:16Z",
// "updated_at":"2022-03-25T00:36:16Z",
// "resource":"account",
// "resource_path":"/v2/accounts/94ad58bc-0f15-5309-b35a-a4c86d7bad60",
// "allow_deposits":true,
// "allow_withdrawals":true
// },
// ]
// }
//
// v3PrivateGetBrokerageAccounts
// {
// "accounts": [
// {
// "uuid": "11111111-1111-1111-1111-111111111111",
// "name": "USDC Wallet",
// "currency": "USDC",
// "available_balance": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// },
// "default": true,
// "active": true,
// "created_at": "2023-01-04T06:20:06.456Z",
// "updated_at": "2023-01-04T06:20:07.181Z",
// "deleted_at": null,
// "type": "ACCOUNT_TYPE_CRYPTO",
// "ready": false,
// "hold": {
// "value": "0.0000000000000000",
// "currency": "USDC"
// }
// },
// ...
// ],
// "has_next": false,
// "cursor": "",
// "size": 9
// }
//
add_element_to_object(&mut params, &Value::Str("type".into()), marketType);
return self.parse_custom_balance(response, &[params]);
Value::Null
}
/*
* @method
* @name coinbase#fetchLedger
* @description Fetch the history of changes, i.e. actions done by the user or operations that altered the balance. Will return staking rewards, and crypto deposits or withdrawals.
* @see https://docs.cdp.coinbase.com/coinbase-app/track-apis/transactions
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchLedger".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchLedger".into()), &[code.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("next_starting_after".into()), Value::Str("starting_after".into()), Value::Null, Value::Int(100)]).await;
}
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code.clone());
}
let mut request: Value = Value::Null;
{ let __destr_tmp = self.prepare_account_request_with_currency_code(&[code, limit.clone(), params.clone()]).await; request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
// for pagination use parameter 'starting_after'
// the value for the next page can be obtained from the result of the previous call in the 'pagination' field
// eg: instance.last_http_response -> pagination.next_starting_after
let __ws_arg_20 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_get_accounts_account_id_transactions(&[__ws_arg_20]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
let mut ledger: Value = self.parse_ledger(data, &[currency, since, limit]);
let mut length: Value = Value::Int(ledger.len() as i64);
if (length.as_f64() == Some(0.0)) {
return ledger;
}
let mut lastIndex: Value = (match (&(length), &(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 });
let mut last: Value = self.safe_dict(ledger.clone(), lastIndex.clone(), &[]);
let mut pagination: Value = self.safe_dict_k(response, "pagination", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cursor: Value = self.safe_string_k(pagination, "next_starting_after", &[]);
if (cursor != Value::Null) && (cursor.as_str() != Some("")) {
add_element_to_object(get_value_mut(&mut last, &Value::Str("info".into())), &Value::Str("next_starting_after".into()), cursor);
add_element_to_object(&mut ledger, &lastIndex, last);
}
return ledger;
Value::Null
}
pub fn parse_ledger_entry_status(&self, mut status: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("completed".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(types, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("buy".to_string(), Value::Str("trade".into()));
m.insert("sell".to_string(), Value::Str("trade".into()));
m.insert("fiat_deposit".to_string(), Value::Str("transaction".into()));
m.insert("fiat_withdrawal".to_string(), Value::Str("transaction".into()));
m.insert("exchange_deposit".to_string(), Value::Str("transaction".into()));
m.insert("exchange_withdrawal".to_string(), Value::Str("transaction".into()));
m.insert("send".to_string(), Value::Str("transaction".into()));
m.insert("pro_deposit".to_string(), Value::Str("transaction".into()));
m.insert("pro_withdrawal".to_string(), Value::Str("transaction".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// crypto deposit transaction
//
// {
// "id": "34e4816b-4c8c-5323-a01c-35a9fa26e490",
// "type": "send",
// "status": "completed",
// "amount": { amount: "28.31976528", currency: "BCH" },
// "native_amount": { amount: "2799.65", currency: "GBP" },
// "description": null,
// "created_at": "2019-02-28T12:35:20Z",
// "updated_at": "2019-02-28T12:43:24Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c01d7364-edd7-5f3a-bd1d-de53d4cbb25e/transactions/34e4816b-4c8c-5323-a01c-35a9fa26e490",
// "instant_exchange": false,
// "network": {
// "status": "confirmed",
// "hash": "56222d865dae83774fccb2efbd9829cf08c75c94ce135bfe4276f3fb46d49701",
// "transaction_url": "https://bch.btc.com/56222d865dae83774fccb2efbd9829cf08c75c94ce135bfe4276f3fb46d49701"
// },
// "from": { resource: "bitcoin_cash_network", currency: "BCH" },
// "details": { title: 'Received Bitcoin Cash', subtitle: "From Bitcoin Cash address" }
// }
//
// crypto withdrawal transaction
//
// {
// "id": "459aad99-2c41-5698-ac71-b6b81a05196c",
// "type": "send",
// "status": "completed",
// "amount": { amount: "-0.36775642", currency: "BTC" },
// "native_amount": { amount: "-1111.65", currency: "GBP" },
// "description": null,
// "created_at": "2019-03-20T08:37:07Z",
// "updated_at": "2019-03-20T08:49:33Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c6afbd34-4bd0-501e-8616-4862c193cd84/transactions/459aad99-2c41-5698-ac71-b6b81a05196c",
// "instant_exchange": false,
// "network": {
// "status": "confirmed",
// "hash": "2732bbcf35c69217c47b36dce64933d103895277fe25738ffb9284092701e05b",
// "transaction_url": "https://blockchain.info/tx/2732bbcf35c69217c47b36dce64933d103895277fe25738ffb9284092701e05b",
// "transaction_fee": { amount: "0.00000000", currency: "BTC" },
// "transaction_amount": { amount: "0.36775642", currency: "BTC" },
// "confirmations": 15682
// },
// "to": {
// "resource": "bitcoin_address",
// "address": "1AHnhqbvbYx3rnZx8uC7NbFZaTe4tafFHX",
// "currency": "BTC",
// "address_info": { address: "1AHnhqbvbYx3rnZx8uC7NbFZaTe4tafFHX" }
// },
// "idem": "da0a2f14-a2af-4c5a-a37e-d4484caf582bsend",
// "application": {
// "id": "5756ab6e-836b-553b-8950-5e389451225d",
// "resource": "application",
// "resource_path": "/v2/applications/5756ab6e-836b-553b-8950-5e389451225d"
// },
// "details": { title: 'Sent Bitcoin', subtitle: "To Bitcoin address" }
// }
//
// withdrawal transaction from coinbase to coinbasepro
//
// {
// "id": "5b1b9fb8-5007-5393-b923-02903b973fdc",
// "type": "pro_deposit",
// "status": "completed",
// "amount": { amount: "-0.00001111", currency: "BCH" },
// "native_amount": { amount: "0.00", currency: "GBP" },
// "description": null,
// "created_at": "2019-02-28T13:31:58Z",
// "updated_at": "2019-02-28T13:31:58Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c01d7364-edd7-5f3a-bd1d-de53d4cbb25e/transactions/5b1b9fb8-5007-5393-b923-02903b973fdc",
// "instant_exchange": false,
// "application": {
// "id": "5756ab6e-836b-553b-8950-5e389451225d",
// "resource": "application",
// "resource_path": "/v2/applications/5756ab6e-836b-553b-8950-5e389451225d"
// },
// "details": { title: 'Transferred Bitcoin Cash', subtitle: "To Coinbase Pro" }
// }
//
// withdrawal transaction from coinbase to gdax
//
// {
// "id": "badb7313-a9d3-5c07-abd0-00f8b44199b1",
// "type": "exchange_deposit",
// "status": "completed",
// "amount": { amount: "-0.43704149", currency: "BCH" },
// "native_amount": { amount: "-51.90", currency: "GBP" },
// "description": null,
// "created_at": "2019-03-19T10:30:40Z",
// "updated_at": "2019-03-19T10:30:40Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c01d7364-edd7-5f3a-bd1d-de53d4cbb25e/transactions/badb7313-a9d3-5c07-abd0-00f8b44199b1",
// "instant_exchange": false,
// "details": { title: 'Transferred Bitcoin Cash', subtitle: "To GDAX" }
// }
//
// deposit transaction from gdax to coinbase
//
// {
// "id": "9c4b642c-8688-58bf-8962-13cef64097de",
// "type": "exchange_withdrawal",
// "status": "completed",
// "amount": { amount: "0.57729420", currency: "BTC" },
// "native_amount": { amount: "4418.72", currency: "GBP" },
// "description": null,
// "created_at": "2018-02-17T11:33:33Z",
// "updated_at": "2018-02-17T11:33:33Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c6afbd34-4bd0-501e-8616-4862c193cd84/transactions/9c4b642c-8688-58bf-8962-13cef64097de",
// "instant_exchange": false,
// "details": { title: 'Transferred Bitcoin', subtitle: "From GDAX" }
// }
//
// deposit transaction from coinbasepro to coinbase
//
// {
// "id": "8d6dd0b9-3416-568a-889d-8f112fae9e81",
// "type": "pro_withdrawal",
// "status": "completed",
// "amount": { amount: "0.40555386", currency: "BTC" },
// "native_amount": { amount: "1140.27", currency: "GBP" },
// "description": null,
// "created_at": "2019-03-04T19:41:58Z",
// "updated_at": "2019-03-04T19:41:58Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c6afbd34-4bd0-501e-8616-4862c193cd84/transactions/8d6dd0b9-3416-568a-889d-8f112fae9e81",
// "instant_exchange": false,
// "application": {
// "id": "5756ab6e-836b-553b-8950-5e389451225d",
// "resource": "application",
// "resource_path": "/v2/applications/5756ab6e-836b-553b-8950-5e389451225d"
// },
// "details": { title: 'Transferred Bitcoin', subtitle: "From Coinbase Pro" }
// }
//
// sell trade
//
// {
// "id": "a9409207-df64-585b-97ab-a50780d2149e",
// "type": "sell",
// "status": "completed",
// "amount": { amount: "-9.09922880", currency: "BTC" },
// "native_amount": { amount: "-7285.73", currency: "GBP" },
// "description": null,
// "created_at": "2017-03-27T15:38:34Z",
// "updated_at": "2017-03-27T15:38:34Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/c6afbd34-4bd0-501e-8616-4862c193cd84/transactions/a9409207-df64-585b-97ab-a50780d2149e",
// "instant_exchange": false,
// "sell": {
// "id": "e3550b4d-8ae6-5de3-95fe-1fb01ba83051",
// "resource": "sell",
// "resource_path": "/v2/accounts/c6afbd34-4bd0-501e-8616-4862c193cd84/sells/e3550b4d-8ae6-5de3-95fe-1fb01ba83051"
// },
// "details": {
// "title": "Sold Bitcoin",
// "subtitle": "Using EUR Wallet",
// "payment_method_name": "EUR Wallet"
// }
// }
//
// buy trade
//
// {
// "id": "63eeed67-9396-5912-86e9-73c4f10fe147",
// "type": "buy",
// "status": "completed",
// "amount": { amount: "2.39605772", currency: "ETH" },
// "native_amount": { amount: "98.31", currency: "GBP" },
// "description": null,
// "created_at": "2017-03-27T09:07:56Z",
// "updated_at": "2017-03-27T09:07:57Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/8902f85d-4a69-5d74-82fe-8e390201bda7/transactions/63eeed67-9396-5912-86e9-73c4f10fe147",
// "instant_exchange": false,
// "buy": {
// "id": "20b25b36-76c6-5353-aa57-b06a29a39d82",
// "resource": "buy",
// "resource_path": "/v2/accounts/8902f85d-4a69-5d74-82fe-8e390201bda7/buys/20b25b36-76c6-5353-aa57-b06a29a39d82"
// },
// "details": {
// "title": "Bought Ethereum",
// "subtitle": "Using EUR Wallet",
// "payment_method_name": "EUR Wallet"
// }
// }
//
// fiat deposit transaction
//
// {
// "id": "04ed4113-3732-5b0c-af86-b1d2146977d0",
// "type": "fiat_deposit",
// "status": "completed",
// "amount": { amount: "114.02", currency: "EUR" },
// "native_amount": { amount: "97.23", currency: "GBP" },
// "description": null,
// "created_at": "2017-02-09T07:01:21Z",
// "updated_at": "2017-02-09T07:01:22Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/transactions/04ed4113-3732-5b0c-af86-b1d2146977d0",
// "instant_exchange": false,
// "fiat_deposit": {
// "id": "f34c19f3-b730-5e3d-9f72-96520448677a",
// "resource": "fiat_deposit",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/deposits/f34c19f3-b730-5e3d-9f72-96520448677a"
// },
// "details": {
// "title": "Deposited funds",
// "subtitle": "From SEPA Transfer (GB47 BARC 20..., reference CBADVI)",
// "payment_method_name": "SEPA Transfer (GB47 BARC 20..., reference CBADVI)"
// }
// }
//
// fiat withdrawal transaction
//
// {
// "id": "957d98e2-f80e-5e2f-a28e-02945aa93079",
// "type": "fiat_withdrawal",
// "status": "completed",
// "amount": { amount: "-11000.00", currency: "EUR" },
// "native_amount": { amount: "-9698.22", currency: "GBP" },
// "description": null,
// "created_at": "2017-12-06T13:19:19Z",
// "updated_at": "2017-12-06T13:19:19Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/transactions/957d98e2-f80e-5e2f-a28e-02945aa93079",
// "instant_exchange": false,
// "fiat_withdrawal": {
// "id": "f4bf1fd9-ab3b-5de7-906d-ed3e23f7a4e7",
// "resource": "fiat_withdrawal",
// "resource_path": "/v2/accounts/91cd2d36-3a91-55b6-a5d4-0124cf105483/withdrawals/f4bf1fd9-ab3b-5de7-906d-ed3e23f7a4e7"
// },
// "details": {
// "title": "Withdrew funds",
// "subtitle": "To HSBC BANK PLC (GB74 MIDL...)",
// "payment_method_name": "HSBC BANK PLC (GB74 MIDL...)"
// }
// }
//
let mut amountInfo: Value = self.safe_dict_k(item.clone(), "amount", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut amount: Value = self.safe_string_k(amountInfo.clone(), "amount", &[]);
let mut direction: Value = Value::Null;
if is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))) {
direction = Value::Str("out".into());
amount = crate::precise::Precise::stringNeg(&amount);
} else {
direction = Value::Str("in".into());
}
let mut currencyId: Value = self.safe_string_k(amountInfo, "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
currency = self.safe_currency(currencyId, &[currency.clone()]);
//
// the address and txid do not belong to the unified ledger structure
//
// let address = undefined;
// if (item['to']) {
// address = this.safeString (item['to'], 'address');
// }
// let txid = undefined;
//
let mut fee: Value = Value::Null;
let mut networkInfo: Value = self.safe_dict_k(item.clone(), "network", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// txid = network['hash']; // txid does not belong to the unified ledger structure
let mut feeInfo: Value = self.safe_dict_k(networkInfo, "transaction_fee", &[]);
if (feeInfo != Value::Null) {
let mut feeCurrencyId: Value = self.safe_string_k(feeInfo.clone(), "currency", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId, &[currency.clone()]);
let mut feeAmount: Value = self.safe_number_k(feeInfo, "amount", &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeAmount);
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
let mut timestamp: Value = self.parse8601(self.safe_string_k(item.clone(), "created_at", &[]));
let mut id: Value = self.safe_string_k(item.clone(), "id", &[]);
let mut type_var: Value = self.parse_ledger_entry_type(self.safe_string_k(item.clone(), "type", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut status: Value = self.parse_ledger_entry_status(self.safe_string_k(item.clone(), "status", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut path: Value = self.safe_string_k(item.clone(), "resource_path", &[]);
let mut accountId: Value = Value::Null;
if (path != Value::Null) {
let mut parts: Value = split(&path, &Value::Str("/".into()));
let mut numParts: f64 = ((parts.len() as i64) as f64);
if numParts > ((3i64) as f64) {
accountId = parts.as_array().and_then(|__arr| __arr.get(3)).cloned().unwrap_or(Value::Null);
}
}
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item);
m.insert("id".to_string(), id);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("direction".to_string(), direction);
m.insert("account".to_string(), accountId);
m.insert("referenceId".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), fee);
m
}), &[currency]);
Value::Null
}
pub async fn find_account_id(&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;
}
self.load_accounts(&[Value::Bool(false), params]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_530: bool = true;
while { if !__for_first_530 { 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_530 = false; i.as_f64().unwrap_or(f64::NAN) < ((self.accounts.len() as i64) as f64) } {
let mut account: Value = self.accounts.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if (account.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null).as_str() == code.as_str()) {
return account.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
}
}
}
return Value::Null;
Value::Null
}
pub fn prepare_account_request(&self, 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
}));
let mut accountId: Value = self.safe_string2(params, Value::Str("account_id".into()), Value::Str("accountId".into()), &[]);
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" prepareAccountRequest() method requires an account_id (or accountId) parameter".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId);
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit); }
}
return request;
Value::Null
}
pub async fn prepare_account_request_with_currency_code(&mut self, optional_args: &[Value]) -> Value {
let mut code = 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
}));
let mut accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".into()), Value::Str("accountId".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
if (accountId == Value::Null) {
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" prepareAccountRequestWithCurrencyCode() method requires an account_id (or accountId) parameter OR a currency code argument".into()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" prepareAccountRequestWithCurrencyCode() could not find account id for ".into())).into()), code).into()), Value::Str(". You might try to generate the deposit address in the website for that coin first.".into()))));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId);
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit); }
}
return Value::from(vec![request, params]);
Value::Null
}
/*
* @method
* @name coinbase#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/create-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @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_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: 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::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketBuyOrderWithCost() supports spot orders only".into()))));
}
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("createMarketBuyOrderRequiresPrice".into(), Value::Bool(false)); }
return self.create_order(symbol, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#createOrder
* @description create a trade order
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/create-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 you want to trade in units of the base currency, quote currency for 'market' 'buy' orders
* @param {float} [price] the price to fulfill the order, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.stopPrice] price to trigger stop orders
* @param {float} [params.triggerPrice] price to trigger stop orders
* @param {float} [params.stopLossPrice] price to trigger stop-loss orders
* @param {float} [params.takeProfitPrice] price to trigger take-profit orders
* @param {bool} [params.postOnly] true or false
* @param {string} [params.timeInForce] 'GTC', 'IOC', 'GTD' or 'PO', 'FOK'
* @param {string} [params.stop_direction] 'UNKNOWN_STOP_DIRECTION', 'STOP_DIRECTION_STOP_UP', 'STOP_DIRECTION_STOP_DOWN' the direction the stopPrice is triggered from
* @param {string} [params.end_time] '2023-05-25T17:01:05.092Z' for 'GTD' orders
* @param {float} [params.cost] *spot market buy only* the quote quantity that can be used as an alternative for the amount
* @param {boolean} [params.preview] default to false, wether to use the test/preview endpoint or not
* @param {float} [params.leverage] default to 1, the leverage to use for the order
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @param {string} [params.retail_portfolio_id] portfolio uid
* @param {boolean} [params.is_max] Used in conjunction with tradable_balance to indicate the user wants to use their entire tradable balance
* @param {string} [params.tradable_balance] amount of tradable balance
* @param {float} [params.reduceOnly] set to true for closing a position or use closePosition
* @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 id: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("ccxt".into())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("client_order_id".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", id, Value::Str("-".into())).into()), self.uuid(&[])).into()));
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), to_upper(&side));
m
});
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[]);
if (reduceOnly.as_bool() == Some(true)) {
params = self.omit(params.clone(), Value::Str("reduceOnly".into()), &[]);
add_element_to_object(&mut params, &Value::Str("amount".into()), amount.clone());
return self.close_position(symbol.clone(), &[side.clone(), params.clone()]).await;
}
let mut triggerPrice: Value = self.safe_number_n(params.clone(), Value::from(vec![Value::Str("stopPrice".into()), Value::Str("stop_price".into()), Value::Str("triggerPrice".into())]), &[]);
let mut stopLossPrice: Value = self.safe_number_k(params.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Value = self.safe_number_k(params.clone(), "takeProfitPrice", &[]);
let mut isStop: bool = triggerPrice != Value::Null;
let mut isStopLoss: bool = stopLossPrice != Value::Null;
let mut isTakeProfit: bool = takeProfitPrice != Value::Null;
let mut timeInForce: Option<String> = self.safe_string_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut postOnly: Value = (if (timeInForce.as_deref() == Some("PO")) { Value::Bool(true) } else { self.safe_bool2(params.clone(), Value::Str("postOnly".into()), Value::Str("post_only".into()), &[Value::Bool(false)]) });
let mut endTime: Value = self.safe_string_k(params.clone(), "end_time", &[]);
let mut stopDirection: Value = self.safe_string_k(params.clone(), "stop_direction", &[]);
if (type_var.as_str() == Some("limit")) {
if isStop {
if (stopDirection == Value::Null) {
stopDirection = (if (side.as_str() == Some("buy")) { Value::Str("STOP_DIRECTION_STOP_DOWN".into()) } else { Value::Str("STOP_DIRECTION_STOP_UP".into()) });
}
if (timeInForce.as_deref() == Some("GTD")) || (endTime != Value::Null) {
if (endTime == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires an end_time parameter for a GTD order".into()))));
}
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stop_limit_stop_limit_gtd".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m.insert("stop_price".to_string(), self.price_to_precision(symbol.clone(), triggerPrice.clone()));
m.insert("stop_direction".to_string(), stopDirection.clone());
m.insert("end_time".to_string(), endTime.clone());
m
}));
m
}));
} else {
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stop_limit_stop_limit_gtc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m.insert("stop_price".to_string(), self.price_to_precision(symbol.clone(), triggerPrice));
m.insert("stop_direction".to_string(), stopDirection.clone());
m
}));
m
}));
}
} else if isStopLoss || isTakeProfit {
let mut tpslPrice: Value = Value::Null;
if isStopLoss {
if (stopDirection == Value::Null) {
stopDirection = (if (side.as_str() == Some("buy")) { Value::Str("STOP_DIRECTION_STOP_UP".into()) } else { Value::Str("STOP_DIRECTION_STOP_DOWN".into()) });
}
tpslPrice = self.price_to_precision(symbol.clone(), stopLossPrice);
} else {
if (stopDirection == Value::Null) {
stopDirection = (if (side.as_str() == Some("buy")) { Value::Str("STOP_DIRECTION_STOP_DOWN".into()) } else { Value::Str("STOP_DIRECTION_STOP_UP".into()) });
}
tpslPrice = self.price_to_precision(symbol.clone(), takeProfitPrice);
}
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stop_limit_stop_limit_gtc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m.insert("stop_price".to_string(), tpslPrice);
m.insert("stop_direction".to_string(), stopDirection);
m
}));
m
}));
} else {
if (timeInForce.as_deref() == Some("GTD")) || (endTime != Value::Null) {
if (endTime == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires an end_time parameter for a GTD order".into()))));
}
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit_limit_gtd".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m.insert("end_time".to_string(), endTime);
m.insert("post_only".to_string(), postOnly.clone());
m
}));
m
}));
} else if (timeInForce.as_deref() == Some("IOC")) {
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sor_limit_ioc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m
}));
m
}));
} else if (timeInForce.as_deref() == Some("FOK")) {
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit_limit_fok".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m
}));
m
}));
} else {
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit_limit_gtc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("limit_price".to_string(), self.price_to_precision(symbol.clone(), price.clone()));
m.insert("post_only".to_string(), postOnly);
m
}));
m
}));
}
}
} else {
if isStop || isStopLoss || isTakeProfit {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() only stop limit orders are supported".into()))));
}
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) && (side.as_str() == Some("buy")) {
let mut total: Value = Value::Null;
let mut createMarketBuyOrderRequiresPrice: Value = Value::Bool(true);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".into()), Value::Str("createMarketBuyOrderRequiresPrice".into()), &[Value::Bool(true)]); createMarketBuyOrderRequiresPrice = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
params = self.omit(params.clone(), Value::Str("cost".into()), &[]);
if (cost != Value::Null) {
total = self.cost_to_precision(symbol.clone(), cost);
} else if is_true(&createMarketBuyOrderRequiresPrice) {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend in the amount argument".into()))));
} else {
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price);
let mut costRequest: Value = crate::precise::Precise::stringMul(&amountString, &priceString);
total = self.cost_to_precision(symbol.clone(), costRequest);
}
} else {
total = self.cost_to_precision(symbol.clone(), amount.clone());
}
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_market_ioc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quote_size".to_string(), total);
m
}));
m
}));
} else {
add_element_to_object(&mut request, &Value::Str("order_configuration".into()), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market_market_ioc".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("base_size".to_string(), self.amount_to_precision(symbol, amount));
m
}));
m
}));
}
}
let mut marginMode: Option<String> = self.safe_string_k(params.clone(), "marginMode", &[]).as_str().map(str::to_owned);
if (marginMode.is_some()) {
if (marginMode.as_deref() == Some("isolated")) {
add_element_to_object(&mut request, &Value::Str("margin_type".into()), Value::Str("ISOLATED".into()));
} else if (marginMode.as_deref() == Some("cross")) {
add_element_to_object(&mut request, &Value::Str("margin_type".into()), Value::Str("CROSS".into()));
}
}
params = self.omit(params.clone(), Value::from(vec![Value::Str("timeInForce".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("stopPrice".into()), Value::Str("stop_price".into()), Value::Str("stopDirection".into()), Value::Str("stop_direction".into()), Value::Str("clientOrderId".into()), Value::Str("postOnly".into()), Value::Str("post_only".into()), Value::Str("end_time".into()), Value::Str("marginMode".into())]), &[]);
let mut preview: Value = self.safe_bool2(params.clone(), Value::Str("preview".into()), Value::Str("test".into()), &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if (preview.as_bool() == Some(true)) {
params = self.omit(params.clone(), Value::from(vec![Value::Str("preview".into()), Value::Str("test".into())]), &[]);
request = self.omit(request.clone(), Value::Str("client_order_id".into()), &[]);
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_post_brokerage_orders_preview(&[__ws_arg_21]).await;
} else {
let __ws_arg_22 = self.extend(request, &[params]);
response = self.v3_private_post_brokerage_orders(&[__ws_arg_22]).await;
}
//
// successful order
//
// {
// "success": true,
// "failure_reason": "UNKNOWN_FAILURE_REASON",
// "order_id": "52cfe5e2-0b29-4c19-a245-a6a773de5030",
// "success_response": {
// "order_id": "52cfe5e2-0b29-4c19-a245-a6a773de5030",
// "product_id": "LTC-BTC",
// "side": "SELL",
// "client_order_id": "4d760580-6fca-4094-a70b-ebcca8626288"
// },
// "order_configuration": null
// }
//
// failed order
//
// {
// "success": false,
// "failure_reason": "UNKNOWN_FAILURE_REASON",
// "order_id": "",
// "error_response": {
// "error": "UNSUPPORTED_ORDER_CONFIGURATION",
// "message": "source is not enabled for trading",
// "error_details": "",
// "new_order_failure_reason": "UNSUPPORTED_ORDER_CONFIGURATION"
// },
// "order_configuration": {
// "limit_limit_gtc": {
// "base_size": "100",
// "limit_price": "40000",
// "post_only": false
// }
// }
// }
//
let mut success: Value = self.safe_bool_k(response.clone(), "success", &[]);
if (success.as_bool() != Some(true)) {
let mut errorResponse: Value = self.safe_dict_k(response.clone(), "error_response", &[]);
let mut errorTitle: Value = self.safe_string_k(errorResponse.clone(), "error", &[]);
let mut errorMessage: Value = self.safe_string_k(errorResponse.clone(), "message", &[]);
if (errorResponse != Value::Null) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorTitle.clone(), errorMessage.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorTitle, errorMessage.clone());
panic!("{}", crate::exchange_errors::exchange_error(errorMessage));
}
}
let mut data: Value = self.safe_dict_k(response, "success_response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data, &[market]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrder
//
// {
// "order_id": "52cfe5e2-0b29-4c19-a245-a6a773de5030",
// "product_id": "LTC-BTC",
// "side": "SELL",
// "client_order_id": "4d760580-6fca-4094-a70b-ebcca8626288"
// }
//
// cancelOrder, cancelOrders
//
// {
// "success": true,
// "failure_reason": "UNKNOWN_CANCEL_FAILURE_REASON",
// "order_id": "bb8851a3-4fda-4a2c-aa06-9048db0e0f0d"
// }
//
// fetchOrder, fetchOrders, fetchOpenOrders, fetchClosedOrders, fetchCanceledOrders
//
// {
// "order_id": "9bc1eb3b-5b46-4b71-9628-ae2ed0cca75b",
// "product_id": "LTC-BTC",
// "user_id": "1111111-1111-1111-1111-111111111111",
// "order_configuration": {
// "limit_limit_gtc": {
// "base_size": "0.2",
// "limit_price": "0.006",
// "post_only": false
// },
// "stop_limit_stop_limit_gtc": {
// "base_size": "48.54",
// "limit_price": "6.998",
// "stop_price": "7.0687",
// "stop_direction": "STOP_DIRECTION_STOP_DOWN"
// }
// },
// "side": "SELL",
// "client_order_id": "e5fe8482-05bb-428f-ad4d-dbc8ce39239c",
// "status": "OPEN",
// "time_in_force": "GOOD_UNTIL_CANCELLED",
// "created_time": "2023-01-16T23:37:23.947030Z",
// "completion_percentage": "0",
// "filled_size": "0",
// "average_filled_price": "0",
// "fee": "",
// "number_of_fills": "0",
// "filled_value": "0",
// "pending_cancel": false,
// "size_in_quote": false,
// "total_fees": "0",
// "size_inclusive_of_fees": false,
// "total_value_after_fees": "0",
// "trigger_status": "INVALID_ORDER_TYPE",
// "order_type": "LIMIT",
// "reject_reason": "REJECT_REASON_UNSPECIFIED",
// "settled": false,
// "product_type": "SPOT",
// "reject_message": "",
// "cancel_message": ""
// }
//
let mut marketId: Value = self.safe_string_k(order.clone(), "product_id", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone(), Value::Str("-".into())]);
if (symbol != Value::Null) {
market = self.safe_market(&[symbol.clone(), market.clone()]);
}
let mut orderConfiguration: Value = self.safe_dict_k(order.clone(), "order_configuration", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut limitGTC: Value = self.safe_dict_k(orderConfiguration.clone(), "limit_limit_gtc", &[]);
let mut limitGTD: Value = self.safe_dict_k(orderConfiguration.clone(), "limit_limit_gtd", &[]);
let mut limitIOC: Value = self.safe_dict_k(orderConfiguration.clone(), "sor_limit_ioc", &[]);
let mut stopLimitGTC: Value = self.safe_dict_k(orderConfiguration.clone(), "stop_limit_stop_limit_gtc", &[]);
let mut stopLimitGTD: Value = self.safe_dict_k(orderConfiguration.clone(), "stop_limit_stop_limit_gtd", &[]);
let mut marketIOC: Value = self.safe_dict_k(orderConfiguration, "market_market_ioc", &[]);
let mut isLimit: bool = (limitGTC != Value::Null) || (limitGTD != Value::Null) || (limitIOC != Value::Null);
let mut isStop: bool = (stopLimitGTC != Value::Null) || (stopLimitGTD != Value::Null);
let mut price: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut postOnly: Value = Value::Null;
let mut triggerPrice: Value = Value::Null;
if isLimit {
let mut target: Value = Value::Null;
if (limitGTC != Value::Null) {
target = limitGTC;
} else if (limitGTD != Value::Null) {
target = limitGTD;
} else {
target = limitIOC;
}
price = self.safe_string_k(target.clone(), "limit_price", &[]);
amount = self.safe_string_k(target.clone(), "base_size", &[]);
postOnly = self.safe_bool_k(target, "post_only", &[]);
} else if isStop {
let mut stopTarget: Value = (if (stopLimitGTC != Value::Null) { stopLimitGTC } else { stopLimitGTD });
price = self.safe_string_k(stopTarget.clone(), "limit_price", &[]);
amount = self.safe_string_k(stopTarget.clone(), "base_size", &[]);
postOnly = self.safe_bool_k(stopTarget.clone(), "post_only", &[]);
triggerPrice = self.safe_string_k(stopTarget, "stop_price", &[]);
} else {
amount = self.safe_string_k(marketIOC, "base_size", &[]);
}
let mut datetime: Value = self.safe_string_k(order.clone(), "created_time", &[]);
let mut totalFees: Option<String> = self.safe_string_k(order.clone(), "total_fees", &[]).as_str().map(str::to_owned);
let mut currencyFee: Value = Value::Null;
if (totalFees.is_some()) && (market != Value::Null) {
currencyFee = market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null);
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "order_id", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "client_order_id", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), self.parse_order_type(self.safe_string_k(order.clone(), "order_type", &[])));
m.insert("timeInForce".to_string(), self.parse_time_in_force(self.safe_string_k(order.clone(), "time_in_force", &[])));
m.insert("postOnly".to_string(), postOnly);
m.insert("side".to_string(), self.safe_string_lower_k(order.clone(), "side", &[]));
m.insert("price".to_string(), price);
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "filled_size", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string_k(order.clone(), "average_filled_price", &[]));
m.insert("status".to_string(), self.parse_order_status(self.safe_string_k(order.clone(), "status", &[])));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_string_k(order, "total_fees", &[]));
m.insert("currency".to_string(), currencyFee);
m
}));
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("OPEN".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("FAILED".to_string(), Value::Str("canceled".into()));
m.insert("UNKNOWN_ORDER_STATUS".to_string(), Value::Null);
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut type_var: Value) -> Value {
if (type_var.as_str() == Some("UNKNOWN_ORDER_TYPE")) {
return Value::Null;
}
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("MARKET".to_string(), Value::Str("market".into()));
m.insert("LIMIT".to_string(), Value::Str("limit".into()));
m.insert("STOP".to_string(), Value::Str("limit".into()));
m.insert("STOP_LIMIT".to_string(), Value::Str("limit".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GOOD_UNTIL_CANCELLED".to_string(), Value::Str("GTC".into()));
m.insert("GOOD_UNTIL_DATE_TIME".to_string(), Value::Str("GTD".into()));
m.insert("IMMEDIATE_OR_CANCEL".to_string(), Value::Str("IOC".into()));
m.insert("FILL_OR_KILL".to_string(), Value::Str("FOK".into()));
m.insert("UNKNOWN_TIME_IN_FORCE".to_string(), Value::Null);
m
});
return self.safe_string(timeInForces, timeInForce.clone(), &[timeInForce.clone()]);
Value::Null
}
/*
* @method
* @name coinbase#cancelOrder
* @description cancels an open order
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/cancel-orders
* @param {string} id order id
* @param {string} symbol not used by cancelOrder()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
return self.safe_dict(orders, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
/*
* @method
* @name coinbase#cancelOrders
* @description cancel multiple orders
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/cancel-orders
* @param {string[]} ids order ids
* @param {string} symbol not used by cancelOrders()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_ids".to_string(), ids);
m
});
let __ws_arg_23 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_post_brokerage_orders_batch_cancel(&[__ws_arg_23]).await;
//
// {
// "results": [
// {
// "success": true,
// "failure_reason": "UNKNOWN_CANCEL_FAILURE_REASON",
// "order_id": "bb8851a3-4fda-4a2c-aa06-9048db0e0f0d"
// }
// ]
// }
//
let mut orders: Value = self.safe_list_k(response, "results", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_531: bool = true;
while { if !__for_first_531 { 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_531 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut success: Value = self.safe_bool(orders.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("success".into()), &[]);
if (success.as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() has failed, check your arguments and parameters".into()))));
}
}
}
return self.parse_orders(orders, &[market]);
Value::Null
}
/*
* @method
* @name coinbase#editOrder
* @description edit a trade order
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/edit-order
* @param {string} id cancel order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.preview] default to false, wether to use the test/preview endpoint or not
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (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("order_id".to_string(), id);
m
});
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol, price)); }
}
let mut preview: Value = self.safe_bool2(params.clone(), Value::Str("preview".into()), Value::Str("test".into()), &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if (preview.as_bool() == Some(true)) {
params = self.omit(params.clone(), Value::from(vec![Value::Str("preview".into()), Value::Str("test".into())]), &[]);
let __ws_arg_24 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_post_brokerage_orders_edit_preview(&[__ws_arg_24]).await;
} else {
let __ws_arg_25 = self.extend(request, &[params]);
response = self.v3_private_post_brokerage_orders_edit(&[__ws_arg_25]).await;
}
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name coinbase#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/get-order
* @param {string} id the order id
* @param {string} symbol unified market symbol that the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_26 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_orders_historical_order_id(&[__ws_arg_26]).await;
//
// {
// "order": {
// "order_id": "9bc1eb3b-5b46-4b71-9628-ae2ed0cca75b",
// "product_id": "LTC-BTC",
// "user_id": "1111111-1111-1111-1111-111111111111",
// "order_configuration": {
// "limit_limit_gtc": {
// "base_size": "0.2",
// "limit_price": "0.006",
// "post_only": false
// }
// },
// "side": "SELL",
// "client_order_id": "e5fe8482-05bb-428f-ad4d-dbc8ce39239c",
// "status": "OPEN",
// "time_in_force": "GOOD_UNTIL_CANCELLED",
// "created_time": "2023-01-16T23:37:23.947030Z",
// "completion_percentage": "0",
// "filled_size": "0",
// "average_filled_price": "0",
// "fee": "",
// "number_of_fills": "0",
// "filled_value": "0",
// "pending_cancel": false,
// "size_in_quote": false,
// "total_fees": "0",
// "size_inclusive_of_fees": false,
// "total_value_after_fees": "0",
// "trigger_status": "INVALID_ORDER_TYPE",
// "order_type": "LIMIT",
// "reject_reason": "REJECT_REASON_UNSPECIFIED",
// "settled": false,
// "product_type": "SPOT",
// "reject_message": "",
// "cancel_message": ""
// }
// }
//
let mut order: Value = self.safe_dict_k(response, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name coinbase#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/list-orders
* @param {string} symbol unified market symbol that the orders were made in
* @param {int} [since] the earliest time in ms to fetch orders
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch trades for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Int(100));
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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrders".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(1000)]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (market != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_id".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()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_date".into(), self.iso8601(since.clone())); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_date".into(), self.iso8601(until)); }
}
let __ws_arg_27 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_orders_historical_batch(&[__ws_arg_27]).await;
//
// {
// "orders": [
// {
// "order_id": "813a53c5-3e39-47bb-863d-2faf685d22d8",
// "product_id": "BTC-USDT",
// "user_id": "1111111-1111-1111-1111-111111111111",
// "order_configuration": {
// "market_market_ioc": {
// "quote_size": "6.36"
// }
// },
// "side": "BUY",
// "client_order_id": "18eb9947-db49-4874-8e7b-39b8fe5f4317",
// "status": "FILLED",
// "time_in_force": "IMMEDIATE_OR_CANCEL",
// "created_time": "2023-01-18T01:37:37.975552Z",
// "completion_percentage": "100",
// "filled_size": "0.000297920684505",
// "average_filled_price": "21220.6399999973697697",
// "fee": "",
// "number_of_fills": "2",
// "filled_value": "6.3220675944333996",
// "pending_cancel": false,
// "size_in_quote": true,
// "total_fees": "0.0379324055666004",
// "size_inclusive_of_fees": true,
// "total_value_after_fees": "6.36",
// "trigger_status": "INVALID_ORDER_TYPE",
// "order_type": "MARKET",
// "reject_reason": "REJECT_REASON_UNSPECIFIED",
// "settled": true,
// "product_type": "SPOT",
// "reject_message": "",
// "cancel_message": "Internal error"
// },
// ],
// "sequence": "0",
// "has_next": false,
// "cursor": ""
// }
//
let mut orders: Value = self.safe_list_k(response.clone(), "orders", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(orders.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
if (cursor != Value::Null) && (cursor.as_str() != Some("")) {
if let Value::Dict(__d) = &mut first { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor); }
add_element_to_object(&mut orders, &Value::Int(0), first);
}
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
pub async fn fetch_orders_by_status(&mut self, mut status: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_status".to_string(), status);
m
});
if (market != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit == Value::Null) {
limit = Value::Int(100);
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_date".into(), self.iso8601(since.clone())); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_date".into(), self.iso8601(until)); }
}
let __ws_arg_28 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_orders_historical_batch(&[__ws_arg_28]).await;
//
// {
// "orders": [
// {
// "order_id": "813a53c5-3e39-47bb-863d-2faf685d22d8",
// "product_id": "BTC-USDT",
// "user_id": "1111111-1111-1111-1111-111111111111",
// "order_configuration": {
// "market_market_ioc": {
// "quote_size": "6.36"
// }
// },
// "side": "BUY",
// "client_order_id": "18eb9947-db49-4874-8e7b-39b8fe5f4314",
// "status": "FILLED",
// "time_in_force": "IMMEDIATE_OR_CANCEL",
// "created_time": "2023-01-18T01:37:37.975552Z",
// "completion_percentage": "100",
// "filled_size": "0.000297920684505",
// "average_filled_price": "21220.6399999973697697",
// "fee": "",
// "number_of_fills": "2",
// "filled_value": "6.3220675944333996",
// "pending_cancel": false,
// "size_in_quote": true,
// "total_fees": "0.0379324055666004",
// "size_inclusive_of_fees": true,
// "total_value_after_fees": "6.36",
// "trigger_status": "INVALID_ORDER_TYPE",
// "order_type": "MARKET",
// "reject_reason": "REJECT_REASON_UNSPECIFIED",
// "settled": true,
// "product_type": "SPOT",
// "reject_message": "",
// "cancel_message": "Internal error"
// },
// ],
// "sequence": "0",
// "has_next": false,
// "cursor": ""
// }
//
let mut orders: Value = self.safe_list_k(response.clone(), "orders", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(orders.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
if (cursor != Value::Null) && (cursor.as_str() != Some("")) {
if let Value::Dict(__d) = &mut first { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor); }
add_element_to_object(&mut orders, &Value::Int(0), first);
}
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name coinbase#fetchOpenOrders
* @description fetches information on all currently open orders
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/list-orders
* @param {string} symbol unified market symbol of the orders
* @param {int} [since] timestamp in ms of the earliest order, default is undefined
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {int} [params.until] the latest time in ms to fetch trades for
* @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 paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchOpenOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(100)]).await;
}
return self.fetch_orders_by_status(Value::Str("OPEN".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/list-orders
* @param {string} symbol unified market symbol of the orders
* @param {int} [since] timestamp in ms of the earliest order, default is undefined
* @param {int} [limit] the maximum number of closed order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {int} [params.until] the latest time in ms to fetch trades for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchClosedOrders".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchClosedOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(1000)]).await;
}
return self.fetch_orders_by_status(Value::Str("FILLED".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/list-orders
* @param {string} symbol unified market symbol of the orders
* @param {int} [since] timestamp in ms of the earliest order, default is undefined
* @param {int} [limit] the maximum number of canceled order structures to retrieve
* @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 fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_orders_by_status(Value::Str("CANCELLED".into()), &[symbol, since, limit, params]).await;
Value::Null
}
/*
* @method
* @name coinbase#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-product-candles
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/get-public-product-candles
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch, not used by coinbase
* @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 {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {boolean} [params.usePrivate] default false, when true will use the private endpoint to fetch the candles
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut maxLimit: Value = Value::Int(300);
limit = (if (limit == Value::Null) { maxLimit.clone() } else { crate::runtime::Math::min(&limit, &maxLimit) });
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), params.clone(), (match (&(maxLimit), &(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 })]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("granularity".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut until: Value = self.safe_integer2(params.clone(), Value::Str("until".into()), Value::Str("end".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut requestedDuration: Value = (match (&(limit), &(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 });
let mut sinceString: Value = Value::Null;
if (since != Value::Null) {
sinceString = self.number_to_string(self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })));
} else {
let mut now: Value = to_string_val(&self.seconds());
sinceString = crate::precise::Precise::stringSub(&now, &to_string_val(&requestedDuration));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), sinceString.clone()); }
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), self.number_to_string(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 {
// 300 candles max
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), crate::precise::Precise::stringAdd(&sinceString, &to_string_val(&requestedDuration))); }
}
let mut response: Value = Value::Null;
let mut usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&usePrivate) {
let __ws_arg_29 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_products_product_id_candles(&[__ws_arg_29]).await;
} else {
let __ws_arg_30 = self.extend(request, &[params]);
response = self.v3_public_get_brokerage_market_products_product_id_candles(&[__ws_arg_30]).await;
}
//
// {
// "candles": [
// {
// "start": "1673391780",
// "low": "17414.36",
// "high": "17417.99",
// "open": "17417.74",
// "close": "17417.38",
// "volume": "1.87780853"
// },
// ]
// }
//
let mut candles: Value = self.safe_list_k(response, "candles", &[Value::from(vec![])]);
return self.parse_ohlc_vs(candles, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_timestamp_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 coinbase#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-market-trades
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/get-public-market-trades
* @param {string} symbol unified market symbol of the trades
* @param {int} [since] not used by coinbase fetchTrades
* @param {int} [limit] the maximum number of trade structures to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.usePrivate] default false, when true will use the private endpoint to fetch the trades
* @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("product_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), self.number_to_string(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 })))); }
}
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))); }
}
let mut until: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".into()), Value::Str("until".into()), &[]); until = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), self.number_to_string(self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })))); }
} else if (since != Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() requires a `until` parameter when you use `since` argument".into()))));
}
let mut response: Value = Value::Null;
let mut usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&usePrivate) {
let __ws_arg_31 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_products_product_id_ticker(&[__ws_arg_31]).await;
} else {
let __ws_arg_32 = self.extend(request, &[params]);
response = self.v3_public_get_brokerage_market_products_product_id_ticker(&[__ws_arg_32]).await;
}
//
// {
// "trades": [
// {
// "trade_id": "10092327",
// "product_id": "BTC-USDT",
// "price": "17488.12",
// "size": "0.0000623",
// "time": "2023-01-11T00:52:37.557001Z",
// "side": "BUY",
// "bid": "",
// "ask": ""
// },
// ]
// }
//
let mut trades: Value = self.safe_list_k(response, "trades", &[Value::from(vec![])]);
return self.parse_trades(trades, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name coinbase#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/list-fills
* @param {string} symbol unified market symbol of the trades
* @param {int} [since] timestamp in ms of the earliest order, default is undefined
* @param {int} [limit] the maximum number of trade structures to fetch
* @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 {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(250)]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (market != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_id".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()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start_sequence_timestamp".into(), self.iso8601(since.clone())); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end_sequence_timestamp".into(), self.iso8601(until)); }
}
let __ws_arg_33 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_orders_historical_fills(&[__ws_arg_33]).await;
//
// {
// "fills": [
// {
// "entry_id": "b88b82cc89e326a2778874795102cbafd08dd979a2a7a3c69603fc4c23c2e010",
// "trade_id": "cdc39e45-bbd3-44ec-bf02-61742dfb16a1",
// "order_id": "813a53c5-3e39-47bb-863d-2faf685d22d8",
// "trade_time": "2023-01-18T01:37:38.091377090Z",
// "trade_type": "FILL",
// "price": "21220.64",
// "size": "0.0046830664333996",
// "commission": "0.0000280983986004",
// "product_id": "BTC-USDT",
// "sequence_timestamp": "2023-01-18T01:37:38.092520Z",
// "liquidity_indicator": "UNKNOWN_LIQUIDITY_INDICATOR",
// "size_in_quote": true,
// "user_id": "1111111-1111-1111-1111-111111111111",
// "side": "BUY"
// },
// ],
// "cursor": ""
// }
//
let mut trades: Value = self.safe_list_k(response.clone(), "fills", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(trades.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cursor: Value = self.safe_string_k(response, "cursor", &[]);
if (cursor != Value::Null) && (cursor.as_str() != Some("")) {
if let Value::Dict(__d) = &mut first { std::sync::Arc::make_mut(__d).insert("cursor".into(), cursor); }
add_element_to_object(&mut trades, &Value::Int(0), first);
}
return self.parse_trades(trades, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name coinbase#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-product-book
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/public/get-public-product-book
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.usePrivate] default false, when true will use the private endpoint to fetch the order book
* @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("product_id".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(), limit); }
}
let mut response: Value = Value::Null;
let mut usePrivate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrderBook".into()), Value::Str("usePrivate".into()), &[Value::Bool(false)]); usePrivate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&usePrivate) {
let __ws_arg_34 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_product_book(&[__ws_arg_34]).await;
} else {
let __ws_arg_35 = self.extend(request, &[params]);
response = self.v3_public_get_brokerage_market_product_book(&[__ws_arg_35]).await;
}
//
// {
// "pricebook": {
// "product_id": "BTC-USDT",
// "bids": [
// {
// "price": "30757.85",
// "size": "0.115"
// },
// ],
// "asks": [
// {
// "price": "30759.07",
// "size": "0.04877659"
// },
// ],
// "time": "2023-06-30T04:02:40.533606Z"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "pricebook", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut time: Value = self.safe_string_k(data.clone(), "time", &[]);
let mut timestamp: Value = self.parse8601(time);
return self.parse_order_book(data, symbol, &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
Value::Null
}
/*
* @method
* @name coinbase#fetchBidsAsks
* @description fetches the bid and ask price and volume for multiple markets
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/products/get-best-bid-ask
* @param {string[]} [symbols] unified symbols of the markets to fetch the bids and asks for, all markets 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_bids_asks(&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;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbols != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("product_ids".into(), self.market_ids(&[symbols.clone()])); }
}
let __ws_arg_36 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_best_bid_ask(&[__ws_arg_36]).await;
//
// {
// "pricebooks": [
// {
// "product_id": "TRAC-EUR",
// "bids": [
// {
// "price": "0.2384",
// "size": "386.1"
// }
// ],
// "asks": [
// {
// "price": "0.2406",
// "size": "672"
// }
// ],
// "time": "2023-06-30T07:15:24.656044Z"
// },
// ]
// }
//
let mut tickers: Value = self.safe_list_k(response, "pricebooks", &[Value::from(vec![])]);
return self.parse_tickers(tickers, &[symbols]);
Value::Null
}
/*
* @method
* @name coinbase#withdraw
* @description make a withdrawal
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/send-crypto
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} [tag] an optional tag for the withdrawal
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] the cryptocurrency network to use for the withdrawal using the lowercase name like bitcoin, ethereum, solana, etc.
* @param {object} [params.travel_rule_data] some regions require travel rule information for crypto withdrawals, see the exchange docs for details https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/travel-rule
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
{ let __destr_tmp = self.handle_withdraw_tag_and_params(tag.clone(), params.clone()); tag = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
self.check_address(&[address.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("send".into()));
m.insert("to".to_string(), address);
m.insert("amount".to_string(), self.number_to_string(amount));
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".into()), Value::Str("accountId".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
if (accountId == Value::Null) {
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" withdraw() requires an account_id (or accountId) parameter OR a currency code argument".into()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" withdraw() could not find account id for ".into())).into()), code)));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("account_id".into(), accountId.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("account_id".into(), accountId); }
}
if (tag != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("destination_tag".into(), tag); }
}
let __ws_arg_37 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_post_accounts_account_id_transactions(&[__ws_arg_37]).await;
//
// {
// "data": {
// "id": "a1794ecf-5693-55fa-70cf-ef731748ed82",
// "type": "send",
// "status": "pending",
// "amount": {
// "amount": "-14.008308",
// "currency": "USDC"
// },
// "native_amount": {
// "amount": "-18.74",
// "currency": "CAD"
// },
// "description": null,
// "created_at": "2024-01-12T01:27:31Z",
// "updated_at": "2024-01-12T01:27:31Z",
// "resource": "transaction",
// "resource_path": "/v2/accounts/a34bgfad-ed67-538b-bffc-730c98c10da0/transactions/a1794ecf-5693-55fa-70cf-ef731748ed82",
// "instant_exchange": false,
// "network": {
// "status": "pending",
// "status_description": "Pending (est. less than 10 minutes)",
// "transaction_fee": {
// "amount": "4.008308",
// "currency": "USDC"
// },
// "transaction_amount": {
// "amount": "10.000000",
// "currency": "USDC"
// },
// "confirmations": 0
// },
// "to": {
// "resource": "ethereum_address",
// "address": "0x9...",
// "currency": "USDC",
// "address_info": {
// "address": "0x9..."
// }
// },
// "idem": "748d8591-dg9a-7831-a45b-crd61dg78762",
// "details": {
// "title": "Sent USDC",
// "subtitle": "To USDC address on Ethereum network",
// "header": "Sent 14.008308 USDC ($18.74)",
// "health": "warning"
// },
// "hide_native_amount": false
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data, &[currency]);
Value::Null
}
/*
* @method
* @name coinbase#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/onchain-addresses
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_addresses_by_network(&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 currency: Value = self.currency(code);
let mut request: Value = Value::Null;
{ let __destr_tmp = self.prepare_account_request_with_currency_code(&[currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null), Value::Null, params.clone()]).await; request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_38 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_get_accounts_account_id_addresses(&[__ws_arg_38]).await;
//
// {
// pagination: {
// ending_before: null,
// starting_after: null,
// previous_ending_before: null,
// next_starting_after: null,
// limit: '25',
// order: 'desc',
// previous_uri: null,
// next_uri: null
// },
// data: [
// {
// id: '64ceb5f1-5fa2-5310-a4ff-9fd46271003d',
// address: '5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk',
// address_info: { address: '5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk' },
// name: null,
// created_at: '2023-05-29T21:12:12Z',
// updated_at: '2023-05-29T21:12:12Z',
// network: 'solana',
// uri_scheme: 'solana',
// resource: 'address',
// resource_path: '/v2/accounts/a7b3d387-bfb8-5ce7-b8da-1f507e81cf25/addresses/64ceb5f1-5fa2-5310-a4ff-9fd46271003d',
// warnings: [
// {
// type: 'correct_address_warning',
// title: 'This is an ERC20 USDC address.',
// details: 'Only send ERC20 USD Coin (USDC) to this address.',
// image_url: 'https://www.coinbase.com/assets/addresses/global-receive-warning-a3d91807e61c717e5a38d270965003dcc025ca8a3cea40ec3d7835b7c86087fa.png',
// options: [ { text: 'I understand', style: 'primary', id: 'dismiss' } ]
// }
// ],
// qr_code_image_url: 'https://static-assets.coinbase.com/p2p/l2/asset_network_combinations/v5/usdc-solana.png',
// address_label: 'USDC address (Solana)',
// default_receive: true,
// deposit_uri: 'solana:5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk?spl-token=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
// callback_url: null,
// share_address_copy: {
// line1: '5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk',
// line2: 'This address can only receive USDC-SPL from Solana network. Don’t send USDC from other networks, other SPL tokens or NFTs, or it may result in a loss of funds.'
// },
// receive_subtitle: 'ERC-20',
// inline_warning: {
// text: 'This address can only receive USDC-SPL from Solana network. Don’t send USDC from other networks, other SPL tokens or NFTs, or it may result in a loss of funds.',
// tooltip: {
// title: 'USDC (Solana)',
// subtitle: 'This address can only receive USDC-SPL from Solana network.'
// }
// }
// },
// ...
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut addressStructures: Value = self.parse_deposit_addresses(data, &[Value::Null, Value::Bool(false)]);
return self.index_by(addressStructures, Value::Str("network".into()));
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);
//
// {
// id: '64ceb5f1-5fa2-5310-a4ff-9fd46271003d',
// address: '5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk',
// address_info: {
// address: 'GCF74576I7AQ56SLMKBQAP255EGUOWCRVII3S44KEXVNJEOIFVBDMXVL',
// destination_tag: '3722061866'
// },
// name: null,
// created_at: '2023-05-29T21:12:12Z',
// updated_at: '2023-05-29T21:12:12Z',
// network: 'solana',
// uri_scheme: 'solana',
// resource: 'address',
// resource_path: '/v2/accounts/a7b3d387-bfb8-5ce7-b8da-1f507e81cf25/addresses/64ceb5f1-5fa2-5310-a4ff-9fd46271003d',
// warnings: [
// {
// type: 'correct_address_warning',
// title: 'This is an ERC20 USDC address.',
// details: 'Only send ERC20 USD Coin (USDC) to this address.',
// image_url: 'https://www.coinbase.com/assets/addresses/global-receive-warning-a3d91807e61c717e5a38d270965003dcc025ca8a3cea40ec3d7835b7c86087fa.png',
// options: [ { text: 'I understand', style: 'primary', id: 'dismiss' } ]
// }
// ],
// qr_code_image_url: 'https://static-assets.coinbase.com/p2p/l2/asset_network_combinations/v5/usdc-solana.png',
// address_label: 'USDC address (Solana)',
// default_receive: true,
// deposit_uri: 'solana:5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk?spl-token=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
// callback_url: null,
// share_address_copy: {
// line1: '5xjPKeAXpnhA2kHyinvdVeui6RXVdEa3B2J3SCAwiKnk',
// line2: 'This address can only receive USDC-SPL from Solana network. Don’t send USDC from other networks, other SPL tokens or NFTs, or it may result in a loss of funds.'
// },
// receive_subtitle: 'ERC-20',
// inline_warning: {
// text: 'This address can only receive USDC-SPL from Solana network. Don’t send USDC from other networks, other SPL tokens or NFTs, or it may result in a loss of funds.',
// tooltip: {
// title: 'USDC (Solana)',
// subtitle: 'This address can only receive USDC-SPL from Solana network.'
// }
// }
// }
//
// {
// "id":"3f2434234943-8c1c-50ef-a5a1-342213bbf45d",
// "address":"0x123123126F5921XXXXX",
// "currency":"USDC",
// "name":"",
// "network":"ethereum",
// "created_at":"2022-03-17T09:20:17.002Z",
// "updated_at":"2022-03-17T09:20:17.002Z",
// "resource":"addresses",
// "resource_path":"v2/accounts/b1091c6e-9ef2-5e4d-b352-665d0cf8f742/addresses/32fd0943-8c1c-50ef-a5a1-342213bbf45d",
// "destination_tag":""
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "address", &[]);
self.check_address(&[address.clone()]);
let mut networkId: Value = self.safe_string_k(depositAddress.clone(), "network", &[]);
let mut code: Value = self.safe_currency_code(Value::Null, &[currency.clone()]);
let mut addressLabel: Value = self.safe_string_k(depositAddress.clone(), "address_label", &[]);
let mut currencyId: Value = Value::Null;
if (addressLabel != Value::Null) {
let mut splitAddressLabel: Value = split(&addressLabel, &Value::Str(" ".into()));
currencyId = self.safe_string(splitAddressLabel, Value::Int(0), &[]);
} else {
currencyId = self.safe_string_k(depositAddress.clone(), "currency", &[]);
}
let mut addressInfo: Value = self.safe_dict_k(depositAddress.clone(), "address_info", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), self.safe_currency_code(currencyId, &[currency]));
m.insert("network".to_string(), self.network_id_to_code(&[networkId, code]));
m.insert("address".to_string(), address);
m.insert("tag".to_string(), self.safe_string_k(addressInfo, "destination_tag", &[]));
m
});
Value::Null
}
/*
* @method
* @name coinbase#deposit
* @description make a deposit
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat
* @param {string} code unified currency code
* @param {float} amount the amount to deposit
* @param {string} id the payment method id to be used for the deposit, can be retrieved from v2PrivateGetPaymentMethods
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountId] the id of the account to deposit into
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn deposit(&mut self, mut code: Value, mut amount: Value, mut id: 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 accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".into()), Value::Str("accountId".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
if (accountId == Value::Null) {
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" deposit() requires an account_id (or accountId) parameter OR a currency code argument".into()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" deposit() could not find account id for ".into())).into()), code)));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId);
m.insert("amount".to_string(), self.number_to_string(amount));
m.insert("currency".to_string(), to_upper(&code));
m.insert("payment_method".to_string(), id);
m.insert("commit".to_string(), Value::Bool(true));
m
});
let __ws_arg_39 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_post_accounts_account_id_deposits(&[__ws_arg_39]).await;
//
// {
// "data": {
// "id": "67e0eaec-07d7-54c4-a72c-2e92826897df",
// "status": "created",
// "payment_method": {
// "id": "83562370-3e5c-51db-87da-752af5ab9559",
// "resource": "payment_method",
// "resource_path": "/v2/payment-methods/83562370-3e5c-51db-87da-752af5ab9559"
// },
// "transaction": {
// "id": "441b9494-b3f0-5b98-b9b0-4d82c21c252a",
// "resource": "transaction",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/transactions/441b9494-b3f0-5b98-b9b0-4d82c21c252a"
// },
// "amount": {
// "amount": "10.00",
// "currency": "USD"
// },
// "subtotal": {
// "amount": "10.00",
// "currency": "USD"
// },
// "created_at": "2015-01-31T20:49:02Z",
// "updated_at": "2015-02-11T16:54:02-08:00",
// "resource": "deposit",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/deposits/67e0eaec-07d7-54c4-a72c-2e92826897df",
// "committed": true,
// "fee": {
// "amount": "0.00",
// "currency": "USD"
// },
// "payout_at": "2015-02-18T16:54:00-08:00"
// }
// }
//
// https://github.com/ccxt/ccxt/issues/25484
let mut data: Value = self.safe_dict2(response, Value::Str("data".into()), Value::Str("transfer".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data, &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchDeposit
* @description fetch information on a deposit, fiat only, for crypto transactions use fetchLedger
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/deposit-fiat
* @param {string} id deposit id
* @param {string} [code] unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountId] the id of the account that the funds were deposited into
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposit(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = 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 accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".into()), Value::Str("accountId".into()), &[]);
params = self.omit(params.clone(), Value::from(vec![Value::Str("account_id".into()), Value::Str("accountId".into())]), &[]);
if (accountId == Value::Null) {
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposit() requires an account_id (or accountId) parameter OR a currency code argument".into()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if (accountId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposit() could not find account id for ".into())).into()), code)));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId);
m.insert("deposit_id".to_string(), id);
m
});
let __ws_arg_40 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_get_accounts_account_id_deposits_deposit_id(&[__ws_arg_40]).await;
//
// {
// "data": {
// "id": "67e0eaec-07d7-54c4-a72c-2e92826897df",
// "status": "completed",
// "payment_method": {
// "id": "83562370-3e5c-51db-87da-752af5ab9559",
// "resource": "payment_method",
// "resource_path": "/v2/payment-methods/83562370-3e5c-51db-87da-752af5ab9559"
// },
// "transaction": {
// "id": "441b9494-b3f0-5b98-b9b0-4d82c21c252a",
// "resource": "transaction",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/transactions/441b9494-b3f0-5b98-b9b0-4d82c21c252a"
// },
// "amount": {
// "amount": "10.00",
// "currency": "USD"
// },
// "subtotal": {
// "amount": "10.00",
// "currency": "USD"
// },
// "created_at": "2015-01-31T20:49:02Z",
// "updated_at": "2015-02-11T16:54:02-08:00",
// "resource": "deposit",
// "resource_path": "/v2/accounts/2bbf394c-193b-5b2a-9155-3b4732659ede/deposits/67e0eaec-07d7-54c4-a72c-2e92826897df",
// "committed": true,
// "fee": {
// "amount": "0.00",
// "currency": "USD"
// },
// "payout_at": "2015-02-18T16:54:00-08:00"
// }
// }
//
// https://github.com/ccxt/ccxt/issues/25484
let mut data: Value = self.safe_dict2(response, Value::Str("data".into()), Value::Str("transfer".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data, &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchDepositMethodIds
* @description fetch the deposit id for a fiat currency associated with this account
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/payment-methods/list-payment-methods
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an array of [deposit id structures]{@link https://docs.ccxt.com/?id=deposit-id-structure}
*/
pub async fn fetch_deposit_method_ids(&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.v3_private_get_brokerage_payment_methods(&[params]).await;
//
// {
// "payment_methods": [
// {
// "id": "21b39a5d-f7b46876fb2e",
// "type": "COINBASE_FIAT_ACCOUNT",
// "name": "CAD Wallet",
// "currency": "CAD",
// "verified": true,
// "allow_buy": false,
// "allow_sell": true,
// "allow_deposit": false,
// "allow_withdraw": false,
// "created_at": "2023-06-29T19:58:46Z",
// "updated_at": "2023-10-30T20:25:01Z"
// }
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "payment_methods", &[Value::from(vec![])]);
return self.parse_deposit_method_ids(result, &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchDepositMethodId
* @description fetch the deposit id for a fiat currency associated with this account
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/payment-methods/get-payment-method
* @param {string} id the deposit payment method id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [deposit id structure]{@link https://docs.ccxt.com/?id=deposit-id-structure}
*/
pub async fn fetch_deposit_method_id(&mut self, mut id: 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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("payment_method_id".to_string(), id);
m
});
let __ws_arg_41 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_payment_methods_payment_method_id(&[__ws_arg_41]).await;
//
// {
// "payment_method": {
// "id": "21b39a5d-f7b46876fb2e",
// "type": "COINBASE_FIAT_ACCOUNT",
// "name": "CAD Wallet",
// "currency": "CAD",
// "verified": true,
// "allow_buy": false,
// "allow_sell": true,
// "allow_deposit": false,
// "allow_withdraw": false,
// "created_at": "2023-06-29T19:58:46Z",
// "updated_at": "2023-10-30T20:25:01Z"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "payment_method", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_deposit_method_id(result);
Value::Null
}
pub fn parse_deposit_method_ids(&self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_532: bool = true;
while { if !__for_first_532 { 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_532 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let __ws_arg_42 = self.parse_deposit_method_id(ids.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 id: Value = self.extend(__ws_arg_42, &[params.clone()]);
append_to_array(&mut result, id);
}
}
return result;
Value::Null
}
pub fn parse_deposit_method_id(&self, mut depositId: Value) -> Value {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositId.clone());
m.insert("id".to_string(), self.safe_string_k(depositId.clone(), "id", &[]));
m.insert("currency".to_string(), self.safe_string_k(depositId.clone(), "currency", &[]));
m.insert("verified".to_string(), self.safe_bool_k(depositId.clone(), "verified", &[]));
m.insert("tag".to_string(), self.safe_string_k(depositId, "name", &[]));
m
});
Value::Null
}
/*
* @method
* @name coinbase#fetchConvertQuote
* @description fetch a quote for converting from one currency to another
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/convert/create-convert-quote
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} [amount] how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {object} [params.trade_incentive_metadata] an object to fill in user incentive data
* @param {string} [params.trade_incentive_metadata.user_incentive_id] the id of the incentive
* @param {string} [params.trade_incentive_metadata.code_val] the code value of the incentive
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_quote(&mut self, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("from_account".to_string(), fromCode);
m.insert("to_account".to_string(), toCode);
m.insert("amount".to_string(), self.number_to_string(amount));
m
});
let __ws_arg_43 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_post_brokerage_convert_quote(&[__ws_arg_43]).await;
let mut data: Value = self.safe_dict_k(response, "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data, &[]);
Value::Null
}
/*
* @method
* @name coinbase#createConvertTrade
* @description convert from one currency to another
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/convert/commit-convert-trade
* @param {string} id the id of the trade that you want to make
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} [amount] how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn create_convert_trade(&mut self, mut id: Value, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade_id".to_string(), id);
m.insert("from_account".to_string(), fromCode);
m.insert("to_account".to_string(), toCode);
m
});
let __ws_arg_44 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_post_brokerage_convert_trade_trade_id(&[__ws_arg_44]).await;
let mut data: Value = self.safe_dict_k(response, "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data, &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchConvertTrade
* @description fetch the data for a conversion trade
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/convert/get-convert-trade
* @param {string} id the id of the trade that you want to commit
* @param {string} code the unified currency code that was converted from
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {strng} params.toCode the unified currency code that was converted into
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_trade(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = 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 (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchConvertTrade() requires a code argument".into()))));
}
let mut toCode: Value = self.safe_string_k(params.clone(), "toCode", &[]);
if (toCode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchConvertTrade() requires a toCode parameter".into()))));
}
params = self.omit(params.clone(), Value::Str("toCode".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade_id".to_string(), id);
m.insert("from_account".to_string(), code);
m.insert("to_account".to_string(), toCode);
m
});
let __ws_arg_45 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_convert_trade_trade_id(&[__ws_arg_45]).await;
let mut data: Value = self.safe_dict_k(response, "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data, &[]);
Value::Null
}
pub fn parse_conversion(&self, mut conversion: Value, optional_args: &[Value]) -> Value {
let mut fromCurrency = get_arg(optional_args, 0, Value::Null);
let mut toCurrency = get_arg(optional_args, 1, Value::Null);
let mut fromCoin: Value = self.safe_string_k(conversion.clone(), "source_currency", &[]);
let mut fromCode: Value = self.safe_currency_code(fromCoin, &[fromCurrency]);
let mut to: Value = self.safe_string_k(conversion.clone(), "target_currency", &[]);
let mut toCode: Value = self.safe_currency_code(to, &[toCurrency]);
let mut fromAmountStructure: Value = self.safe_dict_k(conversion.clone(), "user_entered_amount", &[]);
let mut feeStructure: Value = self.safe_dict_k(conversion.clone(), "total_fee", &[]);
let mut feeAmountStructure: Value = self.safe_dict_k(feeStructure, "amount", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), conversion.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("id".to_string(), self.safe_string_k(conversion, "id", &[]));
m.insert("fromCurrency".to_string(), fromCode);
m.insert("fromAmount".to_string(), self.safe_number_k(fromAmountStructure, "value", &[]));
m.insert("toCurrency".to_string(), toCode);
m.insert("toAmount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
m.insert("fee".to_string(), self.safe_number_k(feeAmountStructure, "value", &[]));
m
});
Value::Null
}
/*
* @method
* @name coinbase#transfer
* @description transfer currency internally between portfolios of the same account
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/portfolios/move-portfolios-funds
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount the portfolio uuid to transfer funds from
* @param {string} toAccount the portfolio uuid to transfer funds to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funds".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("value".to_string(), self.currency_to_precision(code, amount.clone(), &[]));
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
m.insert("source_portfolio_uuid".to_string(), fromAccount);
m.insert("target_portfolio_uuid".to_string(), toAccount);
m
});
let __ws_arg_46 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_post_brokerage_portfolios_move_funds(&[__ws_arg_46]).await;
//
// {
// "source_portfolio_uuid": "8bfc20d7-f7c6-4422-bf07-8243ca4169fe",
// "target_portfolio_uuid": "8bfc20d7-f7c6-4422-bf07-8243ca4169fe"
// }
//
let mut transfer: Value = self.parse_transfer(response, &[currency]);
add_element_to_object(&mut transfer, &Value::Str("amount".into()), amount);
add_element_to_object(&mut transfer, &Value::Str("status".into()), Value::Str("ok".into()));
return transfer;
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "source_portfolio_uuid": "8bfc20d7-f7c6-4422-bf07-8243ca4169fe",
// "target_portfolio_uuid": "8bfc20d7-f7c6-4422-bf07-8243ca4169fe"
// }
//
let mut currencyCode: Value = self.safe_currency_code(Value::Null, &[currency]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("currency".to_string(), currencyCode);
m.insert("amount".to_string(), Value::Null);
m.insert("fromAccount".to_string(), self.safe_string_k(transfer.clone(), "source_portfolio_uuid", &[]));
m.insert("toAccount".to_string(), self.safe_string_k(transfer, "target_portfolio_uuid", &[]));
m.insert("status".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name coinbase#closePosition
* @description *futures only* closes open positions for a market
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/orders/close-position
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] not used by coinbase
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.clientOrderId *mandatory* the client order id of the position to close
* @param {float} [params.size] the size of the position to close, optional
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn close_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut side = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("client_order_id".into()), Value::Str("clientOrderId".into()), &[]);
params = self.omit(params.clone(), Value::Str("clientOrderId".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (clientOrderId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" closePosition() requires a clientOrderId parameter".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_order_id".into(), clientOrderId); }
let __ws_arg_47 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_post_brokerage_orders_close_position(&[__ws_arg_47]).await;
let mut order: Value = self.safe_dict_k(response, "success_response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order, &[]);
Value::Null
}
/*
* @method
* @name coinbase#fetchPositions
* @description fetch all open positions
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/us-derivatives/list-futures-positions
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/international-derivatives/list-perpetuals-positions
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.portfolio] the portfolio UUID to fetch positions for
* @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;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut market: Value = Value::Null;
if (symbols != Value::Null) {
market = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchPositions".into()), &[market, params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("future")) {
response = self.v3_private_get_brokerage_cfm_positions(&[params.clone()]).await;
} else {
let mut portfolio: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositions".into()), Value::Str("portfolio".into()), &[]); portfolio = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (portfolio == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() requires a \"portfolio\" value in params (eg: dbcb91e7-2bc9-515), or set as exchange.options[\"portfolio\"]. You can get a list of portfolios with fetchPortfolios()".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio_uuid".to_string(), portfolio);
m
});
let __ws_arg_48 = self.extend(request, &[params]);
response = self.v3_private_get_brokerage_intx_positions_portfolio_uuid(&[__ws_arg_48]).await;
}
let mut positions: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
return self.parse_positions(positions, &[symbols]);
Value::Null
}
/*
* @method
* @name coinbase#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/international-derivatives/get-perpetuals-position
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/us-derivatives/get-futures-position
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.product_id] *futures only* the product id of the position to fetch, required for futures markets only
* @param {string} [params.portfolio] *perpetual/swaps only* the portfolio UUID to fetch the position for, required for perpetual/swaps markets only
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&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 response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("future")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut productId: Value = self.safe_string_k(market.clone(), "product_id", &[]);
if (productId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() requires a \"product_id\" in params".into()))));
}
let mut futureRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), productId);
m
});
let __ws_arg_49 = self.extend(futureRequest, &[params.clone()]);
response = self.v3_private_get_brokerage_cfm_positions_product_id(&[__ws_arg_49]).await;
} else {
let mut portfolio: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchPositions".into()), Value::Str("portfolio".into()), &[]); portfolio = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (portfolio == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() requires a \"portfolio\" value in params (eg: dbcb91e7-2bc9-515), or set as exchange.options[\"portfolio\"]. You can get a list of portfolios with fetchPortfolios()".into()))));
}
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("portfolio_uuid".to_string(), portfolio);
m
});
let __ws_arg_50 = self.extend(request, &[params]);
response = self.v3_private_get_brokerage_intx_positions_portfolio_uuid_symbol(&[__ws_arg_50]).await;
}
let mut position: Value = self.safe_dict_k(response, "position", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_position(position, &[market]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "product_id": "1r4njf84-0-0",
// "product_uuid": "cd34c18b-3665-4ed8-9305-3db277c49fc5",
// "symbol": "ADA-PERP-INTX",
// "vwap": {
// "value": "0.6171",
// "currency": "USDC"
// },
// "position_side": "POSITION_SIDE_LONG",
// "net_size": "20",
// "buy_order_size": "0",
// "sell_order_size": "0",
// "im_contribution": "0.1",
// "unrealized_pnl": {
// "value": "0.074",
// "currency": "USDC"
// },
// "mark_price": {
// "value": "0.6208",
// "currency": "USDC"
// },
// "liquidation_price": {
// "value": "0",
// "currency": "USDC"
// },
// "leverage": "1",
// "im_notional": {
// "value": "12.342",
// "currency": "USDC"
// },
// "mm_notional": {
// "value": "0.814572",
// "currency": "USDC"
// },
// "position_notional": {
// "value": "12.342",
// "currency": "USDC"
// },
// "margin_type": "MARGIN_TYPE_CROSS",
// "liquidation_buffer": "19.677828",
// "liquidation_percentage": "4689.3506",
// "portfolio_summary": {
// "portfolio_uuid": "018ebd63-1f6d-7c8e-ada9-0761c5a2235f",
// "collateral": "20.4184",
// "position_notional": "12.342",
// "open_position_notional": "12.342",
// "pending_fees": "0",
// "borrow": "0",
// "accrued_interest": "0",
// "rolling_debt": "0",
// "portfolio_initial_margin": "0.1",
// "portfolio_im_notional": {
// "value": "12.342",
// "currency": "USDC"
// },
// "portfolio_maintenance_margin": "0.066",
// "portfolio_mm_notional": {
// "value": "0.814572",
// "currency": "USDC"
// },
// "liquidation_percentage": "4689.3506",
// "liquidation_buffer": "19.677828",
// "margin_type": "MARGIN_TYPE_CROSS",
// "margin_flags": "PORTFOLIO_MARGIN_FLAGS_UNSPECIFIED",
// "liquidation_status": "PORTFOLIO_LIQUIDATION_STATUS_NOT_LIQUIDATING",
// "unrealized_pnl": {
// "value": "0.074",
// "currency": "USDC"
// },
// "buying_power": {
// "value": "8.1504",
// "currency": "USDC"
// },
// "total_balance": {
// "value": "20.4924",
// "currency": "USDC"
// },
// "max_withdrawal": {
// "value": "8.0764",
// "currency": "USDC"
// }
// },
// "entry_vwap": {
// "value": "0.6091",
// "currency": "USDC"
// }
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[Value::Str("".into())]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut rawMargin: Option<String> = self.safe_string_k(position.clone(), "margin_type", &[]).as_str().map(str::to_owned);
let mut marginMode: Value = Value::Null;
if (rawMargin.is_some()) {
marginMode = (if (rawMargin.as_deref() == Some("MARGIN_TYPE_CROSS")) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
}
let mut notionalObject: Value = self.safe_dict_k(position.clone(), "position_notional", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionSide: Option<String> = self.safe_string_k(position.clone(), "position_side", &[]).as_str().map(str::to_owned);
let mut side: Value = (if (positionSide.as_deref() == Some("POSITION_SIDE_LONG")) { Value::Str("long".into()) } else { Value::Str("short".into()) });
let mut unrealizedPNLObject: Value = self.safe_dict_k(position.clone(), "unrealized_pnl", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut liquidationPriceObject: Value = self.safe_dict_k(position.clone(), "liquidation_price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut liquidationPrice: Value = self.safe_number_k(liquidationPriceObject, "value", &[]);
let mut vwapObject: Value = self.safe_dict_k(position.clone(), "vwap", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut summaryObject: Value = self.safe_dict_k(position.clone(), "portfolio_summary", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "product_id", &[]));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone()]));
m.insert("notional".to_string(), self.safe_number_k(notionalObject, "value", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("liquidationPrice".to_string(), liquidationPrice);
m.insert("entryPrice".to_string(), self.safe_number_k(vwapObject, "value", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(unrealizedPNLObject, "value", &[]));
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "net_size", &[]));
m.insert("contractSize".to_string(), market.as_map().and_then(|__m| __m.get("contractSize")).cloned().unwrap_or(Value::Null));
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("hedged".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("collateral".to_string(), self.safe_number_k(summaryObject, "collateral", &[]));
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), self.safe_number_k(position, "leverage", &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name coinbase#fetchTradingFees
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/fees/get-transaction-summary
* @description fetch the trading fees for multiple markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] 'spot' or 'swap'
* @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/?id=fee-structure} indexed by market symbols
*/
pub async fn fetch_trading_fees(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchTradingFees".into()), &[Value::Null, params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isSpot: bool = type_var.as_str() == Some("spot");
let mut productType: Value = (if isSpot { Value::Str("SPOT".into()) } else { Value::Str("FUTURE".into()) });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_type".to_string(), productType);
m
});
let __ws_arg_51 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_transaction_summary(&[__ws_arg_51]).await;
//
// {
// total_volume: '0',
// total_fees: '0',
// fee_tier: {
// pricing_tier: 'Advanced 1',
// usd_from: '0',
// usd_to: '1000',
// taker_fee_rate: '0.008',
// maker_fee_rate: '0.006',
// aop_from: '',
// aop_to: ''
// },
// margin_rate: null,
// goods_and_services_tax: null,
// advanced_trade_only_volume: '0',
// advanced_trade_only_fees: '0',
// coinbase_pro_volume: '0',
// coinbase_pro_fees: '0',
// total_balance: '',
// has_promo_fee: false
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker_fee: Value = self.safe_number_k(data.clone(), "taker_fee_rate", &[]);
let mut maker_fee: Value = self.safe_number_k(data, "maker_fee_rate", &[]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_533: bool = true;
while { if !__for_first_533 { 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_533 = false; i.as_f64().unwrap_or(f64::NAN) < ((self.symbols.len() as i64) as f64) } {
let mut symbol: Value = self.symbols.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 market: Value = self.market(symbol.clone());
if (isSpot && (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) || (!isSpot && (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true))) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("maker".to_string(), maker_fee.clone());
m.insert("taker".to_string(), taker_fee.clone());
m.insert("percentage".to_string(), Value::Bool(true));
m
})); }
}
}
}
return result;
Value::Null
}
/*
* @method
* @name coinbase#fetchPortfolioDetails
* @description Fetch details for a specific portfolio by UUID
* @see https://docs.cdp.coinbase.com/api-reference/advanced-trade-api/rest-api/portfolios/get-portfolio-breakdown
* @param {string} portfolioUuid The unique identifier of the portfolio to fetch
* @param {Dict} [params] Extra parameters specific to the exchange API endpoint
* @returns {any[]} An account structure <https://docs.ccxt.com/?id=account-structure>
*/
pub async fn fetch_portfolio_details(&mut self, mut portfolioUuid: 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 request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio_uuid".to_string(), portfolioUuid);
m
});
let __ws_arg_52 = self.extend(request, &[params]);
let mut response: Value = self.v3_private_get_brokerage_portfolios_portfolio_uuid(&[__ws_arg_52]).await;
let mut result: Value = self.parse_portfolio_details(response);
return result;
Value::Null
}
pub fn parse_portfolio_details(&self, mut portfolioData: Value) -> Value {
let __portfolioData_empty = indexmap::IndexMap::new();
let portfolioData = portfolioData.as_map().unwrap_or(&__portfolioData_empty);
let mut breakdown: Value = portfolioData.get("breakdown").cloned().unwrap_or(Value::Null);
let mut portfolioInfo: Value = self.safe_dict_k(breakdown.clone(), "portfolio", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut portfolioName: Value = self.safe_string_k(portfolioInfo.clone(), "name", &[Value::Str("Unknown".into())]);
let mut portfolioUuid: Value = self.safe_string_k(portfolioInfo, "uuid", &[Value::Str("".into())]);
let mut spotPositions: Value = self.safe_list_k(breakdown, "spot_positions", &[Value::from(vec![])]);
let mut parsedPositions: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_534: bool = true;
while { if !__for_first_534 { 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_534 = false; i.as_f64().unwrap_or(f64::NAN) < ((spotPositions.len() as i64) as f64) } {
let mut position: Value = spotPositions.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 currencyCode: Value = self.safe_string_k(position.clone(), "asset", &[Value::Str("Unknown".into())]);
let mut availableBalanceStr: Value = self.safe_string_k(position.clone(), "available_to_trade_fiat", &[Value::Str("0".into())]);
let mut availableBalance: Value = self.parse_number(availableBalanceStr, &[]);
let mut totalBalanceFiatStr: Value = self.safe_string_k(position.clone(), "total_balance_fiat", &[Value::Str("0".into())]);
let mut totalBalanceFiat: Value = self.parse_number(totalBalanceFiatStr, &[]);
let mut holdAmount: Value = (match (&(totalBalanceFiat), &(availableBalance)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut costBasisDict: Value = self.safe_dict_k(position.clone(), "cost_basis", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut costBasisStr: Value = self.safe_string_k(costBasisDict.clone(), "value", &[Value::Str("0".into())]);
let mut averageEntryPriceDict: Value = self.safe_dict_k(position.clone(), "average_entry_price", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut averageEntryPriceStr: Value = self.safe_string_k(averageEntryPriceDict.clone(), "value", &[Value::Str("0".into())]);
let mut positionData: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currencyCode);
m.insert("available_balance".to_string(), availableBalance);
m.insert("hold_amount".to_string(), (if holdAmount.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) { holdAmount } else { Value::Int(0) }));
m.insert("wallet_name".to_string(), portfolioName.clone());
m.insert("account_id".to_string(), portfolioUuid.clone());
m.insert("account_uuid".to_string(), self.safe_string_k(position.clone(), "account_uuid", &[Value::Str("".into())]));
m.insert("total_balance_fiat".to_string(), totalBalanceFiat);
m.insert("total_balance_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "total_balance_crypto", &[Value::Str("0".into())]), &[]));
m.insert("available_to_trade_fiat".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_fiat", &[Value::Str("0".into())]), &[]));
m.insert("available_to_trade_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_crypto", &[Value::Str("0".into())]), &[]));
m.insert("available_to_transfer_fiat".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_transfer_fiat", &[Value::Str("0".into())]), &[]));
m.insert("available_to_transfer_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_crypto", &[Value::Str("0".into())]), &[]));
m.insert("allocation".to_string(), self.parse_number(self.safe_string_k(position.clone(), "allocation", &[Value::Str("0".into())]), &[]));
m.insert("cost_basis".to_string(), self.parse_number(costBasisStr, &[]));
m.insert("cost_basis_currency".to_string(), self.safe_string_k(costBasisDict, "currency", &[Value::Str("USD".into())]));
m.insert("is_cash".to_string(), self.safe_bool_k(position.clone(), "is_cash", &[Value::Bool(false)]));
m.insert("average_entry_price".to_string(), self.parse_number(averageEntryPriceStr, &[]));
m.insert("average_entry_price_currency".to_string(), self.safe_string_k(averageEntryPriceDict, "currency", &[Value::Str("USD".into())]));
m.insert("asset_uuid".to_string(), self.safe_string_k(position.clone(), "asset_uuid", &[Value::Str("".into())]));
m.insert("unrealized_pnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealized_pnl", &[Value::Str("0".into())]), &[]));
m.insert("asset_color".to_string(), self.safe_string_k(position.clone(), "asset_color", &[Value::Str("".into())]));
m.insert("account_type".to_string(), self.safe_string_k(position, "account_type", &[Value::Str("".into())]));
m
});
append_to_array(&mut parsedPositions, positionData);
}
}
return parsedPositions;
Value::Null
}
pub fn create_auth_token(&self, mut seconds: Value, optional_args: &[Value]) -> Value {
let mut method = get_arg(optional_args, 0, Value::Null);
let mut url = get_arg(optional_args, 1, Value::Null);
let mut useEddsa = get_arg(optional_args, 2, Value::Bool(false));
// v1 https://docs.cdp.coinbase.com/api-reference/authentication#php-2
// v2 https://docs.cdp.coinbase.com/api-reference/v2/authentication
let mut uri: Value = Value::Null;
if (url != Value::Null) {
uri = Value::Str(format!("{}{}", Value::Str(format!("{}{}", method, Value::Str(" ".into())).into()), replace_str(&url, &Value::Str("https://".into()), &Value::Str("".into()))).into());
let mut quesPos: Value = Value::Int(uri.as_str().and_then(|__s| __s.find("?")).map(|__i| __i as i64).unwrap_or(-1));
// Due to we use mb_strpos, quesPos could be false in php. In that case, the quesPos >= 0 is true
// Also it's not possible that the question mark is first character, only check > 0 here.
if quesPos.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
uri = slice(&uri, &Value::Int(0), &quesPos);
}
}
// eddsa {"sub":"d2efa49a-369c-43d7-a60e-ae26e28853c2","iss":"cdp","aud":["cdp_service"],"uris":["GET api.coinbase.com/api/v3/brokerage/transaction_summary"]}
let mut nonce: Value = self.random_bytes(Value::Int(16));
let mut aud: Value = (if is_true(&useEddsa) { Value::Str("cdp_service".into()) } else { Value::Str("retail_rest_api_proxy".into()) });
let mut iss: Value = (if is_true(&useEddsa) { Value::Str("cdp".into()) } else { Value::Str("coinbase-cloud".into()) });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("aud".to_string(), Value::from(vec![aud]));
m.insert("iss".to_string(), iss);
m.insert("nbf".to_string(), seconds.clone());
m.insert("exp".to_string(), (match (&(seconds), &(Value::Int(120))) { (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 }));
m.insert("sub".to_string(), self.apiKey.clone());
m.insert("iat".to_string(), seconds);
m
});
if (uri != Value::Null) {
if !is_true(&useEddsa) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uri".into(), uri.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uris".into(), Value::from(vec![uri])); }
}
}
if is_true(&useEddsa) {
let mut byteArray: Value = self.base64_to_binary(self.secret.clone(), &[]);
let mut seed: Value = self.array_slice(byteArray, Value::Int(0), &[Value::Int(32)]);
return jwt(request.clone(), seed, Value::Str("sha256".into()), Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kid".to_string(), self.apiKey.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("alg".to_string(), Value::Str("EdDSA".into()));
m
}));
} else {
return jwt(request, self.encode(self.secret.clone()), Value::Str("sha256".into()), Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("kid".to_string(), self.apiKey.clone());
m.insert("nonce".to_string(), nonce);
m.insert("alg".to_string(), Value::Str("ES256".into()));
m
}));
}
Value::Null
}
pub fn nonce(&self) -> Value {
return subtract(&self.milliseconds(), &self.options.as_map().and_then(|__m| __m.get("timeDifference")).cloned().unwrap_or(Value::Null));
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![]));
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 version: Value = get_value(&api, &Value::Int(0));
let mut signed: bool = get_value(&api, &Value::Int(1)).as_str() == Some("private");
let mut isV3: bool = version.as_str() == Some("v3");
let mut pathPart: Value = (if (isV3) { Value::Str("api/v3".into()) } else { Value::Str("v2".into()) });
let mut fullPath: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/".into()), pathPart).into()), Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut savedPath: Value = fullPath.clone();
if (method.as_str() == Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
fullPath = Value::Str(format!("{}{}", fullPath, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode_with_array_repeat(query.clone())).into())).into());
}
}
let mut url: Value = add(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("rest")).cloned().unwrap_or(Value::Null), &fullPath);
if signed {
let mut authorization: Value = self.safe_string_k(self.headers.clone(), "Authorization", &[]);
let mut authorizationString: Value = Value::Null;
if (authorization != Value::Null) {
authorizationString = authorization;
} else if (self.token.as_str() != Some("")) && !(self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true)) {
authorizationString = Value::Str(format!("{}{}", Value::Str("Bearer ".into()), self.token.clone()).into());
} else {
self.check_required_credentials(&[]);
let mut seconds: Value = self.seconds();
let mut payload: Value = Value::Str("".into());
if (method.as_str() != Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
body = json_stringify(&query);
payload = body.clone();
}
} else {
if !isV3 {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
payload = Value::Str(format!("{}{}", payload, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
}
}
// v3: 'GET' doesn't need payload in the signature. inside url is enough
// https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication
// v2: 'GET' require payload in the signature
// https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication
let mut isCloudAPiKey: bool = (Value::Int(self.apiKey.as_str().and_then(|__s| __s.find("organizations/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64)) || (starts_with(&self.secret, &Value::Str("-----BEGIN".into())));
// using the size might be fragile, so we add an option to force v2 cloud api key if needed
let mut isV2CloudAPiKey: Value = Value::Bool((Value::Int(self.secret.len() as i64).as_f64() == Some(88.0)) || is_true(&self.safe_bool_k(self.options.clone(), "v2CloudAPiKey", &[Value::Bool(false)])) || (ends_with(&self.secret, &Value::Str("=".into()))));
if isCloudAPiKey || matches!(&isV2CloudAPiKey, Value::Bool(true)) {
if isCloudAPiKey && (starts_with(&self.apiKey, &Value::Str("-----BEGIN".into()))) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" apiKey should contain the name (eg: organizations/3b910e93....) and not the public key".into()))));
}
// // it may not work for v2
// let uri = method + ' ' + url.replace ('https://', '');
// const quesPos = uri.indexOf ('?');
// // Due to we use mb_strpos, quesPos could be false in php. In that case, the quesPos >= 0 is true
// // Also it's not possible that the question mark is first character, only check > 0 here.
// if (quesPos > 0) {
// uri = uri.slice (0, quesPos);
// }
// const nonce = this.randomBytes (16);
// const request: Dict = {
// 'aud': [ 'retail_rest_api_proxy' ],
// 'iss': 'coinbase-cloud',
// 'nbf': seconds,
// 'exp': seconds + 120,
// 'sub': this.apiKey,
// 'uri': uri,
// 'iat': seconds,
// }
let mut token: Value = self.create_auth_token(seconds, &[method.clone(), url.clone(), isV2CloudAPiKey.clone()]);
// const token = jwt (request, this.encode (this.secret), sha256, false, { 'kid': this.apiKey, 'nonce': nonce, 'alg': 'ES256' });
authorizationString = Value::Str(format!("{}{}", Value::Str("Bearer ".into()), token).into());
} else {
let mut nonce: Value = self.nonce();
let mut timestamp: Value = self.parse_to_int((match ((nonce).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
let mut timestampString: Value = to_string_val(×tamp);
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestampString, method).into()), savedPath).into()), payload).into());
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CB-ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("CB-ACCESS-SIGN".to_string(), signature);
m.insert("CB-ACCESS-TIMESTAMP".to_string(), timestampString);
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
});
}
}
if (authorizationString != Value::Null) {
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Authorization".to_string(), authorizationString);
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
});
if (method.as_str() != Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
body = json_stringify(&query);
}
}
}
}
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(), body);
m.insert("headers".to_string(), headers);
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
//
// {"error": "invalid_request", "error_description": "The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed."}
//
// or
//
// {
// "errors": [
// {
// "id": "not_found",
// "message": "Not found"
// }
// ]
// }
// or
// {
// "success": false,
// "error_response": {
// "error": "UNKNOWN_FAILURE_REASON",
// "message": "",
// "error_details": "",
// "preview_failure_reason": "PREVIEW_STOP_PRICE_ABOVE_LAST_TRADE_PRICE"
// },
// "order_configuration": {
// "stop_limit_stop_limit_gtc": {
// "base_size": "0.0001",
// "limit_price": "2000",
// "stop_price": "2005",
// "stop_direction": "STOP_DIRECTION_STOP_DOWN",
// "reduce_only": false
// }
// }
// }
//
let mut errorCode: Value = self.safe_string_k(response.clone(), "error", &[]);
if (errorCode != Value::Null) {
let mut errorMessage: Value = self.safe_string2(response.clone(), Value::Str("error_description".into()), Value::Str("error".into()), &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessage.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
let mut errorResponse: Value = self.safe_dict_k(response.clone(), "error_response", &[]);
if (errorResponse != Value::Null) {
let mut errorMessageInner: Value = self.safe_string2(errorResponse, Value::Str("preview_failure_reason".into()), Value::Str("preview_failure_reason".into()), &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorMessageInner.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessageInner, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
let mut errors: Value = self.safe_list_k(response.clone(), "errors", &[]);
if (errors != Value::Null) {
if (matches!(&errors, Value::Arr(_))) {
let mut numErrors: f64 = ((errors.len() as i64) as f64);
if numErrors > ((0i64) as f64) {
errorCode = self.safe_string(errors.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Str("id".into()), &[]);
let mut errorMessage: Value = self.safe_string(errors.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Str("message".into()), &[]);
if (errorCode != Value::Null) {
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_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessage, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
}
}
let mut advancedTrade: Value = self.options.as_map().and_then(|__m| __m.get("advanced")).cloned().unwrap_or(Value::Null);
if !(in_op(&response, &Value::Str("data".into()))) && (!is_equal(&advancedTrade, &Value::Bool(true))) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" failed due to a malformed response ".into())).into()), json_stringify(&response))));
}
return Value::Null;
Value::Null
}
/*
* @method
* @name coinbase#fetchDepositAddresses
* @description fetch deposit addresses for multiple currencies (when available)
* @see https://docs.cdp.coinbase.com/coinbase-app/transfer-apis/onchain-addresses
* @param {string[]} [codes] list of unified currency codes, default is undefined (all currencies)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountId] account ID to fetch deposit addresses for
* @returns {object} a dictionary of [address structures]{@link https://docs.ccxt.com/?id=address-structure} indexed by currency code
*/
pub async fn fetch_deposit_addresses(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = self.prepare_account_request(&[Value::Null, params.clone()]);
let __ws_arg_53 = self.extend(request, &[params]);
let mut response: Value = self.v2_private_get_accounts_account_id_addresses(&[__ws_arg_53]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_deposit_addresses(data, &[codes, Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
}