// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
pub struct 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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone(), to_currency.clone()])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on CoinbaseCore.
CoinbaseCore::sign(self, path, &[api.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on 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.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_auth_token" => self.create_auth_token(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"create_convert_trade" => self.create_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args.get(3..).unwrap_or(&[]).to_vec()[..]).await,
"create_deposit_address" => self.create_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"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.get(3..).unwrap_or(&[]).to_vec()[..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_accounts" => self.fetch_accounts(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_accounts_v2" => self.fetch_accounts_v2(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_accounts_v3" => self.fetch_accounts_v3(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_bids_asks" => self.fetch_bids_asks(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_convert_quote" => self.fetch_convert_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_convert_trade" => self.fetch_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_currencies" => self.fetch_currencies(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_currencies_from_cache" => self.fetch_currencies_from_cache(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit" => self.fetch_deposit(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_addresses" => self.fetch_deposit_addresses(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_addresses_by_network" => self.fetch_deposit_addresses_by_network(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_method_id" => self.fetch_deposit_method_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_method_ids" => self.fetch_deposit_method_ids(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits" => self.fetch_deposits(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ledger" => self.fetch_ledger(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets_v2" => self.fetch_markets_v2(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets_v3" => self.fetch_markets_v3(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_buys" => self.fetch_my_buys(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_sells" => self.fetch_my_sells(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders_by_status" => self.fetch_orders_by_status(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_portfolio_details" => self.fetch_portfolio_details(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_portfolios" => self.fetch_portfolios(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker_v2" => self.fetch_ticker_v2(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker_v3" => self.fetch_ticker_v3(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers_v2" => self.fetch_tickers_v2(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers_v3" => self.fetch_tickers_v3(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_time" => self.fetch_time(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trading_fees" => self.fetch_trading_fees(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_transactions_with_method" => self.fetch_transactions_with_method(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"find_account_id" => self.find_account_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"nonce" => self.nonce(),
"parse_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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_custom_balance" => self.parse_custom_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry_status" => self.parse_ledger_entry_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ledger_entry_type" => self.parse_ledger_entry_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_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.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"prepare_account_request" => self.prepare_account_request(&args.get(0..).unwrap_or(&[]).to_vec()[..]),
"prepare_account_request_with_currency_code" => self.prepare_account_request_with_currency_code(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args.get(3..).unwrap_or(&[]).to_vec()[..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for 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".to_string()));
m.insert("name".to_string(), Value::Str("Coinbase Advanced".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("US".to_string())]));
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".to_string()));
m.insert("userAgent".to_string(), get_value(&self.userAgents, &Value::Str("chrome".to_string())));
m.insert("headers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CB-VERSION".to_string(), Value::Str("2018-05-30".to_string()));
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".to_string()));
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".to_string()));
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".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://api.coinbase.com".to_string()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.coinbase.com".to_string()));
m.insert("doc".to_string(), Value::List(vec![Value::Str("https://docs.cdp.coinbase.com/coinbase-app/introduction/welcome".to_string()), Value::Str("https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/api-reference".to_string())]));
m.insert("fees".to_string(), Value::List(vec![Value::Str("https://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-fees".to_string()), Value::Str("https://www.coinbase.com/advanced-fees".to_string())]));
m.insert("referral".to_string(), Value::Str("https://www.coinbase.com/join/58cbe25a355148797479dbd2".to_string()));
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
}));
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/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/intx/allocate".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".to_string()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.006".to_string()), &[]));
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::List(vec![Value::List(vec![self.parse_number(Value::Str("0".to_string()), &[]), self.parse_number(Value::Str("0.006".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("10000".to_string()), &[]), self.parse_number(Value::Str("0.004".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("50000".to_string()), &[]), self.parse_number(Value::Str("0.0025".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000".to_string()), &[]), self.parse_number(Value::Str("0.002".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("1000000".to_string()), &[]), self.parse_number(Value::Str("0.0018".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("15000000".to_string()), &[]), self.parse_number(Value::Str("0.0016".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("75000000".to_string()), &[]), self.parse_number(Value::Str("0.0012".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("250000000".to_string()), &[]), self.parse_number(Value::Str("0.0008".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("400000000".to_string()), &[]), self.parse_number(Value::Str("0.0005".to_string()), &[])])]));
m.insert("maker".to_string(), Value::List(vec![Value::List(vec![self.parse_number(Value::Str("0".to_string()), &[]), self.parse_number(Value::Str("0.004".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("10000".to_string()), &[]), self.parse_number(Value::Str("0.0025".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("50000".to_string()), &[]), self.parse_number(Value::Str("0.0015".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000".to_string()), &[]), self.parse_number(Value::Str("0.001".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("1000000".to_string()), &[]), self.parse_number(Value::Str("0.0008".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("15000000".to_string()), &[]), self.parse_number(Value::Str("0.0006".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("75000000".to_string()), &[]), self.parse_number(Value::Str("0.0003".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("250000000".to_string()), &[]), self.parse_number(Value::Str("0.0".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("400000000".to_string()), &[]), self.parse_number(Value::Str("0.0".to_string()), &[])])]));
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".to_string()).clone());
m.insert("param_required".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("validation_error".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("invalid_request".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("personal_details_required".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("identity_verification_required".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("jumio_verification_required".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("jumio_face_match_verification_required".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("unverified_email".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("authentication_error".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("unauthorized".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("invalid_authentication_method".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("invalid_token".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("revoked_token".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("expired_token".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("invalid_scope".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("not_found".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("rate_limit_exceeded".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("resource_exhausted".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("internal_server_error".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("UNSUPPORTED_ORDER_CONFIGURATION".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("INSUFFICIENT_FUND".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("PERMISSION_DENIED".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("INVALID_ARGUMENT".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("PREVIEW_STOP_PRICE_ABOVE_LAST_TRADE_PRICE".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("PREVIEW_INSUFFICIENT_FUND".to_string(), Value::Str("InsufficientFunds".to_string()).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".to_string()).clone());
m.insert("request timestamp expired".to_string(), Value::Str("InvalidNonce".to_string()).clone());
m.insert("order with this orderID was not found".to_string(), Value::Str("OrderNotFound".to_string()).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".to_string()));
m.insert("5m".to_string(), Value::Str("FIVE_MINUTE".to_string()));
m.insert("15m".to_string(), Value::Str("FIFTEEN_MINUTE".to_string()));
m.insert("30m".to_string(), Value::Str("THIRTY_MINUTE".to_string()));
m.insert("1h".to_string(), Value::Str("ONE_HOUR".to_string()));
m.insert("2h".to_string(), Value::Str("TWO_HOUR".to_string()));
m.insert("6h".to_string(), Value::Str("SIX_HOUR".to_string()));
m.insert("1d".to_string(), Value::Str("ONE_DAY".to_string()));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CGLD".to_string(), Value::Str("CELO".to_string()));
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".to_string()));
m.insert("stablePairs".to_string(), Value::List(vec![Value::Str("BUSD-USD".to_string()), Value::Str("CBETH-ETH".to_string()), Value::Str("DAI-USD".to_string()), Value::Str("GUSD-USD".to_string()), Value::Str("GYEN-USD".to_string()), Value::Str("PAX-USD".to_string()), Value::Str("PAX-USDT".to_string()), Value::Str("USDC-EUR".to_string()), Value::Str("USDC-GBP".to_string()), Value::Str("USDT-EUR".to_string()), Value::Str("USDT-GBP".to_string()), Value::Str("USDT-USD".to_string()), Value::Str("USDT-USDC".to_string()), Value::Str("WBTC-BTC".to_string())]));
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::List(vec![Value::Str("wallet".to_string()), Value::Str("fiat".to_string())]));
m.insert("v3Accounts".to_string(), Value::List(vec![Value::Str("ACCOUNT_TYPE_CRYPTO".to_string()), Value::Str("ACCOUNT_TYPE_FIAT".to_string())]));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ERC20".to_string(), Value::Str("ethereum".to_string()));
m.insert("XLM".to_string(), Value::Str("stellar".to_string()));
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".to_string()));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Str("fetchTickerV3".to_string()));
m.insert("fetchTickers".to_string(), Value::Str("fetchTickersV3".to_string()));
m.insert("fetchAccounts".to_string(), Value::Str("fetchAccountsV3".to_string()));
m.insert("fetchBalance".to_string(), Value::Str("v2PrivateGetAccounts".to_string()));
m.insert("fetchTime".to_string(), Value::Str("v2PublicGetTime".to_string()));
m.insert("user_native_currency".to_string(), Value::Str("USD".to_string()));
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".to_string()));
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".to_string()));
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".to_string()));
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".to_string())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod.clone()]);
params = self.omit(params.clone(), Value::Str("method".to_string()), &[]);
let mut response: Value = Value::Null;
if is_equal(&method, &Value::Str("v2PublicGetTime".to_string())) {
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.clone()]).await;
}
return self.safe_timestamp2(response.clone(), Value::Str("epoch".to_string()), Value::Str("epochSeconds".to_string()), &[]);
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: Value = self.safe_string_k(self.options.clone(), "fetchAccounts", &[Value::Str("fetchAccountsV3".to_string())]);
if is_equal(&method, &Value::Str("fetchAccountsV3".to_string())) {
return self.fetch_accounts_v3(&[params.clone()]).await;
}
return self.fetch_accounts_v2(&[params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchAccounts".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchAccounts".to_string()), &[Value::Null, Value::Null, Value::Null, params.clone(), Value::Str("next_starting_after".to_string()), Value::Str("starting_after".to_string()), 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.clone(), &[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::List(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.clone(), "next_starting_after", &[]);
let mut accounts: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut length: Value = get_array_length(&accounts);
let mut lastIndex: Value = subtract(&length, &Value::Int(1));
let mut last: Value = self.safe_dict(accounts.clone(), lastIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
add_element_to_object(&mut last, &Value::Str("next_starting_after".to_string()), cursor.clone());
add_element_to_object(&mut accounts, &lastIndex, last.clone());
}
return self.parse_accounts(data.clone(), &[params.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchAccounts".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchAccounts".to_string()), &[Value::Null, Value::Null, Value::Null, params.clone(), Value::Str("cursor".to_string()), Value::Str("cursor".to_string()), 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.clone(), &[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::List(vec![])]);
let mut accountsLength: Value = get_array_length(&accounts);
let mut cursor: Value = self.safe_string_k(response.clone(), "cursor", &[]);
if is_true(&(is_greater_than(&accountsLength, &Value::Int(0)))) && is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
let mut lastIndex: Value = subtract(&accountsLength, &Value::Int(1));
let mut last: Value = self.safe_dict(accounts.clone(), lastIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
add_element_to_object(&mut last, &Value::Str("cursor".to_string()), cursor.clone());
add_element_to_object(&mut accounts, &lastIndex, last.clone());
}
return self.parse_accounts(accounts.clone(), &[params.clone()]);
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.clone()]).await;
let mut portfolios: Value = self.safe_list_k(response.clone(), "portfolios", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_514: bool = true;
while { if !__for_first_514 { i = add(&i, &Value::Int(1)); } __for_first_514 = false; is_less_than(&i, &get_array_length(&portfolios)) } {
let mut portfolio: Value = get_value(&portfolios, &i);
let mut portfolio: Value = get_value(&portfolios, &i);
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.clone());
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.clone(), "code", &[currencyIdV3.clone()]);
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(" ".to_string()));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(account.clone(), Value::Str("id".to_string()), Value::Str("uuid".to_string()), &[]));
m.insert("type".to_string(), ternary(is_true(&(!is_equal(&active, &Value::Null))), self.safe_string_lower(parts.clone(), Value::Int(1), &[]), typeV2.clone()));
m.insert("code".to_string(), self.safe_currency_code(currencyId.clone(), &[]));
m.insert("info".to_string(), account.clone());
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".to_string()), &[]);
if is_equal(&accountId, &Value::Null) {
self.load_accounts(&[]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_515: bool = true;
while { if !__for_first_515 { i = add(&i, &Value::Int(1)); } __for_first_515 = false; is_less_than(&i, &get_array_length(&self.accounts)) } {
let mut account: Value = get_value(&self.accounts, &i);
if is_equal(&get_value(&account, &Value::Str("code".to_string())), &code) && is_equal(&get_value(&account, &Value::Str("type".to_string())), &Value::Str("wallet".to_string())) {
accountId = get_value(&account, &Value::Str("id".to_string()));
break;
}
}
}
}
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&add(&self.id, &Value::Str(" createDepositAddress() could not find the account with matching currency code ".to_string())), &code), &Value::Str(", specify an `account_id` extra param to target specific wallet".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId.clone());
m
});
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "address", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code.clone());
m.insert("tag".to_string(), tag.clone());
m.insert("address".to_string(), address.clone());
m.insert("network".to_string(), Value::Null);
m.insert("info".to_string(), response.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
let __ws_arg_3 = self.extend(request.clone(), &[query.clone()]);
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.clone(), "data", &[Value::List(vec![])]);
return self.parse_trades(sellsData.clone(), &[Value::Null, since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
let __ws_arg_4 = self.extend(request.clone(), &[query.clone()]);
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.clone(), "data", &[Value::List(vec![])]);
return self.parse_trades(buysData.clone(), &[Value::Null, since.clone(), limit.clone()]);
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.clone(), limit.clone(), params.clone()]).await; request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = Value::Null;
if is_equal(&method, &Value::Str("v2PrivateGetAccountsAccountIdTransactions".to_string())) {
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 is_equal(&method, &Value::Str("v2PrivateGetAccountsAccountIdWithdrawals".to_string())) {
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.clone(), &[params.clone()]);
response = self.v2_private_get_accounts_account_id_deposits(&[__ws_arg_7]).await;
}
return self.parse_transactions(get_value(&response, &Value::Str("data".to_string())), &[Value::Null, since.clone(), limit.clone()]);
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".to_string()), Value::Str("currencyType".to_string()), &[]); currencyType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(¤cyType, &Value::Str("crypto".to_string())) {
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(results.clone(), Value::Str("type".to_string()), &[Value::Str("withdrawal".to_string()), Value::Bool(false)]);
}
return self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdWithdrawals".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).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".to_string()), Value::Str("currencyType".to_string()), &[]); currencyType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(¤cyType, &Value::Str("crypto".to_string())) {
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(results.clone(), Value::Str("type".to_string()), &[Value::Str("deposit".to_string()), Value::Bool(false)]);
}
return self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdDeposits".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut results: Value = self.fetch_transactions_with_method(Value::Str("v2PrivateGetAccountsAccountIdTransactions".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
return self.filter_by_array(results.clone(), Value::Str("type".to_string()), &[Value::List(vec![Value::Str("deposit".to_string()), Value::Str("withdrawal".to_string())]), 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".to_string()));
m.insert("completed".to_string(), Value::Str("ok".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// 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: Value = self.safe_string_k(transaction.clone(), "type", &[]);
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 is_equal(&transactionType, &Value::Str("send".to_string())) {
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 is_equal(&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 is_equal(&status, &Value::Null) {
let mut committed: Value = self.safe_bool_k(transaction.clone(), "committed", &[]);
status = ternary(is_true(&(is_equal(&committed, &Value::Bool(true)))), Value::Str("ok".to_string()), Value::Str("pending".to_string()));
}
let mut id: Value = self.safe_string_k(transaction.clone(), "id", &[]);
let mut currencyId: Value = self.safe_string_k(amountAndCurrencyObject.clone(), "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.clone();
if !is_true(&self.in_array(type_var.clone(), Value::List(vec![Value::Str("deposit".to_string()), Value::Str("withdrawal".to_string())]))) {
if is_true(&crate::precise::Precise::stringGt(&amountString, &Value::Str("0".to_string()))) {
type_var = Value::Str("deposit".to_string());
} else if is_true(&crate::precise::Precise::stringLt(&amountString, &Value::Str("0".to_string()))) {
type_var = Value::Str("withdrawal".to_string());
}
}
let mut toObject: Value = self.safe_dict_k(transaction.clone(), "to", &[]);
let mut addressTo: Value = self.safe_string_k(toObject.clone(), "address", &[]);
let mut networkId: Value = self.safe_string_k(network.clone(), "network_name", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
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.clone(), "hash", &[id.clone()]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("network".to_string(), self.network_id_to_code(&[networkId.clone(), code.clone()]));
m.insert("address".to_string(), addressTo.clone());
m.insert("addressTo".to_string(), addressTo.clone());
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.clone());
m.insert("amount".to_string(), self.parse_number(amountStringAbs.clone(), &[]));
m.insert("currency".to_string(), code.clone());
m.insert("status".to_string(), status.clone());
m.insert("updated".to_string(), self.parse8601(self.safe_string_k(transaction.clone(), "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.clone(), "amount", &[]));
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId.clone(), &[]));
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.clone(), market.clone(), Value::Str("-".to_string())]);
if !is_equal(&market, &Value::Null) {
symbol = get_value(&market, &Value::Str("symbol".to_string()));
} else {
let mut baseId: Value = self.safe_string_k(amountObject.clone(), "currency", &[]);
let mut quoteId: Value = self.safe_string_k(totalObject.clone(), "currency", &[]);
if is_true(&(!is_equal(&baseId, &Value::Null))) && is_true(&(!is_equal("eId, &Value::Null))) {
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
symbol = add(&add(&base, &Value::Str("/".to_string())), "e);
}
}
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 is_equal(&sizeInQuote, &Value::Bool(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.clone(), "amount", &[v3Amount.clone()]);
let mut costString: Value = self.safe_string_k(subtotalObject.clone(), "amount", &[v3Cost.clone()]);
let mut priceString: Value = Value::Null;
let mut cost: Value = Value::Null;
if is_true(&(!is_equal(&costString, &Value::Null))) && is_true(&(!is_equal(&amountString, &Value::Null))) {
priceString = crate::precise::Precise::stringDiv(&costString, &amountString);
} else {
priceString = v3Price.clone();
}
if is_true(&(!is_equal(&priceString, &Value::Null))) && is_true(&(!is_equal(&amountString, &Value::Null))) {
cost = crate::precise::Precise::stringMul(&priceString, &amountString);
} else {
cost = costString.clone();
}
let mut feeCurrencyId: Value = self.safe_string_k(feeObject.clone(), "currency", &[]);
let mut feeCost: Value = self.safe_number_k(feeObject.clone(), "amount", &[self.parse_number(v3FeeCost.clone(), &[])]);
if is_true(&(is_equal(&feeCurrencyId, &Value::Null))) && is_true(&(!is_equal(&market, &Value::Null))) && is_true(&(!is_equal(&feeCost, &Value::Null))) {
feeCurrencyId = get_value(&market, &Value::Str("quote".to_string()));
}
let mut datetime: Value = self.safe_string_n(trade.clone(), Value::List(vec![Value::Str("created_at".to_string()), Value::Str("trade_time".to_string()), Value::Str("time".to_string())]), &[]);
let mut side: Value = self.safe_string_lower2(trade.clone(), Value::Str("resource".to_string()), Value::Str("side".to_string()), &[]);
let mut takerOrMaker: Value = self.safe_string_lower(trade.clone(), Value::Str("liquidity_indicator".to_string()), &[]);
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".to_string()), Value::Str("trade_id".to_string()), &[]));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "order_id", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), ternary(is_true(&(is_equal(&side, &Value::Str("unknown_order_side".to_string())))), Value::Null, side.clone()));
m.insert("takerOrMaker".to_string(), ternary(is_true(&(is_equal(&takerOrMaker, &Value::Str("unknown_liquidity_indicator".to_string())))), Value::Null, takerOrMaker.clone()));
m.insert("price".to_string(), priceString.clone());
m.insert("amount".to_string(), amountString.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), self.safe_currency_code(feeCurrencyId.clone(), &[]));
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(&get_value(&self.options, &Value::Str("adjustForTimeDifference".to_string())), &Value::Bool(true)) {
self.load_time_difference(&[]).await;
}
let mut method: Value = self.safe_string_k(self.options.clone(), "fetchMarkets", &[Value::Str("fetchMarketsV3".to_string())]);
if is_equal(&method, &Value::Str("fetchMarketsV3".to_string())) {
return self.fetch_markets_v3(&[params.clone()]).await;
}
return self.fetch_markets_v2(&[params.clone()]).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.clone()]).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.clone(), "exchangeRates", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_list_k(currencies.clone(), "data", &[Value::List(vec![])]);
let mut dataById: Value = self.index_by(data.clone(), Value::Str("id".to_string()));
let mut rates: Value = self.safe_dict(self.safe_dict_k(exchangeRates.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("rates".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseIds: Value = object_keys(&rates);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_517: bool = true;
while { if !__for_first_517 { i = add(&i, &Value::Int(1)); } __for_first_517 = false; is_less_than(&i, &get_array_length(&baseIds)) } {
let mut baseId: Value = get_value(&baseIds, &i);
let mut baseId: Value = get_value(&baseIds, &i);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut type_var: Value = ternary(is_true(&(Value::Bool(in_op(&dataById, &baseId)))), Value::Str("fiat".to_string()), Value::Str("crypto".to_string()));
// https://github.com/ccxt/ccxt/issues/6066
if is_equal(&type_var, &Value::Str("crypto".to_string())) {
{
let mut j: Value = Value::Int(0);
let mut __for_first_516: bool = true;
while { if !__for_first_516 { j = add(&j, &Value::Int(1)); } __for_first_516 = false; is_less_than(&j, &get_array_length(&data)) } {
let mut quoteCurrency: Value = get_value(&data, &j);
let mut quoteCurrency: Value = get_value(&data, &j);
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(), add(&add(&baseId, &Value::Str("-".to_string())), "eId));
m.insert("symbol".to_string(), add(&add(&base, &Value::Str("/".to_string())), "e));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".to_string()));
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.clone());
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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut spotUnresolvedPromises: Value = Value::List(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 is_true(&self.check_required_credentials(&[Value::Bool(false)])) {
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::List(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".to_string()));
m
})]);
unresolvedContractPromises = Value::List(vec![self.v3_public_get_brokerage_market_products(&[__ws_arg_8]).await, self.v3_public_get_brokerage_market_products(&[self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_type".to_string(), Value::Str("FUTURE".to_string()));
m.insert("contract_expiry_type".to_string(), Value::Str("PERPETUAL".to_string()));
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::List(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::List(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.clone(), 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.clone(), 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.clone(), "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut expiringFeeTier: Value = self.safe_dict_k(expiringFees.clone(), "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); // fee tier null?
let mut perpetualFeeTier: Value = self.safe_dict_k(perpetualFees.clone(), "fee_tier", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); // fee tier null?
let mut data: Value = self.safe_list_k(spot.clone(), "products", &[Value::List(vec![])]);
let mut result: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_518: bool = true;
while { if !__for_first_518 { i = add(&i, &Value::Int(1)); } __for_first_518 = false; is_less_than(&i, &get_array_length(&data)) } {
append_to_array(&mut result, self.parse_spot_market(get_value(&data, &i), feeTier.clone()));
}
}
let mut futureData: Value = self.safe_list_k(expiringFutures.clone(), "products", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_519: bool = true;
while { if !__for_first_519 { i = add(&i, &Value::Int(1)); } __for_first_519 = false; is_less_than(&i, &get_array_length(&futureData)) } {
append_to_array(&mut result, self.parse_contract_market(get_value(&futureData, &i), expiringFeeTier.clone()));
}
}
let mut perpetualData: Value = self.safe_list_k(perpetualFutures.clone(), "products", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_520: bool = true;
while { if !__for_first_520 { i = add(&i, &Value::Int(1)); } __for_first_520 = false; is_less_than(&i, &get_array_length(&perpetualData)) } {
append_to_array(&mut result, self.parse_contract_market(get_value(&perpetualData, &i), perpetualFeeTier.clone()));
}
}
let mut newMarkets: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_521: bool = true;
while { if !__for_first_521 { i = add(&i, &Value::Int(1)); } __for_first_521 = false; is_less_than(&i, &get_array_length(&result)) } {
let mut market: Value = get_value(&result, &i);
let mut market: Value = get_value(&result, &i);
let mut info: Value = self.safe_value_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut realMarketIds: Value = self.safe_list_k(info.clone(), "alias_to", &[Value::List(vec![])]);
let mut length: Value = get_array_length(&realMarketIds);
if is_greater_than(&length, &Value::Int(0)) {
add_element_to_object(&mut market, &Value::Str("alias".to_string()), get_value(&realMarketIds, &Value::Int(0)));
} else {
add_element_to_object(&mut market, &Value::Str("alias".to_string()), Value::Null);
}
append_to_array(&mut newMarkets, market.clone());
}
}
return newMarkets;
Value::Null
}
pub fn parse_spot_market(&self, mut market: Value, mut feeTier: Value) -> Value {
//
// {
// "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(market.clone(), Value::Str("product_type".to_string()), &[]);
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::List(vec![])]);
let mut defaultTakerFee: Value = self.safe_number(get_value(&self.fees, &Value::Str("trading".to_string())), Value::Str("taker".to_string()), &[]);
let mut defaultMakerFee: Value = self.safe_number(get_value(&self.fees, &Value::Str("trading".to_string())), Value::Str("maker".to_string()), &[]);
let mut takerFee: Value = ternary(is_true(&self.in_array(id.clone(), stablePairs.clone())), Value::Float(0.00001), self.safe_number_k(feeTier.clone(), "taker_fee_rate", &[defaultTakerFee.clone()]));
let mut makerFee: Value = ternary(is_true(&self.in_array(id.clone(), stablePairs.clone())), Value::Int(0), self.safe_number_k(feeTier.clone(), "maker_fee_rate", &[defaultMakerFee.clone()]));
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), add(&add(&base, &Value::Str("/".to_string())), "e));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), marketType.clone());
m.insert("spot".to_string(), Value::Bool((is_equal(&marketType, &Value::Str("spot".to_string())))));
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(!is_equal(&tradingDisabled, &Value::Bool(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.clone());
m.insert("maker".to_string(), makerFee.clone());
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".to_string()), Value::Str("quote_increment".to_string()), &[]));
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.clone());
m
})]);
Value::Null
}
pub fn parse_contract_market(&self, mut market: Value, mut feeTier: Value) -> Value {
// 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: Value = self.safe_string_k(futureProductDetails.clone(), "contract_expiry_type", &[]);
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.clone());
let mut expireDateTime: Value = self.iso8601(expireTimestamp.clone());
let mut isSwap: Value = Value::Bool(is_equal(&contractExpiryType, &Value::Str("PERPETUAL".to_string())));
let mut baseId: Value = self.safe_string_k(futureProductDetails.clone(), "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 = add(&add(&base, &Value::Str("/".to_string())), "e);
let mut type_var: Value = Value::Null;
if is_true(&isSwap) {
type_var = Value::Str("swap".to_string());
symbol = add(&add(&symbol, &Value::Str(":".to_string())), "e);
} else {
type_var = Value::Str("future".to_string());
symbol = add(&add(&add(&add(&symbol, &Value::Str(":".to_string())), "e), &Value::Str("-".to_string())), &self.yymmdd(expireTimestamp.clone(), &[]));
}
let mut takerFeeRate: Value = self.safe_number_k(feeTier.clone(), "taker_fee_rate", &[]);
let mut makerFeeRate: Value = self.safe_number_k(feeTier.clone(), "maker_fee_rate", &[]);
let mut taker: Value = ternary(is_true(&(!is_equal(&takerFeeRate, &Value::Null) && !is_equal(&takerFeeRate, &Value::Null) && !is_equal(&takerFeeRate, &Value::Int(0)))), takerFeeRate.clone(), self.parse_number(Value::Str("0.06".to_string()), &[]));
let mut maker: Value = ternary(is_true(&(!is_equal(&makerFeeRate, &Value::Null) && !is_equal(&makerFeeRate, &Value::Null) && !is_equal(&makerFeeRate, &Value::Int(0)))), makerFeeRate.clone(), self.parse_number(Value::Str("0.04".to_string()), &[]));
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), quote.clone());
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), quoteId.clone());
m.insert("type".to_string(), type_var.clone());
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(!is_true(&isSwap)));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(!is_equal(&tradingDisabled, &Value::Bool(true))));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), taker.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("contractSize".to_string(), contractSize.clone());
m.insert("expiry".to_string(), expireTimestamp.clone());
m.insert("expiryDatetime".to_string(), expireDateTime.clone());
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".to_string()), Value::Str("quote_increment".to_string()), &[]));
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.clone());
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 is_true(&(is_equal(×tamp, &Value::Null))) || is_true(&(is_greater_than(&(subtract(&now, ×tamp)), &expires))) {
let mut promises: Value = Value::List(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.clone(), 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.clone(), "data", &[Value::List(vec![])]);
let mut cryptoData: Value = self.safe_list_k(cryptoResponse.clone(), "data", &[Value::List(vec![])]);
let mut exchangeRates: Value = self.v2_public_get_exchange_rates(&[params.clone()]).await;
let __ws_arg_9 = self.array_concat(fiatData.clone(), cryptoData.clone());
{ 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.clone());
m.insert("timestamp".to_string(), now.clone());
m
})]); add_element_to_object(&mut self.options, &Value::Str("fetchCurrencies".to_string()), __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::List(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.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.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.clone(), Value::Int(2), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fiatData: Value = self.safe_list_k(fiatResponse.clone(), "data", &[Value::List(vec![])]);
let mut cryptoData: Value = self.safe_list_k(cryptoResponse.clone(), "data", &[Value::List(vec![])]);
let mut ratesData: Value = self.safe_dict_k(ratesResponse.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rates: Value = self.safe_dict_k(ratesData.clone(), "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.clone(), cryptoData.clone());
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_522: bool = true;
while { if !__for_first_522 { i = add(&i, &Value::Int(1)); } __for_first_522 = false; is_less_than(&i, &get_array_length(¤cies)) } {
let mut currency: Value = get_value(¤cies, &i);
let mut currency: Value = get_value(¤cies, &i);
let mut assetId: Value = self.safe_string_k(currency.clone(), "asset_id", &[]);
let mut id: Value = self.safe_string2(currency.clone(), Value::Str("id".to_string()), Value::Str("code".to_string()), &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
let mut name: Value = self.safe_string_k(currency.clone(), "name", &[]);
if !is_equal(&code, &Value::Null) {
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("networks".to_string())), &code, to_lower(&name));
}
if !is_equal(&code, &Value::Null) {
add_element_to_object(get_value_mut(&mut self.options, &Value::Str("networksById".to_string())), &code, to_lower(&name));
}
let mut type_var: Value = ternary(is_true(&(!is_equal(&assetId, &Value::Null))), Value::Str("crypto".to_string()), Value::Str("fiat".to_string()));
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &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.clone());
m.insert("code".to_string(), code.clone());
m.insert("type".to_string(), type_var.clone());
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.clone(), "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 !is_equal(&assetId, &Value::Null) {
let mut lowerCaseName: Value = to_lower(&name);
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut networks, &code, lowerCaseName.clone());
}
add_element_to_object(&mut networksById, &lowerCaseName, code.clone());
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_523: bool = true;
while { if !__for_first_523 { i = add(&i, &Value::Int(1)); } __for_first_523 = false; is_less_than(&i, &get_array_length(&ratesIds)) } {
let mut currencyId: Value = get_value(&ratesIds, &i);
let mut currencyId: Value = get_value(&ratesIds, &i);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if is_true(&(is_equal(&code, &Value::Null))) || !is_true(&(Value::Bool(in_op(&result, &code)))) {
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &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.clone());
m.insert("code".to_string(), code.clone());
m.insert("type".to_string(), Value::Str("crypto".to_string()));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
})));
}
}
}
}
let __ws_arg_10 = get_value(&self.options, &Value::Str("networks".to_string()));
{ let __be_tmp = self.extend(networks.clone(), &[__ws_arg_10]); add_element_to_object(&mut self.options, &Value::Str("networks".to_string()), __be_tmp); };
let __ws_arg_11 = get_value(&self.options, &Value::Str("networksById".to_string()));
{ let __be_tmp = self.extend(networksById.clone(), &[__ws_arg_11]); add_element_to_object(&mut self.options, &Value::Str("networksById".to_string()), __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: Value = self.safe_string_k(self.options.clone(), "fetchTickers", &[Value::Str("fetchTickersV3".to_string())]);
if is_equal(&method, &Value::Str("fetchTickersV3".to_string())) {
return self.fetch_tickers_v3(&[symbols.clone(), params.clone()]).await;
}
return self.fetch_tickers_v2(&[symbols.clone(), params.clone()]).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 is_equal(&self.markets, &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.clone(), &[params.clone()]);
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.clone(), "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.clone(), "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("-".to_string());
{
let mut i: Value = Value::Int(0);
let mut __for_first_524: bool = true;
while { if !__for_first_524 { i = add(&i, &Value::Int(1)); } __for_first_524 = false; is_less_than(&i, &get_array_length(&baseIds)) } {
let mut baseId: Value = get_value(&baseIds, &i);
let mut baseId: Value = get_value(&baseIds, &i);
let mut marketId: Value = add(&add(&baseId, &delimiter), "eId);
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, delimiter.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
add_element_to_object(&mut result, &symbol, self.parse_ticker(get_value(&rates, &baseId), &[market.clone()]));
}
}
return self.filter_by_array_tickers(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
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 is_equal(&self.markets, &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 !is_equal(&symbols, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("product_ids".to_string()), self.market_ids(&[symbols.clone()]));
}
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchTickers".to_string()), &[self.get_market_from_symbols(&[symbols.clone()]), params.clone(), Value::Str("default".to_string())]); marketType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&marketType, &Value::Null) && !is_equal(&marketType, &Value::Str("default".to_string())) {
add_element_to_object(&mut request, &Value::Str("product_type".to_string()), ternary(is_true(&(is_equal(&marketType, &Value::Str("swap".to_string())))), Value::Str("FUTURE".to_string()), Value::Str("SPOT".to_string())));
}
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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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.clone(), &[params.clone()]);
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.clone(), "products", &[Value::List(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_525: bool = true;
while { if !__for_first_525 { i = add(&i, &Value::Int(1)); } __for_first_525 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut entry: Value = get_value(&data, &i);
let mut entry: Value = get_value(&data, &i);
let mut marketId: Value = self.safe_string_k(entry.clone(), "product_id", &[]);
let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Str("-".to_string())]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
add_element_to_object(&mut result, &symbol, self.parse_ticker(entry.clone(), &[market.clone()]));
}
}
return self.filter_by_array_tickers(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
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: Value = self.safe_string_k(self.options.clone(), "fetchTicker", &[Value::Str("fetchTickerV3".to_string())]);
if is_equal(&method, &Value::Str("fetchTickerV3".to_string())) {
return self.fetch_ticker_v3(symbol.clone(), &[params.clone()]).await;
}
return self.fetch_ticker_v2(symbol.clone(), &[params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
}), &[params.clone()]);
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.clone()]).await;
//
// {"data":{"base":"BTC","currency":"USD","amount":"48691.23"}}
//
let mut spotData: Value = self.safe_dict_k(spot.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut askData: Value = self.safe_dict_k(ask.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bidData: Value = self.safe_dict_k(bid.clone(), "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.clone(), "amount", &[]));
m.insert("ask".to_string(), self.safe_number_k(askData.clone(), "amount", &[]));
m.insert("price".to_string(), self.safe_number_k(spotData.clone(), "amount", &[]));
m
});
return self.parse_ticker(bidAskLast.clone(), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), get_value(&market, &Value::Str("id".to_string())));
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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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.clone(), &[params.clone()]);
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::List(vec![])]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.parse_ticker(first.clone(), &[market.clone()]);
add_element_to_object(&mut ticker, &Value::Str("bid".to_string()), self.safe_number_k(response.clone(), "best_bid", &[]));
add_element_to_object(&mut ticker, &Value::Str("ask".to_string()), self.safe_number_k(response.clone(), "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 is_true(&(Value::Bool(in_op(&ticker, &Value::Str("bids".to_string()))))) {
let mut bids: Value = self.safe_list_k(ticker.clone(), "bids", &[Value::List(vec![])]);
let mut asks: Value = self.safe_list_k(ticker.clone(), "asks", &[Value::List(vec![])]);
let mut firstBid: Value = self.safe_dict(bids.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut firstAsk: Value = self.safe_dict(asks.clone(), 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.clone(), "size", &[]);
ask = self.safe_number_k(firstAsk.clone(), "price", &[]);
askVolume = self.safe_number_k(firstAsk.clone(), "size", &[]);
}
let mut marketId: Value = self.safe_string_k(ticker.clone(), "product_id", &[]);
market = self.safe_market(&[marketId.clone(), 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(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("bid".to_string(), bid.clone());
m.insert("ask".to_string(), ask.clone());
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.clone());
m.insert("askVolume".to_string(), askVolume.clone());
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone());
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.clone());
m
}), &[market.clone()]);
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 mut balances: Value = self.safe_list2(response.clone(), Value::Str("data".to_string()), Value::Str("accounts".to_string()), &[Value::List(vec![])]);
let mut accounts: Value = self.safe_list_k(params.clone(), "type", &[get_value(&self.options, &Value::Str("accounts".to_string()))]);
let mut v3Accounts: Value = self.safe_list_k(params.clone(), "type", &[get_value(&self.options, &Value::Str("v3Accounts".to_string()))]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
{
let mut b: Value = Value::Int(0);
let mut __for_first_526: bool = true;
while { if !__for_first_526 { b = add(&b, &Value::Int(1)); } __for_first_526 = false; is_less_than(&b, &get_array_length(&balances)) } {
let mut balance: Value = get_value(&balances, &b);
let mut balance: Value = get_value(&balances, &b);
let mut type_var: Value = self.safe_string_k(balance.clone(), "type", &[]);
if is_true(&self.in_array(type_var.clone(), accounts.clone())) {
let mut value: Value = self.safe_dict_k(balance.clone(), "balance", &[]);
if !is_equal(&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 is_equal(&account, &Value::Null) {
account = self.account();
add_element_to_object(&mut account, &Value::Str("free".to_string()), free.clone());
add_element_to_object(&mut account, &Value::Str("total".to_string()), total.clone());
} else {
{ let __be_tmp = crate::precise::Precise::stringAdd(&get_value(&account, &Value::Str("free".to_string())), &total); add_element_to_object(&mut account, &Value::Str("free".to_string()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&get_value(&account, &Value::Str("total".to_string())), &total); add_element_to_object(&mut account, &Value::Str("total".to_string()), __be_tmp); };
}
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &code, account.clone());
}
}
} else if is_true(&self.in_array(type_var.clone(), v3Accounts.clone())) {
let mut available: Value = self.safe_dict_k(balance.clone(), "available_balance", &[]);
let mut hold: Value = self.safe_dict_k(balance.clone(), "hold", &[]);
if !is_equal(&available, &Value::Null) && !is_equal(&hold, &Value::Null) {
let mut currencyId: Value = self.safe_string_k(available.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut used: Value = self.safe_string_k(hold.clone(), "value", &[]);
let mut free: Value = self.safe_string_k(available.clone(), "value", &[]);
let mut total: Value = crate::precise::Precise::stringAdd(&used, &free);
let mut account: Value = self.safe_dict(result.clone(), code.clone(), &[]);
if is_equal(&account, &Value::Null) {
account = self.account();
add_element_to_object(&mut account, &Value::Str("free".to_string()), free.clone());
add_element_to_object(&mut account, &Value::Str("used".to_string()), used.clone());
add_element_to_object(&mut account, &Value::Str("total".to_string()), total.clone());
} else {
{ let __be_tmp = crate::precise::Precise::stringAdd(&get_value(&account, &Value::Str("free".to_string())), &free); add_element_to_object(&mut account, &Value::Str("free".to_string()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&get_value(&account, &Value::Str("used".to_string())), &used); add_element_to_object(&mut account, &Value::Str("used".to_string()), __be_tmp); };
{ let __be_tmp = crate::precise::Precise::stringAdd(&get_value(&account, &Value::Str("total".to_string())), &total); add_element_to_object(&mut account, &Value::Str("total".to_string()), __be_tmp); };
}
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &code, account.clone());
}
}
}
}
}
return self.safe_balance(result.clone());
Value::Null
}
/*
* @method
* @name 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
let mut isV3: Value = self.safe_bool_k(params.clone(), "v3", &[Value::Bool(false)]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("v3".to_string())]), &[]);
let mut marketType: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchBalance".to_string()), &[Value::Null, params.clone()]); marketType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut method: Value = self.safe_string_k(self.options.clone(), "fetchBalance", &[Value::Str("v3PrivateGetBrokerageAccounts".to_string())]);
if is_equal(&marketType, &Value::Str("future".to_string())) {
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 is_true(&(is_equal(&isV3, &Value::Bool(true)))) || is_true(&(is_equal(&method, &Value::Str("v3PrivateGetBrokerageAccounts".to_string())))) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), 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 {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), Value::Int(250));
let __ws_arg_19 = self.extend(request.clone(), &[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".to_string()), marketType.clone());
return self.parse_custom_balance(response.clone(), &[params.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchLedger".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchLedger".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("next_starting_after".to_string()), Value::Str("starting_after".to_string()), Value::Null, Value::Int(100)]).await;
}
let mut currency: Value = Value::Null;
if !is_equal(&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.clone(), limit.clone(), params.clone()]).await; request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
// 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.clone(), &[params.clone()]);
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::List(vec![])]);
let mut ledger: Value = self.parse_ledger(data.clone(), &[currency.clone(), since.clone(), limit.clone()]);
let mut length: Value = get_array_length(&ledger);
if is_equal(&length, &Value::Int(0)) {
return ledger;
}
let mut lastIndex: Value = subtract(&length, &Value::Int(1));
let mut last: Value = self.safe_dict(ledger.clone(), lastIndex.clone(), &[]);
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.clone(), "next_starting_after", &[]);
if is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
add_element_to_object(get_value_mut(&mut last, &Value::Str("info".to_string())), &Value::Str("next_starting_after".to_string()), cursor.clone());
add_element_to_object(&mut ledger, &lastIndex, last.clone());
}
return ledger;
Value::Null
}
pub fn parse_ledger_entry_status(&self, mut status: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("completed".to_string(), Value::Str("ok".to_string()));
m
});
return self.safe_string(types.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("buy".to_string(), Value::Str("trade".to_string()));
m.insert("sell".to_string(), Value::Str("trade".to_string()));
m.insert("fiat_deposit".to_string(), Value::Str("transaction".to_string()));
m.insert("fiat_withdrawal".to_string(), Value::Str("transaction".to_string()));
m.insert("exchange_deposit".to_string(), Value::Str("transaction".to_string()));
m.insert("exchange_withdrawal".to_string(), Value::Str("transaction".to_string()));
m.insert("send".to_string(), Value::Str("transaction".to_string()));
m.insert("pro_deposit".to_string(), Value::Str("transaction".to_string()));
m.insert("pro_withdrawal".to_string(), Value::Str("transaction".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// 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".to_string()))) {
direction = Value::Str("out".to_string());
amount = crate::precise::Precise::stringNeg(&amount);
} else {
direction = Value::Str("in".to_string());
}
let mut currencyId: Value = self.safe_string_k(amountInfo.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
currency = self.safe_currency(currencyId.clone(), &[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.clone(), "transaction_fee", &[]);
if !is_equal(&feeInfo, &Value::Null) {
let mut feeCurrencyId: Value = self.safe_string_k(feeInfo.clone(), "currency", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId.clone(), &[currency.clone()]);
let mut feeAmount: Value = self.safe_number_k(feeInfo.clone(), "amount", &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeAmount.clone());
m.insert("currency".to_string(), feeCurrencyCode.clone());
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", &[]));
let mut status: Value = self.parse_ledger_entry_status(self.safe_string_k(item.clone(), "status", &[]));
let mut path: Value = self.safe_string_k(item.clone(), "resource_path", &[]);
let mut accountId: Value = Value::Null;
if !is_equal(&path, &Value::Null) {
let mut parts: Value = split(&path, &Value::Str("/".to_string()));
let mut numParts: Value = get_array_length(&parts);
if is_greater_than(&numParts, &Value::Int(3)) {
accountId = get_value(&parts, &Value::Int(3));
}
}
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), id.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("direction".to_string(), direction.clone());
m.insert("account".to_string(), accountId.clone());
m.insert("referenceId".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), type_var.clone());
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m
}), &[currency.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
self.load_accounts(&[Value::Bool(false), params.clone()]).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_527: bool = true;
while { if !__for_first_527 { i = add(&i, &Value::Int(1)); } __for_first_527 = false; is_less_than(&i, &get_array_length(&self.accounts)) } {
let mut account: Value = get_value(&self.accounts, &i);
if is_equal(&get_value(&account, &Value::Str("code".to_string())), &code) {
return get_value(&account, &Value::Str("id".to_string()));
}
}
}
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.clone(), Value::Str("account_id".to_string()), Value::Str("accountId".to_string()), &[]);
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" prepareAccountRequest() method requires an account_id (or accountId) parameter".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
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".to_string()), Value::Str("accountId".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
if is_equal(&accountId, &Value::Null) {
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" prepareAccountRequestWithCurrencyCode() method requires an account_id (or accountId) parameter OR a currency code argument".to_string()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&add(&self.id, &Value::Str(" prepareAccountRequestWithCurrencyCode() could not find account id for ".to_string())), &code), &Value::Str(". You might try to generate the deposit address in the website for that coin first.".to_string()))));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId.clone());
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
return Value::List(vec![request.clone(), params.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" createMarketBuyOrderWithCost() supports spot orders only".to_string()))));
}
add_element_to_object(&mut params, &Value::Str("createMarketBuyOrderRequiresPrice".to_string()), Value::Bool(false));
return self.create_order(symbol.clone(), Value::Str("market".to_string()), Value::Str("buy".to_string()), cost.clone(), &[Value::Null, params.clone()]).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 is_equal(&self.markets, &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".to_string())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("client_order_id".to_string(), add(&add(&id, &Value::Str("-".to_string())), &self.uuid(&[])));
m.insert("product_id".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("side".to_string(), to_upper(&side));
m
});
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[]);
if is_equal(&reduceOnly, &Value::Bool(true)) {
params = self.omit(params.clone(), Value::Str("reduceOnly".to_string()), &[]);
add_element_to_object(&mut params, &Value::Str("amount".to_string()), amount.clone());
return self.close_position(symbol.clone(), &[side.clone(), params.clone()]).await;
}
let mut triggerPrice: Value = self.safe_number_n(params.clone(), Value::List(vec![Value::Str("stopPrice".to_string()), Value::Str("stop_price".to_string()), Value::Str("triggerPrice".to_string())]), &[]);
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 = !is_equal(&triggerPrice, &Value::Null);
let mut isStopLoss: bool = !is_equal(&stopLossPrice, &Value::Null);
let mut isTakeProfit: bool = !is_equal(&takeProfitPrice, &Value::Null);
let mut timeInForce: Value = self.safe_string_k(params.clone(), "timeInForce", &[]);
let mut postOnly: Value = ternary(is_true(&(is_equal(&timeInForce, &Value::Str("PO".to_string())))), Value::Bool(true), self.safe_bool2(params.clone(), Value::Str("postOnly".to_string()), Value::Str("post_only".to_string()), &[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 is_equal(&type_var, &Value::Str("limit".to_string())) {
if is_true(&isStop) {
if is_equal(&stopDirection, &Value::Null) {
stopDirection = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("STOP_DIRECTION_STOP_DOWN".to_string()), Value::Str("STOP_DIRECTION_STOP_UP".to_string()));
}
if is_true(&(is_equal(&timeInForce, &Value::Str("GTD".to_string())))) || is_true(&(!is_equal(&endTime, &Value::Null))) {
if is_equal(&endTime, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" createOrder() requires an end_time parameter for a GTD order".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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".to_string()), 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.clone()));
m.insert("stop_direction".to_string(), stopDirection.clone());
m
}));
m
}));
}
} else if is_true(&isStopLoss) || is_true(&isTakeProfit) {
let mut tpslPrice: Value = Value::Null;
if is_true(&isStopLoss) {
if is_equal(&stopDirection, &Value::Null) {
stopDirection = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("STOP_DIRECTION_STOP_UP".to_string()), Value::Str("STOP_DIRECTION_STOP_DOWN".to_string()));
}
tpslPrice = self.price_to_precision(symbol.clone(), stopLossPrice.clone());
} else {
if is_equal(&stopDirection, &Value::Null) {
stopDirection = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("STOP_DIRECTION_STOP_DOWN".to_string()), Value::Str("STOP_DIRECTION_STOP_UP".to_string()));
}
tpslPrice = self.price_to_precision(symbol.clone(), takeProfitPrice.clone());
}
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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.clone());
m.insert("stop_direction".to_string(), stopDirection.clone());
m
}));
m
}));
} else {
if is_true(&(is_equal(&timeInForce, &Value::Str("GTD".to_string())))) || is_true(&(!is_equal(&endTime, &Value::Null))) {
if is_equal(&endTime, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" createOrder() requires an end_time parameter for a GTD order".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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.clone());
m.insert("post_only".to_string(), postOnly.clone());
m
}));
m
}));
} else if is_equal(&timeInForce, &Value::Str("IOC".to_string())) {
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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 is_equal(&timeInForce, &Value::Str("FOK".to_string())) {
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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".to_string()), 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.clone());
m
}));
m
}));
}
}
} else {
if is_true(&isStop) || is_true(&isStopLoss) || is_true(&isTakeProfit) {
panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" createOrder() only stop limit orders are supported".to_string()))));
}
if is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))) && is_true(&(is_equal(&side, &Value::Str("buy".to_string())))) {
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".to_string()), Value::Str("createMarketBuyOrderRequiresPrice".to_string()), &[Value::Bool(true)]); createMarketBuyOrderRequiresPrice = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
params = self.omit(params.clone(), Value::Str("cost".to_string()), &[]);
if !is_equal(&cost, &Value::Null) {
total = self.cost_to_precision(symbol.clone(), cost.clone());
} else if is_true(&createMarketBuyOrderRequiresPrice) {
if is_equal(&price, &Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(add(&self.id, &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".to_string()))));
} else {
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price.clone());
let mut costRequest: Value = crate::precise::Precise::stringMul(&amountString, &priceString);
total = self.cost_to_precision(symbol.clone(), costRequest.clone());
}
} else {
total = self.cost_to_precision(symbol.clone(), amount.clone());
}
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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.clone());
m
}));
m
}));
} else {
add_element_to_object(&mut request, &Value::Str("order_configuration".to_string()), 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.clone(), amount.clone()));
m
}));
m
}));
}
}
let mut marginMode: Value = self.safe_string_k(params.clone(), "marginMode", &[]);
if !is_equal(&marginMode, &Value::Null) {
if is_equal(&marginMode, &Value::Str("isolated".to_string())) {
add_element_to_object(&mut request, &Value::Str("margin_type".to_string()), Value::Str("ISOLATED".to_string()));
} else if is_equal(&marginMode, &Value::Str("cross".to_string())) {
add_element_to_object(&mut request, &Value::Str("margin_type".to_string()), Value::Str("CROSS".to_string()));
}
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("timeInForce".to_string()), Value::Str("triggerPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("stopPrice".to_string()), Value::Str("stop_price".to_string()), Value::Str("stopDirection".to_string()), Value::Str("stop_direction".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("postOnly".to_string()), Value::Str("post_only".to_string()), Value::Str("end_time".to_string()), Value::Str("marginMode".to_string())]), &[]);
let mut preview: Value = self.safe_bool2(params.clone(), Value::Str("preview".to_string()), Value::Str("test".to_string()), &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if is_equal(&preview, &Value::Bool(true)) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("preview".to_string()), Value::Str("test".to_string())]), &[]);
request = self.omit(request.clone(), Value::Str("client_order_id".to_string()), &[]);
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.clone(), &[params.clone()]);
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 !is_equal(&success, &Value::Bool(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 !is_equal(&errorResponse, &Value::Null) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorTitle.clone(), errorMessage.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), errorTitle.clone(), errorMessage.clone());
panic!("{}", crate::exchange_errors::exchange_error(errorMessage));
}
}
let mut data: Value = self.safe_dict_k(response.clone(), "success_response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(data.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// 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.clone(), &[market.clone(), Value::Str("-".to_string())]);
if !is_equal(&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.clone(), "market_market_ioc", &[]);
let mut isLimit: bool = is_true(&(!is_equal(&limitGTC, &Value::Null))) || is_true(&(!is_equal(&limitGTD, &Value::Null))) || is_true(&(!is_equal(&limitIOC, &Value::Null)));
let mut isStop: bool = is_true(&(!is_equal(&stopLimitGTC, &Value::Null))) || is_true(&(!is_equal(&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 is_true(&isLimit) {
let mut target: Value = Value::Null;
if !is_equal(&limitGTC, &Value::Null) {
target = limitGTC.clone();
} else if !is_equal(&limitGTD, &Value::Null) {
target = limitGTD.clone();
} else {
target = limitIOC.clone();
}
price = self.safe_string_k(target.clone(), "limit_price", &[]);
amount = self.safe_string_k(target.clone(), "base_size", &[]);
postOnly = self.safe_bool_k(target.clone(), "post_only", &[]);
} else if is_true(&isStop) {
let mut stopTarget: Value = ternary(is_true(&(!is_equal(&stopLimitGTC, &Value::Null))), stopLimitGTC.clone(), stopLimitGTD.clone());
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.clone(), "stop_price", &[]);
} else {
amount = self.safe_string_k(marketIOC.clone(), "base_size", &[]);
}
let mut datetime: Value = self.safe_string_k(order.clone(), "created_time", &[]);
let mut totalFees: Value = self.safe_string_k(order.clone(), "total_fees", &[]);
let mut currencyFee: Value = Value::Null;
if is_true(&(!is_equal(&totalFees, &Value::Null))) && is_true(&(!is_equal(&market, &Value::Null))) {
currencyFee = get_value(&market, &Value::Str("quote".to_string()));
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), 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.clone());
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol.clone());
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.clone());
m.insert("side".to_string(), self.safe_string_lower(order.clone(), Value::Str("side".to_string()), &[]));
m.insert("price".to_string(), price.clone());
m.insert("triggerPrice".to_string(), triggerPrice.clone());
m.insert("amount".to_string(), amount.clone());
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.clone(), "total_fees", &[]));
m.insert("currency".to_string(), currencyFee.clone());
m
}));
m.insert("trades".to_string(), Value::Null);
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("OPEN".to_string(), Value::Str("open".to_string()));
m.insert("FILLED".to_string(), Value::Str("closed".to_string()));
m.insert("CANCELLED".to_string(), Value::Str("canceled".to_string()));
m.insert("EXPIRED".to_string(), Value::Str("canceled".to_string()));
m.insert("FAILED".to_string(), Value::Str("canceled".to_string()));
m.insert("UNKNOWN_ORDER_STATUS".to_string(), Value::Null);
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut type_var: Value) -> Value {
if is_equal(&type_var, &Value::Str("UNKNOWN_ORDER_TYPE".to_string())) {
return Value::Null;
}
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("MARKET".to_string(), Value::Str("market".to_string()));
m.insert("LIMIT".to_string(), Value::Str("limit".to_string()));
m.insert("STOP".to_string(), Value::Str("limit".to_string()));
m.insert("STOP_LIMIT".to_string(), Value::Str("limit".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("GOOD_UNTIL_CANCELLED".to_string(), Value::Str("GTC".to_string()));
m.insert("GOOD_UNTIL_DATE_TIME".to_string(), Value::Str("GTD".to_string()));
m.insert("IMMEDIATE_OR_CANCEL".to_string(), Value::Str("IOC".to_string()));
m.insert("FILL_OR_KILL".to_string(), Value::Str("FOK".to_string()));
m.insert("UNKNOWN_TIME_IN_FORCE".to_string(), Value::Null);
m
});
return self.safe_string(timeInForces.clone(), 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.cancel_orders(Value::List(vec![id.clone()]), &[symbol.clone(), params.clone()]).await;
return self.safe_dict(orders.clone(), 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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_ids".to_string(), ids.clone());
m
});
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "results", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_528: bool = true;
while { if !__for_first_528 { i = add(&i, &Value::Int(1)); } __for_first_528 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut success: Value = self.safe_bool_k(get_value(&orders, &i), "success", &[]);
if !is_equal(&success, &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" cancelOrders() has failed, check your arguments and parameters".to_string()))));
}
}
}
return self.parse_orders(orders.clone(), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id.clone());
m
});
if !is_equal(&amount, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("size".to_string()), self.amount_to_precision(symbol.clone(), amount.clone()));
}
if !is_equal(&price, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("price".to_string()), self.price_to_precision(symbol.clone(), price.clone()));
}
let mut preview: Value = self.safe_bool2(params.clone(), Value::Str("preview".to_string()), Value::Str("test".to_string()), &[Value::Bool(false)]);
let mut response: Value = Value::Null;
if is_equal(&preview, &Value::Bool(true)) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("preview".to_string()), Value::Str("test".to_string())]), &[]);
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.clone(), &[params.clone()]);
response = self.v3_private_post_brokerage_orders_edit(&[__ws_arg_25]).await;
}
return self.parse_order(response.clone(), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id.clone());
m
});
let __ws_arg_26 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order.clone(), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOrders".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".to_string()), Value::Str("cursor".to_string()), Value::Null, Value::Int(1000)]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&market, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("product_id".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start_date".to_string()), self.iso8601(since.clone()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("end_date".to_string()), self.iso8601(until.clone()));
}
let __ws_arg_27 = self.extend(request.clone(), &[params.clone()]);
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::List(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.clone(), "cursor", &[]);
if is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
add_element_to_object(&mut first, &Value::Str("cursor".to_string()), cursor.clone());
add_element_to_object(&mut orders, &Value::Int(0), first.clone());
}
return self.parse_orders(orders.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_status".to_string(), status.clone());
m
});
if !is_equal(&market, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("product_id".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if is_equal(&limit, &Value::Null) {
limit = Value::Int(100);
}
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start_date".to_string()), self.iso8601(since.clone()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("end_date".to_string()), self.iso8601(until.clone()));
}
let __ws_arg_28 = self.extend(request.clone(), &[params.clone()]);
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::List(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.clone(), "cursor", &[]);
if is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
add_element_to_object(&mut first, &Value::Str("cursor".to_string()), cursor.clone());
add_element_to_object(&mut orders, &Value::Int(0), first.clone());
}
return self.parse_orders(orders.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchOpenOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".to_string()), Value::Str("cursor".to_string()), Value::Null, Value::Int(100)]).await;
}
return self.fetch_orders_by_status(Value::Str("OPEN".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchClosedOrders".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchClosedOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".to_string()), Value::Str("cursor".to_string()), Value::Null, Value::Int(1000)]).await;
}
return self.fetch_orders_by_status(Value::Str("FILLED".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).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".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).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".to_string()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut maxLimit: Value = Value::Int(300);
limit = ternary(is_true(&(is_equal(&limit, &Value::Null))), maxLimit.clone(), 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".to_string()), Value::Str("paginate".to_string()), &[Value::Bool(false)]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".to_string()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), params.clone(), subtract(&maxLimit, &Value::Int(1))]).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(), get_value(&market, &Value::Str("id".to_string())));
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".to_string()), Value::Str("end".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut requestedDuration: Value = multiply(&limit, &duration);
let mut sinceString: Value = Value::Null;
if !is_equal(&since, &Value::Null) {
sinceString = self.number_to_string(self.parse_to_int(divide(&since, &Value::Int(1000))));
} else {
let mut now: Value = to_string_val(&self.seconds());
sinceString = crate::precise::Precise::stringSub(&now, &to_string_val(&requestedDuration));
}
add_element_to_object(&mut request, &Value::Str("start".to_string()), sinceString.clone());
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("end".to_string()), self.number_to_string(self.parse_to_int(divide(&until, &Value::Int(1000)))));
} else {
// 300 candles max
add_element_to_object(&mut request, &Value::Str("end".to_string()), 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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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.clone(), &[params.clone()]);
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.clone(), "candles", &[Value::List(vec![])]);
return self.parse_ohlc_vs(candles.clone(), &[market.clone(), timeframe.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::List(vec![self.safe_timestamp(ohlcv.clone(), Value::Str("start".to_string()), &[]), 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.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), self.number_to_string(self.parse_to_int(divide(&since, &Value::Int(1000)))));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), 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".to_string()), Value::Str("until".to_string()), &[]); until = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("end".to_string()), self.number_to_string(self.parse_to_int(divide(&until, &Value::Int(1000)))));
} else if !is_equal(&since, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchTrades() requires a `until` parameter when you use `since` argument".to_string()))));
}
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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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.clone(), &[params.clone()]);
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.clone(), "trades", &[Value::List(vec![])]);
return self.parse_trades(trades.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchMyTrades".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("cursor".to_string()), Value::Str("cursor".to_string()), Value::Null, Value::Int(250)]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&market, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("product_id".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start_sequence_timestamp".to_string()), self.iso8601(since.clone()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::List(vec![Value::Str("until".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("end_sequence_timestamp".to_string()), self.iso8601(until.clone()));
}
let __ws_arg_33 = self.extend(request.clone(), &[params.clone()]);
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::List(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.clone(), "cursor", &[]);
if is_true(&(!is_equal(&cursor, &Value::Null))) && is_true(&(!is_equal(&cursor, &Value::Str("".to_string())))) {
add_element_to_object(&mut first, &Value::Str("cursor".to_string()), cursor.clone());
add_element_to_object(&mut trades, &Value::Int(0), first.clone());
}
return self.parse_trades(trades.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
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".to_string()), Value::Str("usePrivate".to_string()), &[Value::Bool(false)]); usePrivate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
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.clone(), &[params.clone()]);
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.clone(), "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.clone());
return self.parse_order_book(data.clone(), symbol.clone(), &[timestamp.clone(), Value::Str("bids".to_string()), Value::Str("asks".to_string()), Value::Str("price".to_string()), Value::Str("size".to_string())]);
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 is_equal(&self.markets, &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 !is_equal(&symbols, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("product_ids".to_string()), self.market_ids(&[symbols.clone()]));
}
let __ws_arg_36 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "pricebooks", &[Value::List(vec![])]);
return self.parse_tickers(tickers.clone(), &[symbols.clone()]);
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 = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
self.check_address(&[address.clone()]);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("send".to_string()));
m.insert("to".to_string(), address.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
let mut accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".to_string()), Value::Str("accountId".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
if is_equal(&accountId, &Value::Null) {
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" withdraw() requires an account_id (or accountId) parameter OR a currency code argument".to_string()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&self.id, &Value::Str(" withdraw() could not find account id for ".to_string())), &code)));
}
add_element_to_object(&mut request, &Value::Str("account_id".to_string()), accountId.clone());
} else {
add_element_to_object(&mut request, &Value::Str("account_id".to_string()), accountId.clone());
}
if !is_equal(&tag, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("destination_tag".to_string()), tag.clone());
}
let __ws_arg_37 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data.clone(), &[currency.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Null;
{ let __destr_tmp = self.prepare_account_request_with_currency_code(&[get_value(¤cy, &Value::Str("code".to_string())), Value::Null, params.clone()]).await; request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_38 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "data", &[Value::List(vec![])]);
let mut addressStructures: Value = self.parse_deposit_addresses(data.clone(), &[Value::Null, Value::Bool(false)]);
return self.index_by(addressStructures.clone(), Value::Str("network".to_string()));
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 !is_equal(&addressLabel, &Value::Null) {
let mut splitAddressLabel: Value = split(&addressLabel, &Value::Str(" ".to_string()));
currencyId = self.safe_string(splitAddressLabel.clone(), 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.clone());
m.insert("currency".to_string(), self.safe_currency_code(currencyId.clone(), &[currency.clone()]));
m.insert("network".to_string(), self.network_id_to_code(&[networkId.clone(), code.clone()]));
m.insert("address".to_string(), address.clone());
m.insert("tag".to_string(), self.safe_string_k(addressInfo.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".to_string()), Value::Str("accountId".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
if is_equal(&accountId, &Value::Null) {
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" deposit() requires an account_id (or accountId) parameter OR a currency code argument".to_string()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&self.id, &Value::Str(" deposit() could not find account id for ".to_string())), &code)));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m.insert("currency".to_string(), to_upper(&code));
m.insert("payment_method".to_string(), id.clone());
m.insert("commit".to_string(), Value::Bool(true));
m
});
let __ws_arg_39 = self.extend(request.clone(), &[params.clone()]);
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.clone(), Value::Str("data".to_string()), Value::Str("transfer".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut accountId: Value = self.safe_string2(params.clone(), Value::Str("account_id".to_string()), Value::Str("accountId".to_string()), &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("account_id".to_string()), Value::Str("accountId".to_string())]), &[]);
if is_equal(&accountId, &Value::Null) {
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchDeposit() requires an account_id (or accountId) parameter OR a currency code argument".to_string()))));
}
accountId = self.find_account_id(code.clone(), &[params.clone()]).await;
if is_equal(&accountId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&self.id, &Value::Str(" fetchDeposit() could not find account id for ".to_string())), &code)));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_id".to_string(), accountId.clone());
m.insert("deposit_id".to_string(), id.clone());
m
});
let __ws_arg_40 = self.extend(request.clone(), &[params.clone()]);
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.clone(), Value::Str("data".to_string()), Value::Str("transfer".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(data.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.v3_private_get_brokerage_payment_methods(&[params.clone()]).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.clone(), "payment_methods", &[Value::List(vec![])]);
return self.parse_deposit_method_ids(result.clone(), &[]);
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 is_equal(&self.markets, &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.clone());
m
});
let __ws_arg_41 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "payment_method", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_deposit_method_id(result.clone());
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::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_529: bool = true;
while { if !__for_first_529 { i = add(&i, &Value::Int(1)); } __for_first_529 = false; is_less_than(&i, &get_array_length(&ids)) } {
let __ws_arg_42 = self.parse_deposit_method_id(get_value(&ids, &i));
let mut id: Value = self.extend(__ws_arg_42, &[params.clone()]);
append_to_array(&mut result, id.clone());
}
}
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.clone(), "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 is_equal(&self.markets, &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.clone());
m.insert("to_account".to_string(), toCode.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m
});
let __ws_arg_43 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.v3_private_post_brokerage_convert_quote(&[__ws_arg_43]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data.clone(), &[]);
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 is_equal(&self.markets, &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.clone());
m.insert("from_account".to_string(), fromCode.clone());
m.insert("to_account".to_string(), toCode.clone());
m
});
let __ws_arg_44 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&code, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchConvertTrade() requires a code argument".to_string()))));
}
let mut toCode: Value = self.safe_string_k(params.clone(), "toCode", &[]);
if is_equal(&toCode, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchConvertTrade() requires a toCode parameter".to_string()))));
}
params = self.omit(params.clone(), Value::Str("toCode".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade_id".to_string(), id.clone());
m.insert("from_account".to_string(), code.clone());
m.insert("to_account".to_string(), toCode.clone());
m
});
let __ws_arg_45 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "trade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_conversion(data.clone(), &[]);
Value::Null
}
pub fn parse_conversion(&self, mut conversion: Value, optional_args: &[Value]) -> Value {
let mut fromCurrency = get_arg(optional_args, 0, Value::Null);
let mut toCurrency = get_arg(optional_args, 1, Value::Null);
let mut fromCoin: Value = self.safe_string_k(conversion.clone(), "source_currency", &[]);
let mut fromCode: Value = self.safe_currency_code(fromCoin.clone(), &[fromCurrency.clone()]);
let mut to: Value = self.safe_string_k(conversion.clone(), "target_currency", &[]);
let mut toCode: Value = self.safe_currency_code(to.clone(), &[toCurrency.clone()]);
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.clone(), "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.clone(), "id", &[]));
m.insert("fromCurrency".to_string(), fromCode.clone());
m.insert("fromAmount".to_string(), self.safe_number_k(fromAmountStructure.clone(), "value", &[]));
m.insert("toCurrency".to_string(), toCode.clone());
m.insert("toAmount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
m.insert("fee".to_string(), self.safe_number_k(feeAmountStructure.clone(), "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.clone(), amount.clone(), &[]));
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
}));
m.insert("source_portfolio_uuid".to_string(), fromAccount.clone());
m.insert("target_portfolio_uuid".to_string(), toAccount.clone());
m
});
let __ws_arg_46 = self.extend(request.clone(), &[params.clone()]);
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.clone(), &[currency.clone()]);
add_element_to_object(&mut transfer, &Value::Str("amount".to_string()), amount.clone());
add_element_to_object(&mut transfer, &Value::Str("status".to_string()), Value::Str("ok".to_string()));
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.clone()]);
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.clone());
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.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("client_order_id".to_string()), Value::Str("clientOrderId".to_string()), &[]);
params = self.omit(params.clone(), Value::Str("clientOrderId".to_string()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if is_equal(&clientOrderId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" closePosition() requires a clientOrderId parameter".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("client_order_id".to_string()), clientOrderId.clone());
let __ws_arg_47 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "success_response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(order.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut market: Value = Value::Null;
if !is_equal(&symbols, &Value::Null) {
market = self.market(get_value(&symbols, &Value::Int(0)));
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchPositions".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut response: Value = Value::Null;
if is_equal(&type_var, &Value::Str("future".to_string())) {
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".to_string()), Value::Str("portfolio".to_string()), &[]); portfolio = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&portfolio, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &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()".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("portfolio_uuid".to_string(), portfolio.clone());
m
});
let __ws_arg_48 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_intx_positions_portfolio_uuid(&[__ws_arg_48]).await;
}
let mut positions: Value = self.safe_list_k(response.clone(), "positions", &[Value::List(vec![])]);
return self.parse_positions(positions.clone(), &[symbols.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut response: Value = Value::Null;
if is_equal(&get_value(&market, &Value::Str("future".to_string())), &Value::Bool(true)) {
let mut productId: Value = self.safe_string_k(market.clone(), "product_id", &[]);
if is_equal(&productId, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchPosition() requires a \"product_id\" in params".to_string()))));
}
let mut futureRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_id".to_string(), productId.clone());
m
});
let __ws_arg_49 = self.extend(futureRequest.clone(), &[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".to_string()), Value::Str("portfolio".to_string()), &[]); portfolio = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&portfolio, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &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()".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("portfolio_uuid".to_string(), portfolio.clone());
m
});
let __ws_arg_50 = self.extend(request.clone(), &[params.clone()]);
response = self.v3_private_get_brokerage_intx_positions_portfolio_uuid_symbol(&[__ws_arg_50]).await;
}
let mut position: Value = self.safe_dict_k(response.clone(), "position", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_position(position.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "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("".to_string())]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut rawMargin: Value = self.safe_string_k(position.clone(), "margin_type", &[]);
let mut marginMode: Value = Value::Null;
if !is_equal(&rawMargin, &Value::Null) {
marginMode = ternary(is_true(&(is_equal(&rawMargin, &Value::Str("MARGIN_TYPE_CROSS".to_string())))), Value::Str("cross".to_string()), Value::Str("isolated".to_string()));
}
let mut notionalObject: Value = self.safe_dict_k(position.clone(), "position_notional", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionSide: Value = self.safe_string_k(position.clone(), "position_side", &[]);
let mut side: Value = ternary(is_true(&(is_equal(&positionSide, &Value::Str("POSITION_SIDE_LONG".to_string())))), Value::Str("long".to_string()), Value::Str("short".to_string()));
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.clone(), "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.clone(), &[market.clone()]));
m.insert("notional".to_string(), self.safe_number_k(notionalObject.clone(), "value", &[]));
m.insert("marginMode".to_string(), marginMode.clone());
m.insert("liquidationPrice".to_string(), liquidationPrice.clone());
m.insert("entryPrice".to_string(), self.safe_number_k(vwapObject.clone(), "value", &[]));
m.insert("unrealizedPnl".to_string(), self.safe_number_k(unrealizedPNLObject.clone(), "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(), get_value(&market, &Value::Str("contractSize".to_string())));
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
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.clone(), "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.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut type_var: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchTradingFees".to_string()), &[Value::Null, params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isSpot: bool = is_equal(&type_var, &Value::Str("spot".to_string()));
let mut productType: Value = ternary(is_true(&isSpot), Value::Str("SPOT".to_string()), Value::Str("FUTURE".to_string()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("product_type".to_string(), productType.clone());
m
});
let __ws_arg_51 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "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_530: bool = true;
while { if !__for_first_530 { i = add(&i, &Value::Int(1)); } __for_first_530 = false; is_less_than(&i, &get_array_length(&self.symbols)) } {
let mut symbol: Value = get_value(&self.symbols, &i);
let mut market: Value = self.market(symbol.clone());
if is_true(&(is_true(&isSpot) && is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))))) || is_true(&(!is_true(&isSpot) && is_true(&(!is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))))) {
add_element_to_object(&mut result, &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 is_equal(&self.markets, &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.clone());
m
});
let __ws_arg_52 = self.extend(request.clone(), &[params.clone()]);
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.clone());
return result;
Value::Null
}
pub fn parse_portfolio_details(&self, mut portfolioData: Value) -> Value {
let mut breakdown: Value = get_value(&portfolioData, &Value::Str("breakdown".to_string()));
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".to_string())]);
let mut portfolioUuid: Value = self.safe_string_k(portfolioInfo.clone(), "uuid", &[Value::Str("".to_string())]);
let mut spotPositions: Value = self.safe_list_k(breakdown.clone(), "spot_positions", &[Value::List(vec![])]);
let mut parsedPositions: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_531: bool = true;
while { if !__for_first_531 { i = add(&i, &Value::Int(1)); } __for_first_531 = false; is_less_than(&i, &get_array_length(&spotPositions)) } {
let mut position: Value = get_value(&spotPositions, &i);
let mut position: Value = get_value(&spotPositions, &i);
let mut currencyCode: Value = self.safe_string_k(position.clone(), "asset", &[Value::Str("Unknown".to_string())]);
let mut availableBalanceStr: Value = self.safe_string_k(position.clone(), "available_to_trade_fiat", &[Value::Str("0".to_string())]);
let mut availableBalance: Value = self.parse_number(availableBalanceStr.clone(), &[]);
let mut totalBalanceFiatStr: Value = self.safe_string_k(position.clone(), "total_balance_fiat", &[Value::Str("0".to_string())]);
let mut totalBalanceFiat: Value = self.parse_number(totalBalanceFiatStr.clone(), &[]);
let mut holdAmount: Value = subtract(&totalBalanceFiat, &availableBalance);
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".to_string())]);
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".to_string())]);
let mut positionData: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currencyCode.clone());
m.insert("available_balance".to_string(), availableBalance.clone());
m.insert("hold_amount".to_string(), ternary(is_greater_than(&holdAmount, &Value::Int(0)), holdAmount.clone(), 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("".to_string())]));
m.insert("total_balance_fiat".to_string(), totalBalanceFiat.clone());
m.insert("total_balance_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "total_balance_crypto", &[Value::Str("0".to_string())]), &[]));
m.insert("available_to_trade_fiat".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_fiat", &[Value::Str("0".to_string())]), &[]));
m.insert("available_to_trade_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_crypto", &[Value::Str("0".to_string())]), &[]));
m.insert("available_to_transfer_fiat".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_transfer_fiat", &[Value::Str("0".to_string())]), &[]));
m.insert("available_to_transfer_crypto".to_string(), self.parse_number(self.safe_string_k(position.clone(), "available_to_trade_crypto", &[Value::Str("0".to_string())]), &[]));
m.insert("allocation".to_string(), self.parse_number(self.safe_string_k(position.clone(), "allocation", &[Value::Str("0".to_string())]), &[]));
m.insert("cost_basis".to_string(), self.parse_number(costBasisStr.clone(), &[]));
m.insert("cost_basis_currency".to_string(), self.safe_string_k(costBasisDict.clone(), "currency", &[Value::Str("USD".to_string())]));
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.clone(), &[]));
m.insert("average_entry_price_currency".to_string(), self.safe_string_k(averageEntryPriceDict.clone(), "currency", &[Value::Str("USD".to_string())]));
m.insert("asset_uuid".to_string(), self.safe_string_k(position.clone(), "asset_uuid", &[Value::Str("".to_string())]));
m.insert("unrealized_pnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealized_pnl", &[Value::Str("0".to_string())]), &[]));
m.insert("asset_color".to_string(), self.safe_string_k(position.clone(), "asset_color", &[Value::Str("".to_string())]));
m.insert("account_type".to_string(), self.safe_string_k(position.clone(), "account_type", &[Value::Str("".to_string())]));
m
});
append_to_array(&mut parsedPositions, positionData.clone());
}
}
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 !is_equal(&url, &Value::Null) {
uri = add(&add(&method, &Value::Str(" ".to_string())), &replace_str(&url, &Value::Str("https://".to_string()), &Value::Str("".to_string())));
let mut quesPos: Value = get_index_of(&uri, &Value::Str("?".to_string()));
// 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 is_greater_than(&quesPos, &Value::Int(0)) {
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 = ternary(is_true(&useEddsa), Value::Str("cdp_service".to_string()), Value::Str("retail_rest_api_proxy".to_string()));
let mut iss: Value = ternary(is_true(&useEddsa), Value::Str("cdp".to_string()), Value::Str("coinbase-cloud".to_string()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("aud".to_string(), Value::List(vec![aud.clone()]));
m.insert("iss".to_string(), iss.clone());
m.insert("nbf".to_string(), seconds.clone());
m.insert("exp".to_string(), add(&seconds, &Value::Int(120)));
m.insert("sub".to_string(), self.apiKey.clone());
m.insert("iat".to_string(), seconds.clone());
m
});
if !is_equal(&uri, &Value::Null) {
if !is_true(&useEddsa) {
add_element_to_object(&mut request, &Value::Str("uri".to_string()), uri.clone());
} else {
add_element_to_object(&mut request, &Value::Str("uris".to_string()), Value::List(vec![uri.clone()]));
}
}
if is_true(&useEddsa) {
let mut byteArray: Value = self.base64_to_binary(self.secret.clone(), &[]);
let mut seed: Value = self.array_slice(byteArray.clone(), Value::Int(0), &[Value::Int(32)]);
return jwt(request.clone(), seed.clone(), Value::Str("sha256".to_string()), 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".to_string()));
m
}));
} else {
return jwt(request.clone(), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), 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("ES256".to_string()));
m
}));
}
Value::Null
}
pub fn nonce(&self) -> Value {
return subtract(&self.milliseconds(), &get_value(&self.options, &Value::Str("timeDifference".to_string())));
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::List(vec![]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut version: Value = get_value(&api, &Value::Int(0));
let mut signed: bool = is_equal(&get_value(&api, &Value::Int(1)), &Value::Str("private".to_string()));
let mut isV3: Value = Value::Bool(is_equal(&version, &Value::Str("v3".to_string())));
let mut pathPart: Value = ternary(is_true(&(isV3)), Value::Str("api/v3".to_string()), Value::Str("v2".to_string()));
let mut fullPath: Value = add(&add(&add(&Value::Str("/".to_string()), &pathPart), &Value::Str("/".to_string())), &self.implode_params(path.clone(), params.clone()));
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut savedPath: Value = fullPath.clone();
if is_equal(&method, &Value::Str("GET".to_string())) {
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
fullPath = add(&fullPath, &add(&Value::Str("?".to_string()), &self.urlencode_with_array_repeat(query.clone())));
}
}
let mut url: Value = add(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("rest".to_string())), &fullPath);
if is_true(&signed) {
let mut authorization: Value = self.safe_string_k(self.headers.clone(), "Authorization", &[]);
let mut authorizationString: Value = Value::Null;
if !is_equal(&authorization, &Value::Null) {
authorizationString = authorization.clone();
} else if is_true(&(!is_equal(&self.token, &Value::Str("".to_string())))) && !is_true(&self.check_required_credentials(&[Value::Bool(false)])) {
authorizationString = add(&Value::Str("Bearer ".to_string()), &self.token);
} else {
self.check_required_credentials(&[]);
let mut seconds: Value = self.seconds();
let mut payload: Value = Value::Str("".to_string());
if !is_equal(&method, &Value::Str("GET".to_string())) {
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
body = self.json(query.clone());
payload = body.clone();
}
} else {
if !is_true(&isV3) {
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
payload = add(&payload, &add(&Value::Str("?".to_string()), &self.urlencode(query.clone(), &[])));
}
}
}
// 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 = is_true(&(is_greater_than_or_equal(&get_index_of(&self.apiKey, &Value::Str("organizations/".to_string())), &Value::Int(0)))) || is_true(&(Value::Bool(starts_with(&self.secret, &Value::Str("-----BEGIN".to_string())))));
// 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(is_equal(&get_array_length(&self.secret), &Value::Int(88)) || is_true(&self.safe_bool_k(self.options.clone(), "v2CloudAPiKey", &[Value::Bool(false)])) || is_true(&Value::Bool(ends_with(&self.secret, &Value::Str("=".to_string())))));
if is_true(&isCloudAPiKey) || is_true(&isV2CloudAPiKey) {
if is_true(&isCloudAPiKey) && is_true(&Value::Bool(starts_with(&self.apiKey, &Value::Str("-----BEGIN".to_string())))) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" apiKey should contain the name (eg: organizations/3b910e93....) and not the public key".to_string()))));
}
// // 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.clone(), &[method.clone(), url.clone(), isV2CloudAPiKey.clone()]);
// const token = jwt (request, this.encode (this.secret), sha256, false, { 'kid': this.apiKey, 'nonce': nonce, 'alg': 'ES256' });
authorizationString = add(&Value::Str("Bearer ".to_string()), &token);
} else {
let mut nonce: Value = self.nonce();
let mut timestamp: Value = self.parse_to_int(divide(&nonce, &Value::Int(1000)));
let mut timestampString: Value = to_string_val(×tamp);
let mut auth: Value = add(&add(&add(×tampString, &method), &savedPath), &payload);
let mut signature: Value = self.hmac(self.encode(auth.clone()), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), &[]);
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.clone());
m.insert("CB-ACCESS-TIMESTAMP".to_string(), timestampString.clone());
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
});
}
}
if !is_equal(&authorizationString, &Value::Null) {
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Authorization".to_string(), authorizationString.clone());
m.insert("Content-Type".to_string(), Value::Str("application/json".to_string()));
m
});
if !is_equal(&method, &Value::Str("GET".to_string())) {
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
body = self.json(query.clone());
}
}
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
//
// {"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 !is_equal(&errorCode, &Value::Null) {
let mut errorMessage: Value = self.safe_string2(response.clone(), Value::Str("error_description".to_string()), Value::Str("error".to_string()), &[]);
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), errorMessage.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
let mut errorResponse: Value = self.safe_dict_k(response.clone(), "error_response", &[]);
if !is_equal(&errorResponse, &Value::Null) {
let mut errorMessageInner: Value = self.safe_string2(errorResponse.clone(), Value::Str("preview_failure_reason".to_string()), Value::Str("preview_failure_reason".to_string()), &[]);
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorMessageInner.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), errorMessageInner.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
let mut errors: Value = self.safe_list_k(response.clone(), "errors", &[]);
if !is_equal(&errors, &Value::Null) {
if is_true(&Value::Bool(is_array(&errors))) {
let mut numErrors: Value = get_array_length(&errors);
if is_greater_than(&numErrors, &Value::Int(0)) {
errorCode = self.safe_string(get_value(&errors, &Value::Int(0)), Value::Str("id".to_string()), &[]);
let mut errorMessage: Value = self.safe_string(get_value(&errors, &Value::Int(0)), Value::Str("message".to_string()), &[]);
if !is_equal(&errorCode, &Value::Null) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorCode.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), errorMessage.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
}
}
let mut advancedTrade: Value = get_value(&self.options, &Value::Str("advanced".to_string()));
if !is_true(&(Value::Bool(in_op(&response, &Value::Str("data".to_string()))))) && is_true(&(!is_equal(&advancedTrade, &Value::Bool(true)))) {
panic!("{}", crate::exchange_errors::exchange_error(add(&add(&self.id, &Value::Str(" failed due to a malformed response ".to_string())), &self.json(response.clone()))));
}
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 is_equal(&self.markets, &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.clone(), &[params.clone()]);
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.clone(), "data", &[Value::List(vec![])]);
return self.parse_deposit_addresses(data.clone(), &[codes.clone(), Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
}