1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! Alpaca API endpoints
use crate::core::types::Symbol;
/// Base URLs for Alpaca
pub struct AlpacaEndpoints {
pub trading_base: &'static str,
pub market_data_base: &'static str,
pub _ws_market_data: &'static str,
pub _ws_trading: &'static str,
}
impl AlpacaEndpoints {
/// Production (live trading)
pub fn live() -> Self {
Self {
trading_base: "https://api.alpaca.markets",
market_data_base: "https://data.alpaca.markets",
_ws_market_data: "wss://stream.data.alpaca.markets",
_ws_trading: "wss://api.alpaca.markets/stream",
}
}
/// Paper trading (free, global)
pub fn paper() -> Self {
Self {
trading_base: "https://paper-api.alpaca.markets",
market_data_base: "https://data.alpaca.markets",
_ws_market_data: "wss://stream.data.alpaca.markets",
_ws_trading: "wss://paper-api.alpaca.markets/stream",
}
}
/// Sandbox (development)
pub fn _sandbox() -> Self {
Self {
trading_base: "https://paper-api.alpaca.markets",
market_data_base: "https://data.sandbox.alpaca.markets",
_ws_market_data: "wss://stream.data.sandbox.alpaca.markets",
_ws_trading: "wss://paper-api.alpaca.markets/stream",
}
}
}
impl Default for AlpacaEndpoints {
fn default() -> Self {
Self::paper() // Safe default for testing
}
}
/// API endpoint enum
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum AlpacaEndpoint {
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Account Management
// ═══════════════════════════════════════════════════════════════════════
Account,
AccountPortfolioHistory,
AccountActivities,
/// GET /v2/account/activities/{activity_type}
AccountActivitiesByType(String),
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Orders
// ═══════════════════════════════════════════════════════════════════════
Orders,
OrderById(String),
OrderByClientId(String),
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Positions
// ═══════════════════════════════════════════════════════════════════════
Positions,
PositionBySymbol(String),
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Assets & Market Info
// ═══════════════════════════════════════════════════════════════════════
Assets,
AssetBySymbol(String),
OptionContracts,
Calendar,
Clock,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Stock Bars
// ═══════════════════════════════════════════════════════════════════════
StockBars,
StockBarsLatest,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Stock Trades
// ═══════════════════════════════════════════════════════════════════════
StockTrades,
StockTradesLatest,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Stock Quotes
// ═══════════════════════════════════════════════════════════════════════
StockQuotes,
StockQuotesLatest,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Snapshots
// ═══════════════════════════════════════════════════════════════════════
StockSnapshots,
StockSnapshotBySymbol(String),
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Options
// ═══════════════════════════════════════════════════════════════════════
OptionsSnapshots(String), // underlying symbol
OptionsBars,
OptionsTrades,
OptionsQuotes,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Crypto
// ═══════════════════════════════════════════════════════════════════════
CryptoBars,
CryptoTrades,
CryptoQuotes,
CryptoOrderbooks,
CryptoSnapshots,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - News
// ═══════════════════════════════════════════════════════════════════════
News,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Corporate Actions
// ═══════════════════════════════════════════════════════════════════════
CorporateActions,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Screener
// ═══════════════════════════════════════════════════════════════════════
Movers,
/// GET /v1beta1/screener/most-actives
MostActives,
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Watchlists
// ═══════════════════════════════════════════════════════════════════════
/// GET /v2/watchlists — list all watchlists
Watchlists,
/// GET/PUT/DELETE /v2/watchlists/{id}
WatchlistById(String),
/// POST /v2/watchlists/{id} — add symbol to watchlist
WatchlistAddSymbol(String),
// ═══════════════════════════════════════════════════════════════════════
// TRADING API - Account Configurations
// ═══════════════════════════════════════════════════════════════════════
/// GET/PATCH /v2/account/configurations
AccountConfigurations,
// ═══════════════════════════════════════════════════════════════════════
// MARKET DATA API - Options Chain
// ═══════════════════════════════════════════════════════════════════════
/// GET /v1beta1/options/chain — options chain for a symbol
OptionsChain,
}
impl AlpacaEndpoint {
/// Get endpoint path and base URL type
///
/// Returns a String instead of &'static str because some paths are dynamic
pub fn path(&self) -> (String, EndpointBase) {
match self {
// Trading API
Self::Account => ("/v2/account".to_string(), EndpointBase::Trading),
Self::AccountPortfolioHistory => ("/v2/account/portfolio/history".to_string(), EndpointBase::Trading),
Self::AccountActivities => ("/v2/account/activities".to_string(), EndpointBase::Trading),
Self::AccountActivitiesByType(activity_type) => (format!("/v2/account/activities/{}", activity_type), EndpointBase::Trading),
Self::Orders => ("/v2/orders".to_string(), EndpointBase::Trading),
Self::OrderById(id) => (format!("/v2/orders/{}", id), EndpointBase::Trading),
Self::OrderByClientId(id) => (format!("/v2/orders:by_client_order_id?client_order_id={}", id), EndpointBase::Trading),
Self::Positions => ("/v2/positions".to_string(), EndpointBase::Trading),
Self::PositionBySymbol(symbol) => (format!("/v2/positions/{}", symbol), EndpointBase::Trading),
Self::Assets => ("/v2/assets".to_string(), EndpointBase::Trading),
Self::AssetBySymbol(symbol) => (format!("/v2/assets/{}", symbol), EndpointBase::Trading),
Self::OptionContracts => ("/v2/option_contracts".to_string(), EndpointBase::Trading),
Self::Calendar => ("/v2/calendar".to_string(), EndpointBase::Trading),
Self::Clock => ("/v2/clock".to_string(), EndpointBase::Trading),
// Market Data API - Stocks
Self::StockBars => ("/v2/stocks/bars".to_string(), EndpointBase::MarketData),
Self::StockBarsLatest => ("/v2/stocks/bars/latest".to_string(), EndpointBase::MarketData),
Self::StockTrades => ("/v2/stocks/trades".to_string(), EndpointBase::MarketData),
Self::StockTradesLatest => ("/v2/stocks/trades/latest".to_string(), EndpointBase::MarketData),
Self::StockQuotes => ("/v2/stocks/quotes".to_string(), EndpointBase::MarketData),
Self::StockQuotesLatest => ("/v2/stocks/quotes/latest".to_string(), EndpointBase::MarketData),
Self::StockSnapshots => ("/v2/stocks/snapshots".to_string(), EndpointBase::MarketData),
Self::StockSnapshotBySymbol(symbol) => (format!("/v2/stocks/{}/snapshot", symbol), EndpointBase::MarketData),
// Market Data API - Options
Self::OptionsSnapshots(underlying) => (format!("/v1beta1/options/snapshots/{}", underlying), EndpointBase::MarketData),
Self::OptionsBars => ("/v1beta1/options/bars".to_string(), EndpointBase::MarketData),
Self::OptionsTrades => ("/v1beta1/options/trades".to_string(), EndpointBase::MarketData),
Self::OptionsQuotes => ("/v1beta1/options/quotes".to_string(), EndpointBase::MarketData),
// Market Data API - Crypto
Self::CryptoBars => ("/v1beta3/crypto/us/bars".to_string(), EndpointBase::MarketData),
Self::CryptoTrades => ("/v1beta3/crypto/us/trades".to_string(), EndpointBase::MarketData),
Self::CryptoQuotes => ("/v1beta3/crypto/us/quotes".to_string(), EndpointBase::MarketData),
Self::CryptoOrderbooks => ("/v1beta3/crypto/us/latest/orderbooks".to_string(), EndpointBase::MarketData),
Self::CryptoSnapshots => ("/v1beta3/crypto/us/snapshots".to_string(), EndpointBase::MarketData),
// Market Data API - News & Corporate Actions
Self::News => ("/v1beta1/news".to_string(), EndpointBase::MarketData),
Self::CorporateActions => ("/v1beta1/corporate-actions/announcements".to_string(), EndpointBase::MarketData),
// Market Data API - Screener
Self::Movers => ("/v1beta1/screener/stocks/movers".to_string(), EndpointBase::MarketData),
Self::MostActives => ("/v1beta1/screener/most-actives".to_string(), EndpointBase::MarketData),
// Trading API - Watchlists
Self::Watchlists => ("/v2/watchlists".to_string(), EndpointBase::Trading),
Self::WatchlistById(id) => (format!("/v2/watchlists/{}", id), EndpointBase::Trading),
Self::WatchlistAddSymbol(id) => (format!("/v2/watchlists/{}", id), EndpointBase::Trading),
// Trading API - Account Configurations
Self::AccountConfigurations => ("/v2/account/configurations".to_string(), EndpointBase::Trading),
// Market Data API - Options Chain
Self::OptionsChain => ("/v1beta1/options/chain".to_string(), EndpointBase::MarketData),
}
}
}
/// Endpoint base URL type
#[derive(Debug, Clone, Copy)]
pub enum EndpointBase {
Trading,
MarketData,
}
/// Format symbol for Alpaca API
///
/// Alpaca uses different formats for different asset classes:
/// - Stocks: Just ticker symbol (e.g., "AAPL")
/// - Crypto: Base/Quote format (e.g., "BTC/USD")
pub fn format_symbol(symbol: &Symbol) -> String {
// Crypto symbols are detected by short base names (BTC, ETH, etc.)
// Stock tickers are typically longer (AAPL, MSFT, etc.)
// Common crypto bases: BTC, ETH, SOL, AVAX, etc.
let common_crypto = [
"BTC", "ETH", "SOL", "AVAX", "DOGE", "LTC", "BCH", "XLM",
"LINK", "UNI", "AAVE", "SUSHI", "SHIB", "DOT", "MATIC", "ADA",
"XRP", "BNB", "USDT", "USDC", "DAI"
];
let base_upper = symbol.base.to_uppercase();
// If it's a known crypto, always use BASE/QUOTE format
if common_crypto.contains(&base_upper.as_str()) {
format!("{}/{}", base_upper, symbol.quote.to_uppercase())
} else if symbol.quote.is_empty() || symbol.quote == "USD" {
// Stock ticker - just base
base_upper
} else {
// Other crypto or forex - use BASE/QUOTE format
format!("{}/{}", base_upper, symbol.quote.to_uppercase())
}
}
/// Parse symbol from Alpaca API format back to domain Symbol
pub fn _parse_symbol(api_symbol: &str) -> Symbol {
if let Some((base, quote)) = api_symbol.split_once('/') {
// Crypto format: "BTC/USD"
Symbol::new(base, quote)
} else {
// Stock format: "AAPL" (assume USD quote)
Symbol::new(api_symbol, "USD")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_symbol_stock() {
let symbol = Symbol::new("AAPL", "USD");
assert_eq!(format_symbol(&symbol), "AAPL");
}
#[test]
fn test_format_symbol_crypto() {
let symbol = Symbol::new("BTC", "USD");
assert_eq!(format_symbol(&symbol), "BTC/USD");
}
#[test]
fn test_parse_symbol_stock() {
let symbol = _parse_symbol("AAPL");
assert_eq!(symbol.base, "AAPL");
assert_eq!(symbol.quote, "USD");
}
#[test]
fn test_parse_symbol_crypto() {
let symbol = _parse_symbol("BTC/USD");
assert_eq!(symbol.base, "BTC");
assert_eq!(symbol.quote, "USD");
}
}