// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct AlpacaCore {
pub exchange: crate::exchange::Exchange,
}
impl AlpacaCore {
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 = AlpacaCore::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 AlpacaCore {
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_balance(self, response)
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for AlpacaCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_market_order_with_cost" => self.create_market_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"create_market_sell_order_with_cost" => self.create_market_sell_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transactions_helper" => self.fetch_transactions_helper(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)).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for AlpacaCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for AlpacaCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl AlpacaCore {
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("alpaca".into()));
m.insert("name".to_string(), Value::Str("Alpaca".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("rateLimit".to_string(), Value::Int(333));
m.insert("hostname".to_string(), Value::Str("alpaca.markets".into()));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/e9476df8-a450-4c3e-ab9a-1a7794219e1b".into()));
m.insert("www".to_string(), Value::Str("https://alpaca.markets".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("broker".to_string(), Value::Str("https://broker-api.{hostname}".into()));
m.insert("trader".to_string(), Value::Str("https://api.{hostname}".into()));
m.insert("market".to_string(), Value::Str("https://data.{hostname}".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("broker".to_string(), Value::Str("https://broker-api.sandbox.{hostname}".into()));
m.insert("trader".to_string(), Value::Str("https://paper-api.{hostname}".into()));
m.insert("market".to_string(), Value::Str("https://data.{hostname}".into()));
m
}));
m.insert("doc".to_string(), Value::Str("https://alpaca.markets/docs/".into()));
m.insert("fees".to_string(), Value::Str("https://docs.alpaca.markets/docs/crypto-fees".into()));
m
}));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Bool(false));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrder".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(true));
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("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Bool(false));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
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("fetchL1OrderBook".to_string(), Value::Bool(true));
m.insert("fetchL2OrderBook".to_string(), Value::Bool(false));
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("fetchMyLiquidations".to_string(), Value::Bool(false));
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("fetchOpenOrder".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("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositionHistory".to_string(), Value::Bool(false));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(false));
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("fetchStatus".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::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransactionFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(false));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(false));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(false));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("broker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("v1/accounts/{account_id}/tokenization/requests".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/accounts/{account_id}/tokenization/requests/{tokenization_request_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/accounts/{account_id}/tokenization/requests:by_client_request_id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/accounts/{account_id}/tokenization/requests:by_issuer_request_id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/fpsl/analytics/{account_id}/loans".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/ipos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/ipos/{offering_reference}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/wallets/travel-rule/vasps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/acats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/acats/contrabrokers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/acats/{account_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/acats/{account_id}/{acats_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/acats/{account_id}/{acats_id}/assets".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("v1beta1/acats/{account_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("patch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1/accounts/{account_id}/wallets/whitelists/{whitelisted_address_id}/travel-rule-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("trader".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("v2/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/positions/{symbol_or_asset_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/account/portfolio/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists/{watchlist_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists:by_name".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/account/configurations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/account/activities".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/account/activities/{activity_type}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/calendar".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/clock".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/assets/{symbol_or_asset_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/corporate_actions/announcements/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/corporate_actions/announcements".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/wallets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/wallets/transfers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/locates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/locates/{locate_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/locates/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/tokenization/requests".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/tokenization/requests/{tokenization_request_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/tokenization/requests:by_client_request_id".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/wallets/travel-rule/vasps".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("v2/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists/{watchlist_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists:by_name".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/wallets/transfers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/locates".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("v2/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists/{watchlist_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists:by_name".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("patch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v2/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/account/configurations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/wallets/whitelists/{whitelisted_address_id}/travel-rule-info".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("v2/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/orders/{order_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/positions/{symbol_or_asset_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists/{watchlist_id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists:by_name".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/watchlists/{watchlist_id}/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("market".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("v1beta3/crypto/{loc}/bars".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/latest/bars".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/latest/orderbooks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/latest/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/latest/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/snapshots".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta3/crypto/{loc}/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("v1beta1/corporate-actions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/fixed_income/latest/prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/fixed_income/latest/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/forex/latest/rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/forex/rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/logos/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/news".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/screener/stocks/most-actives".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1beta1/screener/{market_type}/movers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/auctions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/bars".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/bars/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/meta/conditions/{ticktype}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/meta/exchanges".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/quotes/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/snapshots".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/trades/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/auctions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/bars".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/bars/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/quotes/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/snapshot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v2/stocks/{symbol}/trades/latest".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("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1min".into()));
m.insert("3m".to_string(), Value::Str("3min".into()));
m.insert("5m".to_string(), Value::Str("5min".into()));
m.insert("15m".to_string(), Value::Str("15min".into()));
m.insert("30m".to_string(), Value::Str("30min".into()));
m.insert("1h".to_string(), Value::Str("1H".into()));
m.insert("2h".to_string(), Value::Str("2H".into()));
m.insert("4h".to_string(), Value::Str("4H".into()));
m.insert("6h".to_string(), Value::Str("6H".into()));
m.insert("8h".to_string(), Value::Str("8H".into()));
m.insert("12h".to_string(), Value::Str("12H".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("3d".to_string(), Value::Str("3D".into()));
m.insert("1w".to_string(), Value::Str("1W".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
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("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0015".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0025".into()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.0025".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0022".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.0020".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0018".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.0015".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.0013".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.0012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.0015".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0008".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.0005".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("25000000".into()), &[]), self.parse_number(Value::Str("0.0002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.0002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0.00".into()), &[])])]));
m
}));
m
}));
m
}));
m.insert("headers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("APCA-PARTNER-ID".to_string(), Value::Str("ccxt".into()));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("minCostUSD".to_string(), Value::Int(10));
m.insert("defaultExchange".to_string(), Value::Str("CBSE".into()));
m.insert("exchanges".to_string(), Value::from(vec![Value::Str("CBSE".into()), Value::Str("FTX".into()), Value::Str("GNSS".into()), Value::Str("ERSX".into())]));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeInForce".to_string(), Value::Str("gtc".into()));
m
}));
m.insert("clientOrderId".to_string(), Value::Str("ccxt_{id}".into()));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("price".to_string(), Value::Bool(true));
m
}));
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(false));
m.insert("PO".to_string(), Value::Bool(false));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
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(100));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(500));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(1000));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("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("forbidden.".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("40410000".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("40010001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("40110000".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("42210000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("42910000".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Invalid format for parameter".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("Invalid symbol".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("cost basis must be".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("insufficient balance for".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("orders are rejected by user request".to_string(), Value::Str("PermissionDenied".into()).clone());
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name alpaca#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.trader_private_get_v2_clock(&[params]).await;
//
// {
// timestamp: '2023-11-22T08:07:57.654738097-05:00',
// is_open: false,
// next_open: '2023-11-22T09:30:00-05:00',
// next_close: '2023-11-22T16:00:00-05:00'
// }
//
let mut timestamp: Value = self.safe_string_k(response, "timestamp", &[]);
if (timestamp == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTime() missing timestamp".into()))));
}
let mut localTime: Value = timestamp.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = __l.min(23); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
if (timestamp == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTime() missing timestamp".into()))));
}
let mut jetlagStrStart: Value = (match (&(Value::Int(timestamp.len() as i64)), &(Value::Int(6))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if (timestamp == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTime() missing timestamp".into()))));
}
let mut jetlagStrEnd: Value = (match (&(Value::Int(timestamp.len() as i64)), &(Value::Int(3))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if (timestamp == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchTime() missing timestamp".into()))));
}
let mut jetlag: Value = slice(×tamp, &jetlagStrStart, &jetlagStrEnd);
let mut iso: Value = (match (&(self.parse_to_int(self.parse8601(localTime))), &((match (&((match (&(self.parse_to_numeric(jetlag)), &(Value::Int(3600))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
return iso;
Value::Null
}
/*
* @method
* @name alpaca#fetchMarkets
* @description retrieves data on all markets for alpaca
* @see https://docs.alpaca.markets/reference/get-v2-assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset_class".to_string(), Value::Str("crypto".into()));
m.insert("status".to_string(), Value::Str("active".into()));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut assets: Value = self.trader_private_get_v2_assets(&[__ws_arg_0]).await;
return self.parse_markets(assets);
Value::Null
}
pub fn parse_market(&self, mut asset: Value) -> Value {
//
// {
// "id": "c150e086-1e75-44e6-9c2c-093bb1e93139",
// "class": "crypto",
// "exchange": "CRYPTO",
// "symbol": "BTC/USDT",
// "name": "Bitcoin / USD Tether",
// "status": "active",
// "tradable": true,
// "marginable": false,
// "maintenance_margin_requirement": 101,
// "shortable": false,
// "easy_to_borrow": false,
// "fractionable": true,
// "attributes": [],
// "min_order_size": "0.000026873",
// "min_trade_increment": "0.000000001",
// "price_increment": "1"
// }
//
let mut marketId: Value = self.safe_string_k(asset.clone(), "symbol", &[]);
if (marketId == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseMarket() missing marketId".into()))));
}
let mut parts: Value = split(&marketId, &Value::Str("/".into()));
let mut assetClass: Option<String> = self.safe_string_k(asset.clone(), "class", &[]).as_str().map(str::to_owned);
let mut baseId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut quoteId: Value = self.safe_string(parts, Value::Int(1), &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
// Us equity markets do not include quote in symbol.
// We can safely coerce us_equity quote to USD
if (quote == Value::Null) && (assetClass.as_deref() == Some("us_equity")) {
quote = Value::Str("USD".into());
}
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut status: Option<String> = self.safe_string_k(asset.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(status.as_deref() == Some("active")));
let mut minAmount: Value = self.safe_number_k(asset.clone(), "min_order_size", &[]);
let mut amount: Value = self.safe_number_k(asset.clone(), "min_trade_increment", &[]);
let mut price: Value = self.safe_number_k(asset.clone(), "price_increment", &[]);
let mut minCost: Value = Value::Null;
if (assetClass.as_deref() == Some("crypto")) && (quote.as_str() == Some("USD")) {
// alpaca rejects USD-quoted crypto buy orders below 10 USD notional: {"code":40310000,"message":"cost basis must be >= minimal amount of order 10"}
// USDT-, USDC- and BTC-quoted pairs accept smaller orders, and sell orders are not floored — verified live 2026-08-25
minCost = self.safe_number_k(self.options.clone(), "minCostUSD", &[self.parse_number(Value::Str("10".into()), &[])]);
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), Value::Bool(true));
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(), active);
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(), amount);
m.insert("price".to_string(), price);
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(), minAmount);
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(), minCost);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), asset);
m
})]);
Value::Null
}
/*
* @method
* @name alpaca#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.alpaca.markets/reference/cryptotrades
* @see https://docs.alpaca.markets/reference/cryptolatesttrades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.loc] crypto location, default: us
* @param {string} [params.method] method, default: marketPublicGetV1beta3CryptoLocTrades
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[Value::Str("marketPublicGetV1beta3CryptoLocTrades".into())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), marketId.clone());
m.insert("loc".to_string(), loc);
m
});
params = self.omit(params.clone(), Value::from(vec![Value::Str("loc".into()), Value::Str("method".into())]), &[]);
let mut symbolTrades: Value = Value::Null;
if (method.as_str() == Some("marketPublicGetV1beta3CryptoLocTrades")) {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), self.iso8601(since.clone())); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_trades(&[__ws_arg_1]).await;
//
// {
// "next_page_token": null,
// "trades": {
// "BTC/USD": [
// {
// "i": 36440704,
// "p": 22625,
// "s": 0.0001,
// "t": "2022-07-21T11:47:31.073391Z",
// "tks": "B"
// }
// ]
// }
// }
//
let mut trades: Value = self.safe_dict_k(response.clone(), "trades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
symbolTrades = self.safe_list(trades.clone(), marketId.clone(), &[Value::from(vec![])]);
} else if (method.as_str() == Some("marketPublicGetV1beta3CryptoLocLatestTrades")) {
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_latest_trades(&[__ws_arg_2]).await;
//
// {
// "trades": {
// "BTC/USD": {
// "i": 36440704,
// "p": 22625,
// "s": 0.0001,
// "t": "2022-07-21T11:47:31.073391Z",
// "tks": "B"
// }
// }
// }
//
let mut trades: Value = self.safe_dict_k(response, "trades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbolTrade: Value = self.safe_dict(trades, marketId, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
symbolTrades = Value::from(vec![symbolTrade]);
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() does not support ".into())).into()), method).into()), Value::Str(", marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported".into()))));
}
let mut symbolTradesList: Value = Value::from(vec![]);
if (symbolTrades != Value::Null) {
symbolTradesList = symbolTrades;
}
return self.parse_trades(symbolTradesList, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name alpaca#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.alpaca.markets/reference/cryptolatestorderbooks
* @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 {string} [params.loc] crypto location, default: us
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut id: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".into())]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), id.clone());
m.insert("loc".to_string(), loc);
m
});
let __ws_arg_3 = self.extend(request, &[params]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_latest_orderbooks(&[__ws_arg_3]).await;
//
// {
// "orderbooks":{
// "BTC/USD":{
// "a":[
// {
// "p":22208,
// "s":0.0051
// },
// {
// "p":22209,
// "s":0.1123
// },
// {
// "p":22210,
// "s":0.2465
// }
// ],
// "b":[
// {
// "p":22203,
// "s":0.395
// },
// {
// "p":22202,
// "s":0.2465
// },
// {
// "p":22201,
// "s":0.6455
// }
// ],
// "t":"2022-07-19T13:41:55.13210112Z"
// }
// }
// }
//
let mut orderbooks: Value = self.safe_dict_k(response, "orderbooks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrderbook: Value = self.safe_dict(orderbooks, id, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(rawOrderbook.clone(), "t", &[]));
return self.parse_order_book(rawOrderbook, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp, Value::Str("b".into()), Value::Str("a".into()), Value::Str("p".into()), Value::Str("s".into())]);
Value::Null
}
/*
* @method
* @name alpaca#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.alpaca.markets/reference/cryptobars
* @see https://docs.alpaca.markets/reference/cryptolatestbars
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @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)
* @param {int} [params.paginationCalls] the maximum number of requests while following next_page_token, default 10 — when the cap is reached the result is silently truncated to the pages already fetched, so raise it for long ranges, 10 requests cover roughly 30 days of 1h candles
* @param {string} [params.loc] crypto location, default: us
* @param {string} [params.method] method, default: marketPublicGetV1beta3CryptoLocBars
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketId: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[Value::Str("marketPublicGetV1beta3CryptoLocBars".into())]);
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut paginationCalls: Value = Value::Int(10);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".into()), Value::Str("paginationCalls".into()), &[Value::Int(10)]); paginationCalls = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), marketId.clone());
m.insert("loc".to_string(), loc);
m
});
params = self.omit(params.clone(), Value::from(vec![Value::Str("loc".into()), Value::Str("method".into())]), &[]);
let mut ohlcvs: Value = Value::Null;
if (method.as_str() == Some("marketPublicGetV1beta3CryptoLocBars")) {
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), self.iso8601(since.clone())); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), self.iso8601(until)); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeframe".into(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()])); }
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_bars(&[__ws_arg_4]).await;
//
// {
// "bars": {
// "BTC/USD": [
// {
// "c": 22887,
// "h": 22888,
// "l": 22873,
// "n": 11,
// "o": 22883,
// "t": "2022-07-21T05:00:00Z",
// "v": 1.1138,
// "vw": 22883.0155324116
// },
// {
// "c": 22895,
// "h": 22895,
// "l": 22884,
// "n": 6,
// "o": 22884,
// "t": "2022-07-21T05:01:00Z",
// "v": 0.001,
// "vw": 22889.5
// }
// ]
// },
// "next_page_token": "QlRDL1VTRHxNfDIwMjItMDctMjFUMDU6MDE6MDAuMDAwMDAwMDAwWg=="
// }
//
let mut bars: Value = self.safe_dict_k(response.clone(), "bars", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
ohlcvs = self.safe_list(bars.clone(), marketId.clone(), &[Value::from(vec![])]);
if is_true(&paginate) {
// the endpoint answers with a server-sized page plus a next_page_token regardless of the requested limit
let mut pageToken: Value = self.safe_string_k(response.clone(), "next_page_token", &[]);
{
let mut i: Value = Value::Int(1);
let mut __for_first_212: bool = true;
while { if !__for_first_212 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_212 = false; i.as_f64().unwrap_or(f64::NAN) < paginationCalls.as_f64().unwrap_or(f64::NAN) } {
let mut ohlcvsLength: f64 = ((ohlcvs.len() as i64) as f64);
if (pageToken == Value::Null) || ((limit != Value::Null) && (ohlcvsLength >= limit.as_f64().unwrap_or(f64::NAN))) {
break;
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_token".into(), pageToken.clone()); }
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
response = self.market_public_get_v1beta3_crypto_loc_bars(&[__ws_arg_5]).await;
bars = self.safe_dict_k(response.clone(), "bars", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut page: Value = self.safe_list(bars.clone(), marketId.clone(), &[Value::from(vec![])]);
let mut pageLength: f64 = ((page.len() as i64) as f64);
if (pageLength == 0.0) {
break;
}
ohlcvs = self.array_concat(ohlcvs.clone(), page);
pageToken = self.safe_string_k(response.clone(), "next_page_token", &[]);
}
}
}
} else if (method.as_str() == Some("marketPublicGetV1beta3CryptoLocLatestBars")) {
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_latest_bars(&[__ws_arg_6]).await;
//
// {
// "bars": {
// "BTC/USD": {
// "c": 22887,
// "h": 22888,
// "l": 22873,
// "n": 11,
// "o": 22883,
// "t": "2022-07-21T05:00:00Z",
// "v": 1.1138,
// "vw": 22883.0155324116
// }
// }
// }
//
let mut bars: Value = self.safe_dict_k(response, "bars", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bar: Value = self.safe_dict(bars, marketId, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
ohlcvs = Value::from(vec![bar]);
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() does not support ".into())).into()), method).into()), Value::Str(", marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported".into()))));
}
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "c":22895,
// "h":22895,
// "l":22884,
// "n":6,
// "o":22884,
// "t":"2022-07-21T05:01:00Z",
// "v":0.001,
// "vw":22889.5
// }
//
let mut datetime: Value = self.safe_string_k(ohlcv.clone(), "t", &[]);
let mut timestamp: Value = self.parse8601(datetime);
return Value::from(vec![timestamp, self.safe_number_k(ohlcv.clone(), "o", &[]), self.safe_number_k(ohlcv.clone(), "h", &[]), self.safe_number_k(ohlcv.clone(), "l", &[]), self.safe_number_k(ohlcv.clone(), "c", &[]), self.safe_number_k(ohlcv, "v", &[])]);
Value::Null
}
/*
* @method
* @name alpaca#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.alpaca.markets/reference/cryptosnapshots-1
* @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 {string} [params.loc] crypto location, default: us
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.symbol(symbol.clone());
let mut tickers: Value = self.fetch_tickers(&[Value::from(vec![symbol.clone()]), params]).await;
return self.safe_dict(tickers, symbol, &[]);
Value::Null
}
/*
* @method
* @name alpaca#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.alpaca.markets/reference/cryptosnapshots-1
* @param {string[]} [symbols] unified symbols of the markets to fetch tickers for, defaults to all markets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.loc] crypto location, default: us
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbols == Value::Null) {
// every listed market is a crypto market because fetchMarkets requests asset_class=crypto, so default to all of them
let mut allSymbols: Value = self.sort(self.symbols.clone(), &[]); // symbol iteration order differs per language
symbols = allSymbols;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".into())]);
let mut ids: Value = self.market_ids(&[symbols.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), join(&ids, &Value::Str(",".into())));
m.insert("loc".to_string(), loc);
m
});
params = self.omit(params.clone(), Value::Str("loc".into()), &[]);
let __ws_arg_7 = self.extend(request, &[params]);
let mut response: Value = self.market_public_get_v1beta3_crypto_loc_snapshots(&[__ws_arg_7]).await;
//
// {
// "snapshots": {
// "BTC/USD": {
// "dailyBar": {
// "c": 69403.554,
// "h": 69609.6515,
// "l": 69013.26,
// "n": 9,
// "o": 69536.7,
// "t": "2024-11-01T05:00:00Z",
// "v": 0.210809181,
// "vw": 69327.655393908
// },
// "latestQuote": {
// "ap": 69424.19,
// "as": 0.68149,
// "bp": 69366.086,
// "bs": 0.68312,
// "t": "2024-11-01T08:31:41.880246926Z"
// },
// "latestTrade": {
// "i": 5272941104897543146,
// "p": 69416.9,
// "s": 0.014017324,
// "t": "2024-11-01T08:14:28.245088803Z",
// "tks": "B"
// },
// "minuteBar": {
// "c": 69403.554,
// "h": 69403.554,
// "l": 69399.125,
// "n": 0,
// "o": 69399.125,
// "t": "2024-11-01T08:30:00Z",
// "v": 0,
// "vw": 0
// },
// "prevDailyBar": {
// "c": 69515.1415,
// "h": 72668.837,
// "l": 68796.85,
// "n": 129,
// "o": 72258.9,
// "t": "2024-10-31T05:00:00Z",
// "v": 2.217683307,
// "vw": 70782.6811608144
// }
// },
// }
// }
//
let mut results: Value = Value::from(vec![]);
let mut snapshots: Value = self.safe_dict_k(response, "snapshots", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketIds: Value = object_keys(&snapshots);
{
let mut i: Value = Value::Int(0);
let mut __for_first_213: bool = true;
while { if !__for_first_213 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_213 = false; i.as_f64().unwrap_or(f64::NAN) < ((marketIds.len() as i64) as f64) } {
let mut marketId: Value = marketIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut entry: Value = self.safe_dict(snapshots.clone(), marketId, &[]);
let mut dailyBar: Value = self.safe_dict_k(entry.clone(), "dailyBar", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut prevDailyBar: Value = self.safe_dict_k(entry.clone(), "prevDailyBar", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut latestQuote: Value = self.safe_dict_k(entry.clone(), "latestQuote", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut latestTrade: Value = self.safe_dict_k(entry.clone(), "latestTrade", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut datetime: Value = self.safe_string_k(latestQuote.clone(), "t", &[]);
let mut ticker: Value = self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime);
m.insert("high".to_string(), self.safe_string_k(dailyBar.clone(), "h", &[]));
m.insert("low".to_string(), self.safe_string_k(dailyBar.clone(), "l", &[]));
m.insert("bid".to_string(), self.safe_string_k(latestQuote.clone(), "bp", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(latestQuote.clone(), "bs", &[]));
m.insert("ask".to_string(), self.safe_string_k(latestQuote.clone(), "ap", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(latestQuote, "as", &[]));
m.insert("vwap".to_string(), self.safe_string_k(dailyBar.clone(), "vw", &[]));
m.insert("open".to_string(), self.safe_string_k(dailyBar.clone(), "o", &[]));
m.insert("close".to_string(), self.safe_string_k(dailyBar.clone(), "c", &[]));
m.insert("last".to_string(), self.safe_string_k(latestTrade, "p", &[]));
m.insert("previousClose".to_string(), self.safe_string_k(prevDailyBar, "c", &[]));
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_string_k(dailyBar.clone(), "v", &[]));
m.insert("quoteVolume".to_string(), crate::precise::Precise::stringMul(&self.safe_string_k(dailyBar.clone(), "v", &[]), &self.safe_string_k(dailyBar, "vw", &[])));
m
}), &[market]);
append_to_array(&mut results, ticker);
}
}
return self.filter_by_array(results, Value::Str("symbol".into()), &[symbols]);
Value::Null
}
pub fn generate_client_order_id(&self, mut params: Value) -> Option<String> {
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut clientOrderIdprefix: Value = self.safe_string_k(self.options.clone(), "clientOrderId", &[]);
let mut uuid: Value = self.uuid(&[]);
let mut parts: Value = split(&uuid, &Value::Str("-".into()));
let mut random_id: Value = join(&parts, &Value::Str("".into()));
let mut defaultClientId: Value = self.implode_params(clientOrderIdprefix, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), random_id);
m
}));
let mut clientOrderId: Value = (match params.get("clientOrderId") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => defaultClientId });
return clientOrderId.as_str().map(str::to_owned);
}
/*
* @method
* @name alpaca#createMarketOrderWithCost
* @description create a market order by providing the symbol, side and cost
* @see https://docs.alpaca.markets/reference/postorder
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} side 'buy' or 'sell'
* @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_order_with_cost(&mut self, mut symbol: Value, mut side: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost);
m
});
let __ws_arg_8 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), side, Value::Int(0), &[Value::Null, __ws_arg_8]).await;
Value::Null
}
/*
* @method
* @name alpaca#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @see https://docs.alpaca.markets/reference/postorder
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost);
m
});
let __ws_arg_9 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), Value::Str("buy".into()), Value::Int(0), &[Value::Null, __ws_arg_9]).await;
Value::Null
}
/*
* @method
* @name alpaca#createMarketSellOrderWithCost
* @description create a market sell order by providing the symbol and cost
* @see https://docs.alpaca.markets/reference/postorder
* @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_sell_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost.clone());
m
});
let __ws_arg_10 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), Value::Str("sell".into()), cost, &[Value::Null, __ws_arg_10]).await;
Value::Null
}
/*
* @method
* @name alpaca#createOrder
* @description create a trade order
* @see https://docs.alpaca.markets/reference/postorder
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market', 'limit' or 'stop_limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.triggerPrice] The price at which a trigger order is triggered at
* @param {string} [params.timeInForce] 'GTC' or 'IOC', the venue supports only these two for crypto orders, defaults to 'GTC'
* @param {float} [params.cost] *market orders only* the cost of the order in units of the quote currency
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut id: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), id.clone());
m.insert("side".to_string(), side);
m.insert("type".to_string(), type_var.clone());
m
});
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".into()), Value::Str("stop_price".into()), &[]);
if (triggerPrice != Value::Null) {
let mut newType: Value = Value::Null;
if Value::Int(type_var.as_str().and_then(|__s| __s.find("limit")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
newType = Value::Str("stop_limit".into());
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support stop orders for ".into())).into()), type_var).into()), Value::Str(" orders, only stop_limit orders are supported".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stop_price".into(), self.price_to_precision(symbol.clone(), triggerPrice)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), newType); }
}
if Value::Int(type_var.as_str().and_then(|__s| __s.find("limit")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit_price".into(), self.price_to_precision(symbol.clone(), price)); }
}
let mut cost: Value = self.safe_string_k(params.clone(), "cost", &[]);
if (cost != Value::Null) {
params = self.omit(params.clone(), Value::Str("cost".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("notional".into(), self.cost_to_precision(symbol.clone(), cost)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("qty".into(), self.amount_to_precision(symbol, amount)); }
}
let mut defaultTIF: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".into()), Value::Str("timeInForce".into()), &[]); defaultTIF = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (defaultTIF != Value::Null) {
// the venue only accepts lowercase values, normalize the unified uppercase spellings
defaultTIF = to_lower(&defaultTIF);
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("time_in_force".into(), defaultTIF); }
params = self.omit(params.clone(), Value::from(vec![Value::Str("timeInForce".into()), Value::Str("triggerPrice".into())]), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_order_id".into(), self.generate_client_order_id(params.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
params = self.omit(params.clone(), Value::from(vec![Value::Str("clientOrderId".into())]), &[]);
let __ws_arg_11 = self.extend(request, &[params]);
let mut order: Value = self.trader_private_post_v2_orders(&[__ws_arg_11]).await;
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name alpaca#cancelOrder
* @description cancels an open order
* @see https://docs.alpaca.markets/reference/deleteorderbyorderid
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_12 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_delete_v2_orders_order_id(&[__ws_arg_12]).await;
return self.parse_order(response, &[]);
Value::Null
}
/*
* @method
* @name alpaca#cancelAllOrders
* @description cancel all open orders in a market
* @see https://docs.alpaca.markets/reference/deleteallorders
* @param {string} [symbol] alpaca cancelAllOrders cannot setting symbol, it will cancel all open orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.trader_private_delete_v2_orders(&[params]).await;
if (matches!(&response, Value::Arr(_))) {
return self.parse_orders(response.clone(), &[]);
} else {
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
}
Value::Null
}
/*
* @method
* @name alpaca#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.alpaca.markets/reference/getorderbyorderid
* @param {string} id the order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let __ws_arg_13 = self.extend(request, &[params]);
let mut order: Value = self.trader_private_get_v2_orders_order_id(&[__ws_arg_13]).await;
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
let mut market: Value = self.safe_market(&[marketId]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name alpaca#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://docs.alpaca.markets/reference/getallorders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {string} [params.direction] the ordering of the results, 'asc' or 'desc', defaults to 'asc' when since is set
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("all".into()));
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("symbols".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("until".into(), self.iso8601(until)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), self.iso8601(since.clone())); }
let mut direction: Option<String> = self.safe_string_k(params.clone(), "direction", &[]).as_str().map(str::to_owned);
if (direction.is_none()) {
// the server default is desc, so a limit would truncate the newest window instead of the range starting at since — request oldest-first like krakenfutures does
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("direction".into(), Value::Str("asc".into())); }
}
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_14 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_get_v2_orders(&[__ws_arg_14]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name alpaca#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.alpaca.markets/reference/getallorders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {string} [params.direction] the ordering of the results, 'asc' or 'desc', defaults to 'asc' when since is set
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("open".into()));
m
});
let __ws_arg_15 = self.extend(request, &[params]);
return self.fetch_orders(&[symbol, since, limit, __ws_arg_15]).await;
Value::Null
}
/*
* @method
* @name alpaca#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.alpaca.markets/reference/getallorders
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {string} [params.direction] the ordering of the results, 'asc' or 'desc', defaults to 'asc' when since is set
* @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
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("closed".into()));
m
});
let __ws_arg_16 = self.extend(request, &[params]);
return self.fetch_orders(&[symbol, since, limit, __ws_arg_16]).await;
Value::Null
}
/*
* @method
* @name alpaca#editOrder
* @description edit a trade order
* @see https://docs.alpaca.markets/reference/patchorderbyorderid-1
* @param {string} id order id
* @param {string} [symbol] unified symbol of the market to create an order in
* @param {string} [type] 'market', 'limit' or 'stop_limit'
* @param {string} [side] 'buy' or 'sell'
* @param {float} [amount] how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price for the order, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.triggerPrice] the price to trigger a stop order
* @param {string} [params.timeInForce] 'GTC' or 'IOC', the venue supports only these two for crypto orders, defaults to 'GTC'
* @param {string} [params.clientOrderId] a unique identifier for the order, automatically generated if not sent
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("qty".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".into()), Value::Str("stop_price".into()), &[]);
if (triggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("stop_price".into(), self.price_to_precision(symbol.clone(), triggerPrice)); }
params = self.omit(params.clone(), Value::Str("triggerPrice".into()), &[]);
}
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit_price".into(), self.price_to_precision(symbol, price)); }
}
let mut timeInForce: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("editOrder".into()), Value::Str("timeInForce".into()), &[Value::Str("gtc".into())]); timeInForce = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (timeInForce != Value::Null) {
// the venue only accepts lowercase values, normalize the unified uppercase spellings
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("time_in_force".into(), to_lower(&timeInForce)); }
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("client_order_id".into(), self.generate_client_order_id(params.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
params = self.omit(params.clone(), Value::from(vec![Value::Str("clientOrderId".into())]), &[]);
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_patch_v2_orders_order_id(&[__ws_arg_17]).await;
return self.parse_order(response, &[market]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id":"6ecfcc34-4bed-4b53-83ba-c564aa832a81",
// "client_order_id":"ccxt_1c6ceab0b5e84727b2f1c0394ba17560",
// "created_at":"2022-06-14T13:59:30.224037068Z",
// "updated_at":"2022-06-14T13:59:30.224037068Z",
// "submitted_at":"2022-06-14T13:59:30.221856828Z",
// "filled_at":null,
// "expired_at":null,
// "canceled_at":null,
// "failed_at":null,
// "replaced_at":null,
// "replaced_by":null,
// "replaces":null,
// "asset_id":"64bbff51-59d6-4b3c-9351-13ad85e3c752",
// "symbol":"BTCUSD",
// "asset_class":"crypto",
// "notional":null,
// "qty":"0.01",
// "filled_qty":"0",
// "filled_avg_price":null,
// "order_class":"",
// "order_type":"limit",
// "type":"limit",
// "side":"buy",
// "time_in_force":"day",
// "limit_price":"14000",
// "stop_price":null,
// "status":"accepted",
// "extended_hours":false,
// "legs":null,
// "trail_percent":null,
// "trail_price":null,
// "hwm":null,
// "commission":"0.42",
// "source":null
// }
//
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
market = self.safe_market(&[marketId, market.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut alpacaStatus: Value = self.safe_string_k(order.clone(), "status", &[]);
let mut status: Value = self.parse_order_status(alpacaStatus);
let mut feeValue: Value = self.safe_string_k(order.clone(), "commission", &[]);
let mut fee: Value = Value::Null;
if (feeValue != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeValue);
m.insert("currency".to_string(), Value::Str("USD".into()));
m
});
}
let mut orderType: Value = self.safe_string_k(order.clone(), "order_type", &[]);
if (orderType != Value::Null) {
if Value::Int(orderType.as_str().and_then(|__s| __s.find("limit")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
// might be limit or stop-limit
orderType = Value::Str("limit".into());
}
}
let mut datetime: Value = self.safe_string_k(order.clone(), "submitted_at", &[]);
let mut timestamp: Value = self.parse8601(datetime.clone());
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(order.clone(), "id", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "client_order_id", &[]));
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("lastTradeTimestamp".to_string(), self.parse8601(self.safe_string_k(order.clone(), "filled_at", &[])));
m.insert("status".to_string(), status);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), orderType);
m.insert("timeInForce".to_string(), self.parse_time_in_force(self.safe_string_k(order.clone(), "time_in_force", &[])));
m.insert("postOnly".to_string(), Value::Null);
m.insert("side".to_string(), self.safe_string_k(order.clone(), "side", &[]));
m.insert("price".to_string(), self.safe_number_k(order.clone(), "limit_price", &[]));
m.insert("triggerPrice".to_string(), self.safe_number_k(order.clone(), "stop_price", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_number_k(order.clone(), "filled_avg_price", &[]));
m.insert("amount".to_string(), self.safe_number_k(order.clone(), "qty", &[]));
m.insert("filled".to_string(), self.safe_number_k(order.clone(), "filled_qty", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("info".to_string(), order);
m
}), &[market]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pending_new".to_string(), Value::Str("open".into()));
m.insert("accepted".to_string(), Value::Str("open".into()));
m.insert("accepted_for_bidding".to_string(), Value::Str("open".into()));
m.insert("new".to_string(), Value::Str("open".into()));
m.insert("partially_filled".to_string(), Value::Str("open".into()));
m.insert("activated".to_string(), Value::Str("open".into()));
m.insert("done_for_day".to_string(), Value::Str("open".into()));
m.insert("stopped".to_string(), Value::Str("open".into()));
m.insert("suspended".to_string(), Value::Str("open".into()));
m.insert("held".to_string(), Value::Str("open".into()));
m.insert("pending_replace".to_string(), Value::Str("open".into()));
m.insert("pending_cancel".to_string(), Value::Str("canceling".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("calculated".to_string(), Value::Str("closed".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("replaced".to_string(), Value::Str("canceled".into()));
m.insert("expired".to_string(), Value::Str("expired".into()));
m.insert("rejected".to_string(), Value::Str("rejected".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("day".to_string(), Value::Str("Day".into()));
m.insert("gtc".to_string(), Value::Str("GTC".into()));
m.insert("ioc".to_string(), Value::Str("IOC".into()));
m.insert("fok".to_string(), Value::Str("FOK".into()));
m
});
return self.safe_string(timeInForces, timeInForce.clone(), &[timeInForce.clone()]);
Value::Null
}
/*
* @method
* @name alpaca#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.alpaca.markets/reference/getaccountactivitiesbyactivitytype-1
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trade 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 {string} [params.page_token] page_token - used for paging
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("activity_type".to_string(), Value::Str("FILL".into()));
m
});
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("until".into(), self.iso8601(until)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), self.iso8601(since.clone())); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("page_size".into(), limit.clone()); }
}
{ let __destr_tmp = self.handle_until_option(Value::Str("until".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_get_v2_account_activities_activity_type(&[__ws_arg_18]).await;
return self.parse_trades(response, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades
//
// {
// "t":"2022-06-14T05:00:00.027869Z",
// "x":"CBSE",
// "p":"21942.15",
// "s":"0.0001",
// "tks":"S",
// "i":"355681339"
// }
//
// fetchMyTrades
//
// {
// "id": "20221228071929579::ca2aafd0-1270-4b56-b0a9-85423b4a07c8",
// "activity_type": "FILL",
// "transaction_time": "2022-12-28T12:19:29.579352Z",
// "type": "fill",
// "price": "67.31",
// "qty": "0.07",
// "side": "sell",
// "symbol": "LTC/USD",
// "leaves_qty": "0",
// "order_id": "82eebcf7-6e66-4b7e-93f8-be0df0e4f12e",
// "cum_qty": "0.07",
// "order_status": "filled",
// "swap_rate": "1"
// },
//
let mut marketId: Value = self.safe_string2(trade.clone(), Value::Str("S".into()), Value::Str("symbol".into()), &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market.clone()]);
let mut datetime: Value = self.safe_string2(trade.clone(), Value::Str("t".into()), Value::Str("transaction_time".into()), &[]);
let mut timestamp: Value = self.parse8601(datetime);
let mut alpacaSide: Option<String> = self.safe_string_k(trade.clone(), "tks", &[]).as_str().map(str::to_owned);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if (alpacaSide.as_deref() == Some("B")) {
side = Value::Str("buy".into());
} else if (alpacaSide.as_deref() == Some("S")) {
side = Value::Str("sell".into());
}
let mut priceString: Value = self.safe_string2(trade.clone(), Value::Str("p".into()), Value::Str("price".into()), &[]);
let mut amountString: Value = self.safe_string2(trade.clone(), Value::Str("s".into()), Value::Str("qty".into()), &[]);
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("i".into()), Value::Str("id".into()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("order".to_string(), self.safe_string_k(trade, "order_id", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("price".to_string(), priceString);
m.insert("amount".to_string(), amountString);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name alpaca#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.alpaca.markets/reference/listcryptofundingwallets
* @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_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_19 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_get_v2_wallets(&[__ws_arg_19]).await;
return self.parse_deposit_address(response, &[currency]);
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "asset_id": "4fa30c85-77b7-4cbc-92dd-7b7513640aad",
// "address": "bc1q2fpskfnwem3uq9z8660e4z6pfv7aqfamysk75r",
// "created_at": "2024-11-03T07:30:05.609976344Z"
// }
//
let mut parsedCurrency: Value = Value::Null;
if (currency != Value::Null) {
parsedCurrency = currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress.clone());
m.insert("currency".to_string(), parsedCurrency);
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), self.safe_string_k(depositAddress, "address", &[]));
m.insert("tag".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name alpaca#withdraw
* @description make a withdrawal
* @see https://docs.alpaca.markets/reference/createcryptotransferforaccount
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag a memo for the transaction
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
{ let __destr_tmp = self.handle_withdraw_tag_and_params(tag.clone(), params.clone()); tag = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
self.check_address(&[address.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
if (tag != Value::Null) && (tag.as_str() != Some("")) {
address = Value::Str(format!("{}{}", Value::Str(format!("{}{}", address, Value::Str(":".into())).into()), tag).into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("address".to_string(), address);
m.insert("amount".to_string(), self.number_to_string(amount));
m
});
let __ws_arg_20 = self.extend(request, &[params]);
let mut response: Value = self.trader_private_post_v2_wallets_transfers(&[__ws_arg_20]).await;
return self.parse_transaction(response, &[currency]);
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enable); }
}
pub async fn fetch_transactions_helper(&mut self, mut type_var: Value, mut code: Value, mut since: Value, mut limit: Value, mut params: Value) -> Value {
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
let mut sandboxMode: bool = is_true(&self.isSandboxModeEnabled) || is_true(&self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]));
if (sandboxMode) {
// paper-trading hosts do not serve the crypto wallets api at all, so route
// through the account activities ledger instead, filtered to transfer-like
// entries, see https://github.com/ccxt/ccxt/issues/24847
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("activity_types".to_string(), Value::Str("CSD,CSW,TRANS".into()));
m
});
let __ws_arg_21 = self.extend(request, &[params.clone()]);
let mut activities: Value = self.trader_private_get_v2_account_activities(&[__ws_arg_21]).await;
//
// [
// {
// "id": "20250110000000000::7f6cba2b-4c72-46b9-8e34-8e5b0b8d8e10",
// "activity_type": "CSD",
// "date": "2025-01-10",
// "net_amount": "1000",
// "status": "executed"
// }
// ]
//
let mut filtered: Value = Value::from(vec![]);
let mut ledger: Value = Value::from(vec![]);
if (matches!(&activities, Value::Arr(_))) {
ledger = activities.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_214: bool = true;
while { if !__for_first_214 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_214 = false; i.as_f64().unwrap_or(f64::NAN) < ((ledger.len() as i64) as f64) } {
let mut entry: Value = ledger.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut activityType: Option<String> = self.safe_string_k(entry.clone(), "activity_type", &[]).as_str().map(str::to_owned);
let mut amount: Value = self.safe_string_k(entry.clone(), "net_amount", &[]);
let mut isIncoming: bool = (activityType.as_deref() == Some("CSD")) || ((activityType.as_deref() == Some("TRANS")) && !is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))));
let mut entryDirection: Value = (if isIncoming { Value::Str("INCOMING".into()) } else { Value::Str("OUTGOING".into()) });
if (type_var.as_str() == Some("BOTH")) || (is_equal(&entryDirection, &type_var)) {
append_to_array(&mut filtered, entry.clone());
}
}
}
return self.parse_transactions(filtered, &[currency.clone(), since.clone(), limit.clone(), params.clone()]);
}
let mut response: Value = self.trader_private_get_v2_wallets_transfers(&[params.clone()]).await;
//
// {
// "id": "e27b70a6-5610-40d7-8468-a516a284b776",
// "tx_hash": null,
// "direction": "OUTGOING",
// "amount": "20",
// "usd_value": "19.99856",
// "chain": "ETH",
// "asset": "USDT",
// "from_address": "0x123930E4dCA196E070d39B60c644C8Aae02f23",
// "to_address": "0x1232c0925196e4dcf05945f67f690153190fbaab",
// "status": "PROCESSING",
// "created_at": "2024-11-07T02:39:01.775495Z",
// "network_fee": "4",
// "fees": "0.1"
// }
//
let mut results: Value = Value::from(vec![]);
let mut transfers: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
transfers = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_215: bool = true;
while { if !__for_first_215 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_215 = false; i.as_f64().unwrap_or(f64::NAN) < ((transfers.len() as i64) as f64) } {
let mut entry: Value = transfers.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut direction: Value = self.safe_string_k(entry.clone(), "direction", &[]);
if is_equal(&direction, &type_var) {
append_to_array(&mut results, entry.clone());
} else if (type_var.as_str() == Some("BOTH")) {
append_to_array(&mut results, entry);
}
}
}
return self.parse_transactions(results, &[currency, since, limit, params]);
Value::Null
}
/*
* @method
* @name alpaca#fetchDepositsWithdrawals
* @description fetch history of deposits and withdrawals
* @see https://docs.alpaca.markets/reference/listcryptofundingtransfers
* @param {string} [code] unified currency code for the currency of the deposit/withdrawals, default is undefined
* @param {int} [since] timestamp in ms of the earliest deposit/withdrawal, default is undefined
* @param {int} [limit] max number of deposit/withdrawals to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_transactions_helper(Value::Str("BOTH".into()), code, since, limit, params).await;
Value::Null
}
/*
* @method
* @name alpaca#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.alpaca.markets/reference/listcryptofundingtransfers
* @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 deposit structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_transactions_helper(Value::Str("INCOMING".into()), code, since, limit, params).await;
Value::Null
}
/*
* @method
* @name alpaca#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.alpaca.markets/reference/listcryptofundingtransfers
* @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 withdrawal structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_transactions_helper(Value::Str("OUTGOING".into()), code, since, limit, params).await;
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// account activities ledger entry (paper-trading path), see https://github.com/ccxt/ccxt/issues/24847
//
// {
// "id": "20250110000000000::7f6cba2b-4c72-46b9-8e34-8e5b0b8d8e10",
// "activity_type": "CSD",
// "date": "2025-01-10",
// "net_amount": "1000",
// "status": "executed"
// }
//
// crypto wallets api entry
//
// {
// "id": "e27b70a6-5610-40d7-8468-a516a284b776",
// "tx_hash": null,
// "direction": "OUTGOING",
// "amount": "20",
// "usd_value": "19.99856",
// "chain": "ETH",
// "asset": "USDT",
// "from_address": "0x123930E4dCA196E070d39B60c644C8Aae02f23",
// "to_address": "0x1232c0925196e4dcf05945f67f690153190fbaab",
// "status": "PROCESSING",
// "created_at": "2024-11-07T02:39:01.775495Z",
// "network_fee": "4",
// "fees": "0.1"
// }
//
let mut activityType: Value = self.safe_string_k(transaction.clone(), "activity_type", &[]);
let mut txid: Value = Value::Null;
let mut timestamp: Value = Value::Null;
let mut datetime: Value = Value::Null;
let mut network: Value = Value::Null;
let mut address: Value = Value::Null;
let mut addressTo: Value = Value::Null;
let mut addressFrom: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut code: Value = Value::Null;
let mut status: Value = Value::Null;
let mut comment: Value = Value::Null;
let mut internal: Value = Value::Null;
let mut fee: Value = Value::Null;
if (activityType != Value::Null) {
let mut netAmount: Value = self.safe_string_k(transaction.clone(), "net_amount", &[]);
let mut isIncoming: bool = (activityType.as_str() == Some("CSD")) || ((activityType.as_str() == Some("TRANS")) && !is_true(&crate::precise::Precise::stringLt(&netAmount, &Value::Str("0".into()))));
timestamp = self.parse8601(Value::Str(format!("{}{}", self.safe_string_k(transaction.clone(), "date", &[]), Value::Str("T00:00:00Z".into())).into()));
datetime = self.iso8601(timestamp.clone());
type_var = (if isIncoming { Value::Str("deposit".into()) } else { Value::Str("withdrawal".into()) });
amount = self.parse_number(crate::precise::Precise::stringAbs(&netAmount), &[]);
// cash ledger rows carry no per-entry asset field and are USD, while crypto
// TRANS entries may carry symbol/asset - never blindly adopt the caller's
// currency filter, see the review on https://github.com/ccxt/ccxt/pull/29580
let mut activityCurrencyId: Value = self.safe_string2(transaction.clone(), Value::Str("symbol".into()), Value::Str("asset".into()), &[]);
if (activityCurrencyId != Value::Null) {
code = self.safe_currency_code(activityCurrencyId, &[]);
} else if (activityType.as_str() == Some("CSD")) || (activityType.as_str() == Some("CSW")) {
code = Value::Str("USD".into());
} else {
code = self.safe_currency_code(Value::Null, &[currency.clone()]);
}
status = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
comment = activityType.clone();
internal = (Value::Bool(activityType.as_str() != Some("TRANS")));
} else {
txid = self.safe_string_k(transaction.clone(), "tx_hash", &[]);
datetime = self.safe_string_k(transaction.clone(), "created_at", &[]);
timestamp = self.parse8601(datetime.clone());
network = self.safe_string_k(transaction.clone(), "chain", &[]);
address = self.safe_string_k(transaction.clone(), "to_address", &[]);
addressTo = self.safe_string_k(transaction.clone(), "to_address", &[]);
addressFrom = self.safe_string_k(transaction.clone(), "from_address", &[]);
type_var = self.parse_transaction_type(self.safe_string_k(transaction.clone(), "direction", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
amount = self.safe_number_k(transaction.clone(), "amount", &[]);
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "asset", &[]);
code = self.safe_currency_code(currencyId, &[currency]);
status = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
let mut fees: Value = self.safe_string_k(transaction.clone(), "fees", &[]);
let mut networkFee: Value = self.safe_string_k(transaction.clone(), "network_fee", &[]);
let mut totalFee: Value = crate::precise::Precise::stringAdd(&fees, &networkFee);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(totalFee, &[]));
m.insert("currency".to_string(), code.clone());
m
});
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction, "id", &[]));
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("network".to_string(), network);
m.insert("address".to_string(), address);
m.insert("addressTo".to_string(), addressTo);
m.insert("addressFrom".to_string(), addressFrom);
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), type_var);
m.insert("amount".to_string(), amount);
m.insert("currency".to_string(), code);
m.insert("status".to_string(), status);
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), comment);
m.insert("internal".to_string(), internal);
m.insert("fee".to_string(), fee);
m
});
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("PROCESSING".to_string(), Value::Str("pending".into()));
m.insert("FAILED".to_string(), Value::Str("failed".into()));
m.insert("COMPLETE".to_string(), Value::Str("ok".into()));
m.insert("executed".to_string(), Value::Str("ok".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("pending".to_string(), Value::Str("pending".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("INCOMING".to_string(), Value::Str("deposit".into()));
m.insert("OUTGOING".to_string(), Value::Str("withdrawal".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name alpaca#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.alpaca.markets/reference/getaccount-1
* @see https://docs.alpaca.markets/reference/getallopenpositions
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}. note that `info` is
* the composite `{ account, positions }` wrapper of both raw venue payloads, not the bare account payload it was
* before crypto positions were included — read `info['account']['cash']` where `info['cash']` used to be read
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// the two calls stay sequential deliberately — the static request harness records one request per case,
// and concurrent calls make the recorded url nondeterministic per language
let mut account: Value = self.trader_private_get_v2_account(&[params]).await;
let mut positions: Value = self.trader_private_get_v2_positions(&[]).await;
//
// {
// "id": "43a01bde-4eb1-64fssc26adb5",
// "admin_configurations": {
// "allow_instant_ach": true,
// "max_margin_multiplier": "4"
// },
// "user_configurations": {
// "fractional_trading": true,
// "max_margin_multiplier": "4"
// },
// "account_number": "744873727",
// "status": "ACTIVE",
// "crypto_status": "ACTIVE",
// "currency": "USD",
// "buying_power": "5.92",
// "regt_buying_power": "5.92",
// "daytrading_buying_power": "0",
// "effective_buying_power": "5.92",
// "non_marginable_buying_power": "5.92",
// "bod_dtbp": "0",
// "cash": "5.92",
// "accrued_fees": "0",
// "portfolio_value": "48.6",
// "pattern_day_trader": false,
// "trading_blocked": false,
// "transfers_blocked": false,
// "account_blocked": false,
// "created_at": "2022-06-13T14:59:18.318096Z",
// "trade_suspended_by_user": false,
// "multiplier": "1",
// "shorting_enabled": false,
// "equity": "48.6",
// "last_equity": "48.8014266",
// "long_market_value": "42.68",
// "short_market_value": "0",
// "position_market_value": "42.68",
// "initial_margin": "0",
// "maintenance_margin": "0",
// "last_maintenance_margin": "0",
// "sma": "5.92",
// "daytrade_count": 0,
// "balance_asof": "2024-12-10",
// "crypto_tier": 1,
// "intraday_adjustments": "0",
// "pending_reg_taf_fees": "0"
// }
//
let mut response: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account".to_string(), account);
m.insert("positions".to_string(), positions);
m
});
return self.parse_balance(response);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// crypto holdings live on the positions endpoint, the account endpoint carries only the cash currency
//
// "positions": [
// {
// "asset_id": "64bbff51-59d6-4b3c-9351-13ad85e3c752",
// "symbol": "BTCUSD",
// "exchange": "CRYPTO",
// "asset_class": "crypto",
// "asset_marginable": false,
// "qty": "0.000207296",
// "avg_entry_price": "80037",
// "side": "long",
// "market_value": "16.592345",
// "cost_basis": "16.59135",
// "unrealized_pl": "0.000995",
// "unrealized_plpc": "0.00006",
// "current_price": "80041.8",
// "qty_available": "0.000207296"
// }
// ]
//
let mut account: Value = self.safe_dict_k(response.clone(), "account", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positions: Value = self.safe_list_k(response.clone(), "positions", &[Value::from(vec![])]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
});
let mut currencyId: Value = self.safe_string_k(account.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if (code != Value::Null) {
let mut cashAccount: Value = self.account();
add_element_to_object(&mut cashAccount, &Value::Str("free".into()), self.safe_string_k(account.clone(), "cash", &[])); // cash already excludes the amounts held for open orders, verified live 2026-09-16
let mut equity: Value = self.safe_string_k(account.clone(), "equity", &[]);
let mut positionsValue: Value = self.safe_string_k(account.clone(), "position_market_value", &[]);
add_element_to_object(&mut cashAccount, &Value::Str("total".into()), crate::precise::Precise::stringSub(&equity, &positionsValue)); // equity minus the positions market value equals cash plus open-order holds; stringSub degrades to undefined when either field is absent and safeBalance then derives the total from free
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), cashAccount); }
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_216: bool = true;
while { if !__for_first_216 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_216 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
let mut position: Value = positions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut positionSymbol: Value = self.safe_string_k(position.clone(), "symbol", &[]);
if (positionSymbol == Value::Null) {
continue;
}
let mut baseId: Value = Value::Null;
if Value::Int(positionSymbol.as_str().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
let mut parts: Value = split(&positionSymbol, &Value::Str("/".into()));
baseId = self.safe_string(parts, Value::Int(0), &[]);
} else {
// crypto position symbols come compressed with a USD tail, e.g. BTCUSD or USDTUSD
let mut baseLength: Value = (match (&(Value::Int(positionSymbol.len() as i64)), &(Value::Int(3))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if (baseLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) && (slice(&positionSymbol, &baseLength, &Value::Null).as_str() == Some("USD")) {
baseId = slice(&positionSymbol, &Value::Int(0), &baseLength);
}
}
if (baseId == Value::Null) {
continue;
}
let mut positionCode: Value = self.safe_currency_code(baseId, &[]);
if (positionCode != Value::Null) && !(in_op(&result, &positionCode)) {
let mut positionAccount: Value = self.account();
add_element_to_object(&mut positionAccount, &Value::Str("free".into()), self.safe_string_k(position.clone(), "qty_available", &[]));
add_element_to_object(&mut positionAccount, &Value::Str("total".into()), self.safe_string_k(position, "qty", &[]));
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&positionCode), positionAccount); }
}
}
}
return self.safe_balance(result);
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut endpoint: Value = Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path.clone(), params.clone())).into());
let mut url: Value = self.implode_hostname(get_value(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), &get_value(&api, &Value::Int(0))));
headers = (if (headers != Value::Null) { headers.clone() } else { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
if (get_value(&api, &Value::Int(1)).as_str() == Some("private")) {
self.check_required_credentials(&[]);
if let Value::Dict(__d) = &mut headers { std::sync::Arc::make_mut(__d).insert("APCA-API-KEY-ID".into(), self.apiKey.clone()); }
if let Value::Dict(__d) = &mut headers { std::sync::Arc::make_mut(__d).insert("APCA-API-SECRET-KEY".into(), self.secret.clone()); }
}
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
if (method.as_str() == Some("GET")) || (method.as_str() == Some("DELETE")) {
endpoint = Value::Str(format!("{}{}", endpoint, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
} else {
body = json_stringify(&query);
if let Value::Dict(__d) = &mut headers { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
}
}
url = Value::Str(format!("{}{}", url, endpoint).into());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), body);
m.insert("headers".to_string(), headers);
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
// {
// "code": 40110000,
// "message": "request is not authorized"
// }
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
let mut errorCode: Value = self.safe_string_k(response.clone(), "code", &[]);
if (code != Value::Null) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode, feedback.clone());
}
let mut message: Value = self.safe_string_k(response, "message", &[]);
if (message != Value::Null) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
let mut codeAsString: Value = to_string_val(&code);
if (code.as_f64().unwrap_or(f64::NAN) < ((400i64) as f64)) || !(in_op(&self.httpExceptions, &codeAsString)) {
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
return Value::Null;
Value::Null
}
}