alpaca_api_client 0.8.0

Unofficial Alpaca API Client
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
# Alpaca API Client for Rust

An unofficial Rust SDK for the [Alpaca](https://alpaca.markets/) trading API. This library provides a type-safe, ergonomic interface for accessing Alpaca's Market Data and Trading APIs.

![Build Status](https://img.shields.io/badge/build-passing-green.svg) ![Version 0.6.4](https://img.shields.io/badge/version-0.6.4-blue.svg) ![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)

> **Note:** Recommended for Paper Accounts. Use with live accounts at your own risk.

## Table of Contents

- [Installation]#installation
- [Configuration]#configuration
- [Quick Start]#quick-start
- [Market Data API]#market-data-api
  - [Stocks]#stocks
  - [Crypto]#crypto
  - [Options]#options
  - [News]#news
  - [Screener]#screener
- [Trading API]#trading-api
  - [Orders]#orders
  - [Positions]#positions
  - [Account]#account
  - [Portfolio]#portfolio
  - [Assets]#assets
  - [Clock & Calendar]#clock--calendar
  - [Activities]#activities
- [Types & Enums]#types--enums
- [Error Handling]#error-handling
- [Contributing]#contributing
- [License]#license

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
alpaca_api_client = "0.6"
```

Or use cargo:

```bash
cargo add alpaca_api_client
```

## Configuration

The library uses environment variables for API authentication. Create a `.env` file in your project root:

```bash
APCA_API_KEY_ID=your_api_key_id
APCA_API_SECRET_KEY=your_api_secret_key
```

Or set them directly in your environment. The library uses `dotenvy` to load these automatically.

## Quick Start

```rust
use alpaca_api_client::{
    trading::{AccountType, order::{CreateOrderQuery, OrderSide, OrderType, TimeInForce}},
    market_data::stocks::LatestBarsQuery,
};

fn main() -> Result<(), ureq::Error> {
    // Get latest stock prices
    let bars = LatestBarsQuery::new(vec!["AAPL", "GOOGL"])
        .feed("iex")
        .send()?;

    println!("AAPL price: {:?}", bars.get("AAPL"));

    // Place a market order
    let order = CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::Day)
        .qty("1")
        .send(AccountType::Paper)?;

    println!("Order placed: {}", order.id);

    Ok(())
}
```

---

## Market Data API

All market data queries follow a builder pattern. Construct your query, chain optional parameters, then call `.send()`.

### Stocks

#### Historical Bars

```rust
use alpaca_api_client::{market_data::stocks::HistoricalBarsQuery, TimeFrame};

let bars = HistoricalBarsQuery::new(vec!["AAPL", "TSLA"], TimeFrame::OneDay)
    .start("2024-01-01")
    .end("2024-01-31")
    .feed("iex")        // "iex" (free) or "sip" (premium)
    .limit(100)
    .sort_desc()
    .send()?;

// Returns HashMap<String, Vec<StockBar>>
for (symbol, bars) in &bars {
    println!("{}: {} bars", symbol, bars.len());
}
```

#### Latest Bars

```rust
use alpaca_api_client::market_data::stocks::LatestBarsQuery;

let bars = LatestBarsQuery::new(vec!["AAPL", "TSLA"])
    .feed("iex")
    .send()?;

// Returns HashMap<String, StockBar>
if let Some(bar) = bars.get("AAPL") {
    println!("AAPL - Open: {}, High: {}, Low: {}, Close: {}", bar.o, bar.h, bar.l, bar.c);
}
```

#### Quotes

```rust
use alpaca_api_client::market_data::stocks::{HistoricalQuotesQuery, LatestQuotesQuery};

// Historical quotes
let quotes = HistoricalQuotesQuery::new(vec!["AAPL"])
    .start("2024-01-01")
    .limit(100)
    .send()?;

// Latest quotes
let latest = LatestQuotesQuery::new(vec!["AAPL", "GOOGL"])
    .feed("iex")
    .send()?;
```

#### Trades

```rust
use alpaca_api_client::market_data::stocks::{HistoricalTradesQuery, LatestTradesQuery};

// Historical trades
let trades = HistoricalTradesQuery::new(vec!["AAPL"])
    .start("2024-01-01")
    .limit(100)
    .send()?;

// Latest trades
let latest = LatestTradesQuery::new(vec!["AAPL"])
    .send()?;
```

#### Snapshots

Get a complete market snapshot including latest trade, quote, and bars:

```rust
use alpaca_api_client::market_data::stocks::SnapshotsQuery;

let snapshots = SnapshotsQuery::new(vec!["AAPL", "GOOGL"])
    .feed("iex")
    .send()?;

if let Some(snapshot) = snapshots.get("AAPL") {
    if let Some(trade) = &snapshot.latest_trade {
        println!("Latest trade price: {}", trade.p);
    }
}
```

#### Auctions

```rust
use alpaca_api_client::market_data::stocks::HistoricalAuctionsQuery;

let auctions = HistoricalAuctionsQuery::new(vec!["AAPL"])
    .start("2024-01-01")
    .feed("sip")
    .send()?;
```

### Crypto

Crypto market data uses similar patterns to stocks:

```rust
use alpaca_api_client::{
    market_data::crypto::{
        HistoricalCryptoBarsQuery, LatestCryptoBarsQuery,
        HistoricalCryptoTradesQuery, LatestCryptoTradesQuery,
        HistoricalCryptoQuotesQuery, LatestCryptoQuotesQuery,
        SnapshotsQuery, OrderbookQuery,
    },
    TimeFrame,
};

// Historical bars
let bars = HistoricalCryptoBarsQuery::new(vec!["BTC/USD", "ETH/USD"], TimeFrame::OneHour)
    .start("2024-01-01")
    .limit(100)
    .send()?;

// Latest bars
let latest = LatestCryptoBarsQuery::new(vec!["BTC/USD"])
    .send()?;

// Snapshots
let snapshots = SnapshotsQuery::new(vec!["BTC/USD"])
    .send()?;

// Order book
let orderbooks = OrderbookQuery::new(vec!["BTC/USD"])
    .send()?;

if let Some(book) = orderbooks.get("BTC/USD") {
    println!("Best bid: {:?}", book.b.first());
    println!("Best ask: {:?}", book.a.first());
}
```

### Options

```rust
use alpaca_api_client::{
    market_data::options::{
        HistoricalOptionBarsQuery, HistoricalOptionTradesQuery,
        LatestOptionTradesQuery, LatestOptionQuotesQuery,
        OptionSnapshotQuery, OptionChainQuery,
    },
    TimeFrame,
};

// Option symbols follow OCC format: AAPL261218C00200000
// (Underlying + YYMMDD + C/P + Strike*1000)

// Historical bars
let bars = HistoricalOptionBarsQuery::new(vec!["AAPL261218C00200000"], TimeFrame::OneDay)
    .send()?;

// Latest quotes
let quotes = LatestOptionQuotesQuery::new(vec!["AAPL261218C00200000"])
    .feed("indicative")
    .send()?;

// Option snapshots with Greeks
let snapshots = OptionSnapshotQuery::new(vec!["AAPL261218C00200000"])
    .send()?;

if let Some(snap) = snapshots.get("AAPL261218C00200000") {
    if let Some(greeks) = &snap.greeks {
        println!("Delta: {}, Gamma: {}, Theta: {}", greeks.delta, greeks.gamma, greeks.theta);
    }
}

// Option chain for underlying
let chain = OptionChainQuery::new("AAPL")
    .expiration_date_gte("2024-06-01")
    .expiration_date_lte("2024-12-31")
    .strike_price_gte(150.0)
    .strike_price_lte(250.0)
    .set_type("call")
    .limit(50)
    .send()?;
```

### News

```rust
use alpaca_api_client::market_data::news::NewsQuery;

let news = NewsQuery::new(vec!["AAPL", "TSLA"])
    .start("2024-01-01")
    .limit(10)
    .include_content(true)
    .exclude_contentless(true)
    .sort_desc()
    .send()?;

for article in &news {
    println!("{} - {}", article.created_at, article.headline);
}
```

### Screener

```rust
use alpaca_api_client::market_data::screener::{ActiveStocksQuery, TopMoversQuery, MarketType};

// Most active stocks
let actives = ActiveStocksQuery::new()
    .by("volume")  // or "trades"
    .top(10)
    .send()?;

for stock in &actives {
    println!("{}: {} volume", stock.symbol, stock.volume);
}

// Top movers (gainers and losers)
let movers = TopMoversQuery::new(MarketType::Stocks)
    .top(10)
    .send()?;

println!("Top Gainers:");
for gainer in &movers.gainers {
    println!("  {}: +{:.2}%", gainer.symbol, gainer.percent_change);
}

println!("Top Losers:");
for loser in &movers.losers {
    println!("  {}: {:.2}%", loser.symbol, loser.percent_change);
}
```

---

## Trading API

All trading operations require specifying `AccountType::Paper` or `AccountType::Live`.

### Orders

#### Create Orders

```rust
use alpaca_api_client::trading::{
    AccountType,
    order::{CreateOrderQuery, OrderSide, OrderType, OrderClass, TimeInForce, TakeProfit, StopLoss},
};

// Market order
let order = CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::Day)
    .qty("10")
    .send(AccountType::Paper)?;

