// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
pub struct 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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
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.clone()])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on AlpacaCore.
AlpacaCore::sign(self, path, &[api.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on 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.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"create_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.get(3..).unwrap_or(&[]).to_vec()[..]).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.get(2..).unwrap_or(&[]).to_vec()[..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits" => self.fetch_deposits(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_orders" => self.fetch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_time" => self.fetch_time(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_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.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"generate_client_order_id" => self.generate_client_order_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_time_in_force" => self.parse_time_in_force(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transaction_type" => self.parse_transaction_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args.get(3..).unwrap_or(&[]).to_vec()[..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for 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".to_string()));
m.insert("name".to_string(), Value::Str("Alpaca".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("US".to_string())]));
m.insert("rateLimit".to_string(), Value::Int(333));
m.insert("hostname".to_string(), Value::Str("alpaca.markets".to_string()));
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".to_string()));
m.insert("www".to_string(), Value::Str("https://alpaca.markets".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("broker".to_string(), Value::Str("https://broker-api.{hostname}".to_string()));
m.insert("trader".to_string(), Value::Str("https://api.{hostname}".to_string()));
m.insert("market".to_string(), Value::Str("https://data.{hostname}".to_string()));
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}".to_string()));
m.insert("trader".to_string(), Value::Str("https://paper-api.{hostname}".to_string()));
m.insert("market".to_string(), Value::Str("https://data.{hostname}".to_string()));
m
}));
m.insert("doc".to_string(), Value::Str("https://alpaca.markets/docs/".to_string()));
m.insert("fees".to_string(), Value::Str("https://docs.alpaca.markets/docs/crypto-fees".to_string()));
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
}));
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
}));
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
}));
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
}));
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/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".to_string()));
m.insert("3m".to_string(), Value::Str("3min".to_string()));
m.insert("5m".to_string(), Value::Str("5min".to_string()));
m.insert("15m".to_string(), Value::Str("15min".to_string()));
m.insert("30m".to_string(), Value::Str("30min".to_string()));
m.insert("1h".to_string(), Value::Str("1H".to_string()));
m.insert("2h".to_string(), Value::Str("2H".to_string()));
m.insert("4h".to_string(), Value::Str("4H".to_string()));
m.insert("6h".to_string(), Value::Str("6H".to_string()));
m.insert("8h".to_string(), Value::Str("8H".to_string()));
m.insert("12h".to_string(), Value::Str("12H".to_string()));
m.insert("1d".to_string(), Value::Str("1D".to_string()));
m.insert("3d".to_string(), Value::Str("3D".to_string()));
m.insert("1w".to_string(), Value::Str("1W".to_string()));
m.insert("1M".to_string(), Value::Str("1M".to_string()));
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".to_string()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0025".to_string()), &[]));
m.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::List(vec![Value::List(vec![self.parse_number(Value::Str("0".to_string()), &[]), self.parse_number(Value::Str("0.0025".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000".to_string()), &[]), self.parse_number(Value::Str("0.0022".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("500000".to_string()), &[]), self.parse_number(Value::Str("0.0020".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("1000000".to_string()), &[]), self.parse_number(Value::Str("0.0018".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("10000000".to_string()), &[]), self.parse_number(Value::Str("0.0015".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("25000000".to_string()), &[]), self.parse_number(Value::Str("0.0013".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("50000000".to_string()), &[]), self.parse_number(Value::Str("0.0012".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000000".to_string()), &[]), self.parse_number(Value::Str("0.001".to_string()), &[])])]));
m.insert("maker".to_string(), Value::List(vec![Value::List(vec![self.parse_number(Value::Str("0".to_string()), &[]), self.parse_number(Value::Str("0.0015".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000".to_string()), &[]), self.parse_number(Value::Str("0.0012".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("500000".to_string()), &[]), self.parse_number(Value::Str("0.001".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("1000000".to_string()), &[]), self.parse_number(Value::Str("0.0008".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("10000000".to_string()), &[]), self.parse_number(Value::Str("0.0005".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("25000000".to_string()), &[]), self.parse_number(Value::Str("0.0002".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("50000000".to_string()), &[]), self.parse_number(Value::Str("0.0002".to_string()), &[])]), Value::List(vec![self.parse_number(Value::Str("100000000".to_string()), &[]), self.parse_number(Value::Str("0.00".to_string()), &[])])]));
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".to_string()));
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".to_string()));
m.insert("exchanges".to_string(), Value::List(vec![Value::Str("CBSE".to_string()), Value::Str("FTX".to_string()), Value::Str("GNSS".to_string()), Value::Str("ERSX".to_string())]));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeInForce".to_string(), Value::Str("gtc".to_string()));
m
}));
m.insert("clientOrderId".to_string(), Value::Str("ccxt_{id}".to_string()));
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(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("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".to_string()).clone());
m.insert("40410000".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("40010001".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("40110000".to_string(), Value::Str("PermissionDenied".to_string()).clone());
m.insert("42910000".to_string(), Value::Str("RateLimitExceeded".to_string()).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".to_string()).clone());
m.insert("Invalid symbol".to_string(), Value::Str("BadSymbol".to_string()).clone());
m.insert("cost basis must be".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("insufficient balance for".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m.insert("orders are rejected by user request".to_string(), Value::Str("PermissionDenied".to_string()).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.clone()]).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.clone(), "timestamp", &[]);
if is_equal(×tamp, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchTime() missing timestamp".to_string()))));
}
let mut localTime: Value = slice(×tamp, &Value::Int(0), &Value::Int(23));
if is_equal(×tamp, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchTime() missing timestamp".to_string()))));
}
let mut jetlagStrStart: Value = subtract(&get_array_length(×tamp), &Value::Int(6));
if is_equal(×tamp, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchTime() missing timestamp".to_string()))));
}
let mut jetlagStrEnd: Value = subtract(&get_array_length(×tamp), &Value::Int(3));
if is_equal(×tamp, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchTime() missing timestamp".to_string()))));
}
let mut jetlag: Value = slice(×tamp, &jetlagStrStart, &jetlagStrEnd);
let mut iso: Value = subtract(&self.parse_to_int(self.parse8601(localTime.clone())), &multiply(&multiply(&self.parse_to_numeric(jetlag.clone()), &Value::Int(3600)), &Value::Int(1000)));
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".to_string()));
m.insert("status".to_string(), Value::Str("active".to_string()));
m
});
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
let mut assets: Value = self.trader_private_get_v2_assets(&[__ws_arg_0]).await;
return self.parse_markets(assets.clone());
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 is_equal(&marketId, &Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" parseMarket() missing marketId".to_string()))));
}
let mut parts: Value = split(&marketId, &Value::Str("/".to_string()));
let mut assetClass: Value = self.safe_string_k(asset.clone(), "class", &[]);
let mut baseId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut quoteId: Value = self.safe_string(parts.clone(), 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 is_equal("e, &Value::Null) && is_equal(&assetClass, &Value::Str("us_equity".to_string())) {
quote = Value::Str("USD".to_string());
}
let mut symbol: Value = add(&add(&base, &Value::Str("/".to_string())), "e);
let mut status: Value = self.safe_string_k(asset.clone(), "status", &[]);
let mut active: Value = Value::Bool(is_equal(&status, &Value::Str("active".to_string())));
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 is_true(&(is_equal(&assetClass, &Value::Str("crypto".to_string())))) && is_true(&(is_equal("e, &Value::Str("USD".to_string())))) {
// 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".to_string()), &[])]);
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".to_string()));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::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.clone());
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.clone());
m.insert("price".to_string(), price.clone());
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.clone());
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.clone());
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), asset.clone());
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = get_value(&market, &Value::Str("id".to_string()));
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".to_string())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[Value::Str("marketPublicGetV1beta3CryptoLocTrades".to_string())]);
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.clone());
m
});
params = self.omit(params.clone(), Value::List(vec![Value::Str("loc".to_string()), Value::Str("method".to_string())]), &[]);
let mut symbolTrades: Value = Value::Null;
if is_equal(&method, &Value::Str("marketPublicGetV1beta3CryptoLocTrades".to_string())) {
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), 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::List(vec![])]);
} else if is_equal(&method, &Value::Str("marketPublicGetV1beta3CryptoLocLatestTrades".to_string())) {
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "trades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbolTrade: Value = self.safe_dict(trades.clone(), marketId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
symbolTrades = Value::List(vec![symbolTrade.clone()]);
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&self.id, &Value::Str(" fetchTrades() does not support ".to_string())), &method), &Value::Str(", marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported".to_string()))));
}
let mut symbolTradesList: Value = Value::List(vec![]);
if !is_equal(&symbolTrades, &Value::Null) {
symbolTradesList = symbolTrades.clone();
}
return self.parse_trades(symbolTradesList.clone(), &[market.clone(), since.clone(), limit.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut id: Value = get_value(&market, &Value::Str("id".to_string()));
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".to_string())]);
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.clone());
m
});
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "orderbooks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawOrderbook: Value = self.safe_dict(orderbooks.clone(), id.clone(), &[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.clone(), get_value(&market, &Value::Str("symbol".to_string())), &[timestamp.clone(), Value::Str("b".to_string()), Value::Str("a".to_string()), Value::Str("p".to_string()), Value::Str("s".to_string())]);
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".to_string()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = get_value(&market, &Value::Str("id".to_string()));
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".to_string())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[Value::Str("marketPublicGetV1beta3CryptoLocBars".to_string())]);
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".to_string()), Value::Str("paginate".to_string()), &[Value::Bool(false)]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut paginationCalls: Value = Value::Int(10);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".to_string()), Value::Str("paginationCalls".to_string()), &[Value::Int(10)]); paginationCalls = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbols".to_string(), marketId.clone());
m.insert("loc".to_string(), loc.clone());
m
});
params = self.omit(params.clone(), Value::List(vec![Value::Str("loc".to_string()), Value::Str("method".to_string())]), &[]);
let mut ohlcvs: Value = Value::Null;
if is_equal(&method, &Value::Str("marketPublicGetV1beta3CryptoLocBars".to_string())) {
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("start".to_string()), self.iso8601(since.clone()));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("end".to_string()), self.iso8601(until.clone()));
}
add_element_to_object(&mut request, &Value::Str("timeframe".to_string()), 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::List(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 = add(&i, &Value::Int(1)); } __for_first_212 = false; is_less_than(&i, &paginationCalls) } {
let mut ohlcvsLength: Value = get_array_length(&ohlcvs);
if is_true(&(is_equal(&pageToken, &Value::Null))) || is_true(&(is_true(&(!is_equal(&limit, &Value::Null))) && is_true(&(is_greater_than_or_equal(&ohlcvsLength, &limit))))) {
break;
}
add_element_to_object(&mut request, &Value::Str("page_token".to_string()), 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::List(vec![])]);
let mut pageLength: Value = get_array_length(&page);
if is_equal(&pageLength, &Value::Int(0)) {
break;
}
ohlcvs = self.array_concat(ohlcvs.clone(), page.clone());
pageToken = self.safe_string_k(response.clone(), "next_page_token", &[]);
}
}
}
} else if is_equal(&method, &Value::Str("marketPublicGetV1beta3CryptoLocLatestBars".to_string())) {
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
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.clone(), "bars", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bar: Value = self.safe_dict(bars.clone(), marketId.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
ohlcvs = Value::List(vec![bar.clone()]);
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&self.id, &Value::Str(" fetchOHLCV() does not support ".to_string())), &method), &Value::Str(", marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported".to_string()))));
}
return self.parse_ohlc_vs(ohlcvs.clone(), &[market.clone(), timeframe.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "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.clone());
return Value::List(vec![timestamp.clone(), 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.clone(), "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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbol = self.symbol(symbol.clone());
let mut tickers: Value = self.fetch_tickers(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
return self.safe_dict(tickers.clone(), symbol.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&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.clone();
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut loc: Value = self.safe_string_k(params.clone(), "loc", &[Value::Str("us".to_string())]);
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(",".to_string())));
m.insert("loc".to_string(), loc.clone());
m
});
params = self.omit(params.clone(), Value::Str("loc".to_string()), &[]);
let __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
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::List(vec![]);
let mut snapshots: Value = self.safe_dict_k(response.clone(), "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 = add(&i, &Value::Int(1)); } __for_first_213 = false; is_less_than(&i, &get_array_length(&marketIds)) } {
let mut marketId: Value = get_value(&marketIds, &i);
let mut marketId: Value = get_value(&marketIds, &i);
let mut market: Value = self.safe_market(&[marketId.clone()]);
let mut entry: Value = self.safe_dict(snapshots.clone(), marketId.clone(), &[]);
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.clone());
m.insert("symbol".to_string(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone()));
m.insert("datetime".to_string(), datetime.clone());
m.insert("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.clone(), "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.clone(), "p", &[]));
m.insert("previousClose".to_string(), self.safe_string_k(prevDailyBar.clone(), "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.clone(), "vw", &[])));
m
}), &[market.clone()]);
append_to_array(&mut results, ticker.clone());
}
}
return self.filter_by_array(results.clone(), Value::Str("symbol".to_string()), &[symbols.clone()]);
Value::Null
}
pub fn generate_client_order_id(&self, mut params: Value) -> Value {
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("-".to_string()));
let mut random_id: Value = join(&parts, &Value::Str("".to_string()));
let mut defaultClientId: Value = self.implode_params(clientOrderIdprefix.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), random_id.clone());
m
}));
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[defaultClientId.clone()]);
return clientOrderId;
Value::Null
}
/*
* @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 is_equal(&self.markets, &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_8 = self.extend(req.clone(), &[params.clone()]);
return self.create_order(symbol.clone(), Value::Str("market".to_string()), side.clone(), 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 is_equal(&self.markets, &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_9 = self.extend(req.clone(), &[params.clone()]);
return self.create_order(symbol.clone(), Value::Str("market".to_string()), Value::Str("buy".to_string()), 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 is_equal(&self.markets, &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.clone(), &[params.clone()]);
return self.create_order(symbol.clone(), Value::Str("market".to_string()), Value::Str("sell".to_string()), cost.clone(), &[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 {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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut id: Value = get_value(&market, &Value::Str("id".to_string()));
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.clone());
m.insert("type".to_string(), type_var.clone());
m
});
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stop_price".to_string()), &[]);
if !is_equal(&triggerPrice, &Value::Null) {
let mut newType: Value = Value::Null;
if is_greater_than_or_equal(&get_index_of(&type_var, &Value::Str("limit".to_string())), &Value::Int(0)) {
newType = Value::Str("stop_limit".to_string());
} else {
panic!("{}", crate::exchange_errors::not_supported(add(&add(&add(&self.id, &Value::Str(" createOrder() does not support stop orders for ".to_string())), &type_var), &Value::Str(" orders, only stop_limit orders are supported".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("stop_price".to_string()), self.price_to_precision(symbol.clone(), triggerPrice.clone()));
add_element_to_object(&mut request, &Value::Str("type".to_string()), newType.clone());
}
if is_greater_than_or_equal(&get_index_of(&type_var, &Value::Str("limit".to_string())), &Value::Int(0)) {
add_element_to_object(&mut request, &Value::Str("limit_price".to_string()), self.price_to_precision(symbol.clone(), price.clone()));
}
let mut cost: Value = self.safe_string_k(params.clone(), "cost", &[]);
if !is_equal(&cost, &Value::Null) {
params = self.omit(params.clone(), Value::Str("cost".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("notional".to_string()), self.cost_to_precision(symbol.clone(), cost.clone()));
} else {
add_element_to_object(&mut request, &Value::Str("qty".to_string()), self.amount_to_precision(symbol.clone(), amount.clone()));
}
let mut defaultTIF: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("timeInForce".to_string()), &[]); defaultTIF = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut request, &Value::Str("time_in_force".to_string()), defaultTIF.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("timeInForce".to_string()), Value::Str("triggerPrice".to_string())]), &[]);
add_element_to_object(&mut request, &Value::Str("client_order_id".to_string()), self.generate_client_order_id(params.clone()));
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string())]), &[]);
let __ws_arg_11 = self.extend(request.clone(), &[params.clone()]);
let mut order: Value = self.trader_private_post_v2_orders(&[__ws_arg_11]).await;
return self.parse_order(order.clone(), &[market.clone()]);
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.clone());
m
});
let __ws_arg_12 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_delete_v2_orders_order_id(&[__ws_arg_12]).await;
return self.parse_order(response.clone(), &[]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.trader_private_delete_v2_orders(&[params.clone()]).await;
if is_true(&Value::Bool(is_array(&response))) {
return self.parse_orders(response.clone(), &[]);
} else {
return Value::List(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
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 is_equal(&self.markets, &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.clone());
m
});
let __ws_arg_13 = self.extend(request.clone(), &[params.clone()]);
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.clone()]);
return self.parse_order(order.clone(), &[market.clone()]);
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
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("all".to_string()));
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
add_element_to_object(&mut request, &Value::Str("symbols".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("endTime".to_string()), self.iso8601(until.clone()));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("after".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_get_v2_orders(&[__ws_arg_14]).await;
return self.parse_orders(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
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
* @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".to_string()));
m
});
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
return self.fetch_orders(&[symbol.clone(), since.clone(), limit.clone(), __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
* @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".to_string()));
m
});
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
return self.fetch_orders(&[symbol.clone(), since.clone(), limit.clone(), __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] for crypto trading either 'gtc' or 'ioc' can be used
* @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 is_equal(&self.markets, &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.clone());
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
if !is_equal(&amount, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("qty".to_string()), self.amount_to_precision(symbol.clone(), amount.clone()));
}
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stop_price".to_string()), &[]);
if !is_equal(&triggerPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("stop_price".to_string()), self.price_to_precision(symbol.clone(), triggerPrice.clone()));
params = self.omit(params.clone(), Value::Str("triggerPrice".to_string()), &[]);
}
if !is_equal(&price, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit_price".to_string()), self.price_to_precision(symbol.clone(), price.clone()));
}
let mut timeInForce: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("editOrder".to_string()), Value::Str("timeInForce".to_string()), &[Value::Str("gtc".to_string())]); timeInForce = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&timeInForce, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("time_in_force".to_string()), timeInForce.clone());
}
add_element_to_object(&mut request, &Value::Str("client_order_id".to_string()), self.generate_client_order_id(params.clone()));
params = self.omit(params.clone(), Value::List(vec![Value::Str("clientOrderId".to_string())]), &[]);
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_patch_v2_orders_order_id(&[__ws_arg_17]).await;
return self.parse_order(response.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "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.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut alpacaStatus: Value = self.safe_string_k(order.clone(), "status", &[]);
let mut status: Value = self.parse_order_status(alpacaStatus.clone());
let mut feeValue: Value = self.safe_string_k(order.clone(), "commission", &[]);
let mut fee: Value = Value::Null;
if !is_equal(&feeValue, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeValue.clone());
m.insert("currency".to_string(), Value::Str("USD".to_string()));
m
});
}
let mut orderType: Value = self.safe_string_k(order.clone(), "order_type", &[]);
if !is_equal(&orderType, &Value::Null) {
if is_greater_than_or_equal(&get_index_of(&orderType, &Value::Str("limit".to_string())), &Value::Int(0)) {
// might be limit or stop-limit
orderType = Value::Str("limit".to_string());
}
}
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.clone());
m.insert("datetime".to_string(), datetime.clone());
m.insert("lastTradeTimeStamp".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), orderType.clone());
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.clone());
m.insert("info".to_string(), order.clone());
m
}), &[market.clone()]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pending_new".to_string(), Value::Str("open".to_string()));
m.insert("accepted".to_string(), Value::Str("open".to_string()));
m.insert("new".to_string(), Value::Str("open".to_string()));
m.insert("partially_filled".to_string(), Value::Str("open".to_string()));
m.insert("activated".to_string(), Value::Str("open".to_string()));
m.insert("filled".to_string(), Value::Str("closed".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_time_in_force(&self, mut timeInForce: Value) -> Value {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("day".to_string(), Value::Str("Day".to_string()));
m
});
return self.safe_string(timeInForces.clone(), 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 is_equal(&self.markets, &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".to_string()));
m
});
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("until".to_string()), self.iso8601(until.clone()));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("after".to_string()), self.iso8601(since.clone()));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("page_size".to_string()), limit.clone());
}
{ let __destr_tmp = self.handle_until_option(Value::Str("until".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_get_v2_account_activities_activity_type(&[__ws_arg_18]).await;
return self.parse_trades(response.clone(), &[market.clone(), since.clone(), limit.clone()]);
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".to_string()), Value::Str("symbol".to_string()), &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut datetime: Value = self.safe_string2(trade.clone(), Value::Str("t".to_string()), Value::Str("transaction_time".to_string()), &[]);
let mut timestamp: Value = self.parse8601(datetime.clone());
let mut alpacaSide: Value = self.safe_string_k(trade.clone(), "tks", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if is_equal(&alpacaSide, &Value::Str("B".to_string())) {
side = Value::Str("buy".to_string());
} else if is_equal(&alpacaSide, &Value::Str("S".to_string())) {
side = Value::Str("sell".to_string());
}
let mut priceString: Value = self.safe_string2(trade.clone(), Value::Str("p".to_string()), Value::Str("price".to_string()), &[]);
let mut amountString: Value = self.safe_string2(trade.clone(), Value::Str("s".to_string()), Value::Str("qty".to_string()), &[]);
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string2(trade.clone(), Value::Str("i".to_string()), Value::Str("id".to_string()), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("symbol".to_string(), symbol.clone());
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "order_id", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("takerOrMaker".to_string(), Value::Str("taker".to_string()));
m.insert("price".to_string(), priceString.clone());
m.insert("amount".to_string(), amountString.clone());
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
}), &[market.clone()]);
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m
});
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_get_v2_wallets(&[__ws_arg_19]).await;
return self.parse_deposit_address(response.clone(), &[currency.clone()]);
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 !is_equal(¤cy, &Value::Null) {
parsedCurrency = get_value(¤cy, &Value::Str("id".to_string()));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress.clone());
m.insert("currency".to_string(), parsedCurrency.clone());
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), self.safe_string_k(depositAddress.clone(), "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 = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
self.check_address(&[address.clone()]);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
if is_true(&(!is_equal(&tag, &Value::Null))) && is_true(&(!is_equal(&tag, &Value::Str("".to_string())))) {
address = add(&add(&address, &Value::Str(":".to_string())), &tag);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m.insert("address".to_string(), address.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m
});
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.trader_private_post_v2_wallets_transfers(&[__ws_arg_20]).await;
return self.parse_transaction(response.clone(), &[currency.clone()]);
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
add_element_to_object(&mut self.options, &Value::Str("sandboxMode".to_string()), enable.clone());
}
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
}
let mut sandboxMode: Value = Value::Bool(is_true(&self.isSandboxModeEnabled) || is_true(&self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)])));
if is_equal(&sandboxMode, &Value::Bool(true)) {
// 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".to_string()));
m
});
let __ws_arg_21 = self.extend(request.clone(), &[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::List(vec![]);
let mut ledger: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&activities))) {
ledger = activities.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_214: bool = true;
while { if !__for_first_214 { i = add(&i, &Value::Int(1)); } __for_first_214 = false; is_less_than(&i, &get_array_length(&ledger)) } {
let mut entry: Value = get_value(&ledger, &i);
let mut entry: Value = get_value(&ledger, &i);
let mut activityType: Value = self.safe_string_k(entry.clone(), "activity_type", &[]);
let mut amount: Value = self.safe_string_k(entry.clone(), "net_amount", &[]);
let mut isIncoming: bool = is_true(&(is_equal(&activityType, &Value::Str("CSD".to_string())))) || is_true(&(is_true(&(is_equal(&activityType, &Value::Str("TRANS".to_string())))) && !is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".to_string())))));
let mut entryDirection: Value = ternary(is_true(&isIncoming), Value::Str("INCOMING".to_string()), Value::Str("OUTGOING".to_string()));
if is_true(&(is_equal(&type_var, &Value::Str("BOTH".to_string())))) || is_true(&(is_equal(&entryDirection, &type_var))) {
append_to_array(&mut filtered, entry.clone());
}
}
}
return self.parse_transactions(filtered.clone(), &[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::List(vec![]);
let mut transfers: Value = Value::List(vec![]);
if is_true(&Value::Bool(is_array(&response))) {
transfers = response.clone();
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_215: bool = true;
while { if !__for_first_215 { i = add(&i, &Value::Int(1)); } __for_first_215 = false; is_less_than(&i, &get_array_length(&transfers)) } {
let mut entry: Value = get_value(&transfers, &i);
let mut entry: Value = get_value(&transfers, &i);
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 is_equal(&type_var, &Value::Str("BOTH".to_string())) {
append_to_array(&mut results, entry.clone());
}
}
}
return self.parse_transactions(results.clone(), &[currency.clone(), since.clone(), limit.clone(), params.clone()]);
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".to_string()), code.clone(), since.clone(), limit.clone(), params.clone()).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".to_string()), code.clone(), since.clone(), limit.clone(), params.clone()).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".to_string()), code.clone(), since.clone(), limit.clone(), params.clone()).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 !is_equal(&activityType, &Value::Null) {
let mut netAmount: Value = self.safe_string_k(transaction.clone(), "net_amount", &[]);
let mut isIncoming: bool = is_true(&(is_equal(&activityType, &Value::Str("CSD".to_string())))) || is_true(&(is_true(&(is_equal(&activityType, &Value::Str("TRANS".to_string())))) && !is_true(&crate::precise::Precise::stringLt(&netAmount, &Value::Str("0".to_string())))));
timestamp = self.parse8601(add(&self.safe_string_k(transaction.clone(), "date", &[]), &Value::Str("T00:00:00Z".to_string())));
datetime = self.iso8601(timestamp.clone());
type_var = ternary(is_true(&isIncoming), Value::Str("deposit".to_string()), Value::Str("withdrawal".to_string()));
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".to_string()), Value::Str("asset".to_string()), &[]);
if !is_equal(&activityCurrencyId, &Value::Null) {
code = self.safe_currency_code(activityCurrencyId.clone(), &[]);
} else if is_true(&(is_equal(&activityType, &Value::Str("CSD".to_string())))) || is_true(&(is_equal(&activityType, &Value::Str("CSW".to_string())))) {
code = Value::Str("USD".to_string());
} 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(!is_equal(&activityType, &Value::Str("TRANS".to_string())));
} 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", &[]));
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.clone(), &[currency.clone()]);
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.clone(), &[]));
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.clone(), "id", &[]));
m.insert("txid".to_string(), txid.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), datetime.clone());
m.insert("network".to_string(), network.clone());
m.insert("address".to_string(), address.clone());
m.insert("addressTo".to_string(), addressTo.clone());
m.insert("addressFrom".to_string(), addressFrom.clone());
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), type_var.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("currency".to_string(), code.clone());
m.insert("status".to_string(), status.clone());
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), comment.clone());
m.insert("internal".to_string(), internal.clone());
m.insert("fee".to_string(), fee.clone());
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".to_string()));
m.insert("FAILED".to_string(), Value::Str("failed".to_string()));
m.insert("COMPLETE".to_string(), Value::Str("ok".to_string()));
m.insert("executed".to_string(), Value::Str("ok".to_string()));
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("pending".to_string(), Value::Str("pending".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("INCOMING".to_string(), Value::Str("deposit".to_string()));
m.insert("OUTGOING".to_string(), Value::Str("withdrawal".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
/*
* @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
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.trader_private_get_v2_account(&[params.clone()]).await;
return self.parse_balance(response.clone());
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut account: Value = self.account();
let mut currencyId: Value = self.safe_string_k(response.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
add_element_to_object(&mut account, &Value::Str("free".to_string()), self.safe_string_k(response.clone(), "cash", &[]));
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string_k(response.clone(), "equity", &[]));
if !is_equal(&code, &Value::Null) {
add_element_to_object(&mut result, &code, account.clone());
}
return self.safe_balance(result.clone());
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut endpoint: Value = add(&Value::Str("/".to_string()), &self.implode_params(path.clone(), params.clone()));
let mut url: Value = self.implode_hostname(get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &get_value(&api, &Value::Int(0))));
headers = ternary(is_true(&(!is_equal(&headers, &Value::Null))), headers.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&get_value(&api, &Value::Int(1)), &Value::Str("private".to_string())) {
self.check_required_credentials(&[]);
add_element_to_object(&mut headers, &Value::Str("APCA-API-KEY-ID".to_string()), self.apiKey.clone());
add_element_to_object(&mut headers, &Value::Str("APCA-API-SECRET-KEY".to_string()), self.secret.clone());
}
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
if is_greater_than(&get_array_length(&object_keys(&query)), &Value::Int(0)) {
if is_true(&(is_equal(&method, &Value::Str("GET".to_string())))) || is_true(&(is_equal(&method, &Value::Str("DELETE".to_string())))) {
endpoint = add(&endpoint, &add(&Value::Str("?".to_string()), &self.urlencode(query.clone(), &[])));
} else {
body = self.json(query.clone());
add_element_to_object(&mut headers, &Value::Str("Content-Type".to_string()), Value::Str("application/json".to_string()));
}
}
url = add(&url, &endpoint);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
// {
// "code": 40110000,
// "message": "request is not authorized"
// }
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
let mut errorCode: Value = self.safe_string_k(response.clone(), "code", &[]);
if !is_equal(&code, &Value::Null) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), errorCode.clone(), feedback.clone());
}
let mut message: Value = self.safe_string_k(response.clone(), "message", &[]);
if !is_equal(&message, &Value::Null) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), message.clone(), feedback.clone());
let mut codeAsString: Value = to_string_val(&code);
if is_true(&(is_less_than(&code, &Value::Int(400)))) || !is_true(&(Value::Bool(in_op(&self.httpExceptions, &codeAsString)))) {
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
return Value::Null;
Value::Null
}
}