// Limit order
let order = CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Limit, TimeInForce::GoodTilCanceled)
    .qty("10")
    .limit_price("150.00")
    .send(AccountType::Paper)?;

// Stop order
let order = CreateOrderQuery::new("AAPL", OrderSide::Sell, OrderType::Stop, TimeInForce::GoodTilCanceled)
    .qty("10")
    .stop_price("140.00")
    .send(AccountType::Paper)?;

// Stop-limit order
let order = CreateOrderQuery::new("AAPL", OrderSide::Sell, OrderType::StopLimit, TimeInForce::GoodTilCanceled)
    .qty("10")
    .stop_price("140.00")
    .limit_price("139.00")
    .send(AccountType::Paper)?;

// Trailing stop order
let order = CreateOrderQuery::new("AAPL", OrderSide::Sell, OrderType::TrailingStop, TimeInForce::GoodTilCanceled)
    .qty("10")
    .trail_percent("5")  // or .trail_price("10.00")
    .send(AccountType::Paper)?;

// Bracket order (entry with take-profit and stop-loss)
let order = CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::GoodTilCanceled)
    .qty("10")
    .order_class(OrderClass::Bracket)
    .take_profit(TakeProfit::new("200.00"))
    .stop_loss(StopLoss::new("140.00", "139.00"))  // stop_price, limit_price
    .send(AccountType::Paper)?;

// One-Triggers-Other (OTO) order
let order = CreateOrderQuery::new("AAPL", OrderSide::Buy, OrderType::Market, TimeInForce::GoodTilCanceled)
    .qty("10")
    .order_class(OrderClass::OneTriggersOther)
    .stop_loss(StopLoss::new("140.00", "139.00"))
    .send(AccountType::Paper)?;
```

#### Get Orders

```rust
use alpaca_api_client::trading::{AccountType, order::GetOrdersQuery};

// Get all orders
let orders = GetOrdersQuery::new(AccountType::Paper)
    .status("open")  // "open", "closed", "all"
    .limit(100)
    .symbols(vec!["AAPL", "TSLA"])
    .side("buy")     // "buy" or "sell"
    .direction("desc")
    .send()?;

// Get order by ID
let order = GetOrdersQuery::new(AccountType::Paper)
    .get_by_id("order-uuid-here", true)?;  // true = include nested orders
```

#### Cancel Orders

```rust
use alpaca_api_client::trading::{AccountType, order::{delete_all_orders, delete_by_id}};

// Cancel all open orders
let results = delete_all_orders(AccountType::Paper)?;

// Cancel specific order
let status = delete_by_id("order-uuid-here", AccountType::Paper)?;
// Returns HTTP status code (204 on success)
```

#### Replace Orders

```rust
use alpaca_api_client::trading::{AccountType, order::{ReplaceOrderQuery, TimeInForce}};

let order = ReplaceOrderQuery::new("order-uuid-here")
    .qty("20")
    .limit_price("155.00")
    .time_in_force(TimeInForce::GoodTilCanceled)
    .send(AccountType::Paper)?;
```

### Positions

```rust
use alpaca_api_client::trading::{AccountType, positions::PositionsQuery};

let positions = PositionsQuery::new(AccountType::Paper);

// Get all open positions
let all = positions.get_all_open_positions()?;

for pos in &all {
    println!("{}: {} shares, P&L: {}", pos.symbol, pos.qty, pos.unrealized_pl);
}

// Get position by symbol
let pos = positions.get_position_by_symbol("AAPL")?;

// Close all positions
let closed = positions.close_all_positions(true)?;  // true = cancel open orders

// Close specific position
let order = positions.close_position_by_id_or_symbol(
    "AAPL",
    Some(5.0),   // qty to close (optional)
    None,        // percentage to close (optional)
)?;
```

### Account

```rust
use alpaca_api_client::trading::{AccountType, account::{get_account, get_account_configurations, PatchAccountConfigQuery}};

// Get account info
let account = get_account(AccountType::Paper)?;
println!("Buying power: {}", account.buying_power);
println!("Portfolio value: {}", account.portfolio_value);
println!("Cash: {}", account.cash);

// Get account configuration
let config = get_account_configurations(AccountType::Paper)?;

// Update account configuration
let new_config = PatchAccountConfigQuery::new()
    .fractional_trading(true)
    .no_shorting(false)
    .send(AccountType::Paper)?;
```

### Portfolio

```rust
use alpaca_api_client::{trading::{AccountType, portfolio::PortfolioHistoryQuery}, TimeFrame};

let history = PortfolioHistoryQuery::new(AccountType::Paper)
    .period("1M")  // 1D, 1W, 1M, 3M, 1A, all
    .timeframe(TimeFrame::OneDay)
    .extended_hours("true")
    .send()?;

for (i, timestamp) in history.timestamp.iter().enumerate() {
    println!("Time: {}, Equity: {}, P&L: {}",
        timestamp,
        history.equity[i],
        history.profit_loss[i]
    );
}
```

### Assets

```rust
use alpaca_api_client::trading::{AccountType, assets::{AssetsQuery, OptionContractsQuery}};

// Get all tradable assets
let assets = AssetsQuery::new(AccountType::Paper)
    .status("active")
    .asset_class("us_equity")
    .send()?;

// Get specific asset
let asset = AssetsQuery::new(AccountType::Paper)
    .get_by_symbol("AAPL")?;

println!("{} - Tradable: {}, Fractionable: {}", asset.symbol, asset.tradable, asset.fractionable);

// Get option contracts
let contracts = OptionContractsQuery::new(AccountType::Paper)
    .underlying_symbols(vec!["AAPL"])
    .expiration_date_gte("2024-06-01")
    .limit(50)
    .send()?;
```

### Clock & Calendar

```rust
use alpaca_api_client::trading::{AccountType, clock::get_market_clock, calendar::CalendarQuery};

// Get market clock
let clock = get_market_clock(AccountType::Paper)?;
println!("Market is {}", if clock.is_open { "OPEN" } else { "CLOSED" });
println!("Next open: {}", clock.next_open);
println!("Next close: {}", clock.next_close);

// Get market calendar
let calendar = CalendarQuery::new(AccountType::Paper)
    .start("2024-01-01")
    .end("2024-12-31")
    .send()?;

for day in &calendar {
    println!("{}: {} - {}", day.date, day.open, day.close);
}
```

### Activities

```rust
use alpaca_api_client::trading::{AccountType, activities::ActivitiesQuery};

let activities = ActivitiesQuery::new(AccountType::Paper)
    .activity_types(vec!["FILL", "TRANS"])
    .after("2024-01-01")
    .direction("desc")
    .limit(100)
    .send()?;

for activity in &activities {
    println!("{:?}: {} {:?}", activity.activity_type, activity.symbol.as_deref().unwrap_or("N/A"), activity.qty);
}
```

---

## Types & Enums

### TimeFrame

```rust
use alpaca_api_client::TimeFrame;

// Available timeframes
TimeFrame::OneMinute      // "1Min"
TimeFrame::FiveMinutes    // "5Min"
TimeFrame::FifteenMinutes // "15Min"
TimeFrame::ThirtyMinutes  // "30Min"
TimeFrame::OneHour        // "1H"
TimeFrame::FourHours      // "4H"
TimeFrame::OneDay         // "1D"
TimeFrame::OneWeek        // "1W"
TimeFrame::OneMonth       // "1M"
```

### Order Enums

```rust
use alpaca_api_client::trading::order::{OrderSide, OrderType, TimeInForce, OrderClass};

// Order sides
OrderSide::Buy
OrderSide::Sell

// Order types
OrderType::Market
OrderType::Limit
OrderType::Stop
OrderType::StopLimit
OrderType::TrailingStop

// Time in force
TimeInForce::Day              // Day order
TimeInForce::GoodTilCanceled  // GTC
TimeInForce::OpeningOrder     // OPG - execute at market open
TimeInForce::ClosingOrder     // CLS - execute at market close
TimeInForce::ImmediateOrCancel // IOC
TimeInForce::FillOrKill       // FOK

// Order classes
OrderClass::Simple
OrderClass::Bracket
OrderClass::OneCancelsOther
OrderClass::OneTriggersOther
```

### Account Type

```rust
use alpaca_api_client::trading::AccountType;

AccountType::Paper  // Paper trading (sandbox)
AccountType::Live   // Live trading (real money)
```

### StreamBar (for WebSocket integration)

```rust
use alpaca_api_client::StreamBar;

// Used for parsing WebSocket bar data
pub struct StreamBar {
    pub bar_type: String,
    pub symbol: String,
    pub o: f32,    // open
    pub h: f32,    // high
    pub l: f32,    // low
    pub c: f32,    // close
    pub v: u32,    // volume
    pub t: String, // timestamp
    pub n: u32,    // number of trades
    pub vw: f32,   // volume weighted average
}
```

---

## Error Handling

All API calls return `Result<T, ureq::Error>`. Handle errors appropriately:

```rust
use alpaca_api_client::trading::{AccountType, order::GetOrdersQuery};

match GetOrdersQuery::new(AccountType::Paper).send() {
    Ok(orders) => {
        println!("Found {} orders", orders.len());
    }
    Err(e) => {
        eprintln!("API error: {}", e);
    }
}
```

Common error scenarios:
- `StatusCode(401)` - Invalid API credentials
- `StatusCode(403)` - Forbidden (insufficient permissions)
- `StatusCode(404)` - Resource not found
- `StatusCode(422)` - Invalid request parameters
- `StatusCode(429)` - Rate limited

---

## Contributing

Contributions are welcome! Areas that need work:

- Broker API implementation
- WebSocket streaming support
- Additional documentation and examples

Please submit PRs to [GitHub](https://github.com/jonkarrer/alpaca_api_client).

## License

This project is dual-licensed under MIT and Apache 2.0. See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE).

---

## Resources

- [Alpaca Documentation]https://docs.alpaca.markets/
- [Market Data API Docs]https://docs.alpaca.markets/docs/about-market-data-api
- [Trading API Docs]https://docs.alpaca.markets/docs/trading-api
- [API Reference on docs.rs]https://docs.rs/alpaca_api_client