Alpaca API Client for Rust
An unofficial Rust SDK for the Alpaca trading API. This library provides a type-safe, ergonomic interface for accessing Alpaca's Market Data and Trading APIs.
Note: Recommended for Paper Accounts. Use with live accounts at your own risk.
Table of Contents
- Installation
- Configuration
- Quick Start
- Market Data API
- Trading API
- Types & Enums
- Error Handling
- Contributing
- License
Installation
Add to your Cargo.toml:
[]
= "0.6"
Or use cargo:
Configuration
The library uses environment variables for API authentication. Create a .env file in your project root:
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
use ;
Market Data API
All market data queries follow a builder pattern. Construct your query, chain optional parameters, then call .send().
Stocks
Historical Bars
use ;
let bars = new
.start
.end
.feed // "iex" (free) or "sip" (premium)
.limit
.sort_desc
.send?;
// Returns HashMap<String, Vec<StockBar>>
for in &bars
Latest Bars
use LatestBarsQuery;
let bars = new
.feed
.send?;
// Returns HashMap<String, StockBar>
if let Some = bars.get
Quotes
use ;
// Historical quotes
let quotes = new
.start
.limit
.send?;
// Latest quotes
let latest = new
.feed
.send?;
Trades
use ;
// Historical trades
let trades = new
.start
.limit
.send?;
// Latest trades
let latest = new
.send?;
Snapshots
Get a complete market snapshot including latest trade, quote, and bars:
use SnapshotsQuery;
let snapshots = new
.feed
.send?;
if let Some = snapshots.get
Auctions
use HistoricalAuctionsQuery;
let auctions = new
.start
.feed
.send?;
Crypto
Crypto market data uses similar patterns to stocks:
use ;
// Historical bars
let bars = new
.start
.limit
.send?;
// Latest bars
let latest = new
.send?;
// Snapshots
let snapshots = new
.send?;
// Order book
let orderbooks = new
.send?;
if let Some = orderbooks.get
Options
use ;
// Option symbols follow OCC format: AAPL261218C00200000
// (Underlying + YYMMDD + C/P + Strike*1000)
// Historical bars
let bars = new
.send?;
// Latest quotes
let quotes = new
.feed
.send?;
// Option snapshots with Greeks
let snapshots = new
.send?;
if let Some = snapshots.get
// Option chain for underlying
let chain = new
.expiration_date_gte
.expiration_date_lte
.strike_price_gte
.strike_price_lte
.set_type
.limit
.send?;
News
use NewsQuery;
let news = new
.start
.limit
.include_content
.exclude_contentless
.sort_desc
.send?;
for article in &news
Screener
use ;
// Most active stocks
let actives = new
.by // or "trades"
.top
.send?;
for stock in &actives
// Top movers (gainers and losers)
let movers = new
.top
.send?;
println!;
for gainer in &movers.gainers
println!;
for loser in &movers.losers
Trading API
All trading operations require specifying AccountType::Paper or AccountType::Live.
Orders
Create Orders
use ;
// Market order
let order = new
.qty
.send?;
// Limit order
let order = new
.qty
.limit_price
.send?;
// Stop order
let order = new
.qty
.stop_price
.send?;
// Stop-limit order
let order = new
.qty
.stop_price
.limit_price
.send?;
// Trailing stop order
let order = new
.qty
.trail_percent // or .trail_price("10.00")
.send?;
// Bracket order (entry with take-profit and stop-loss)
let order = new
.qty
.order_class
.take_profit
.stop_loss // stop_price, limit_price
.send?;
// One-Triggers-Other (OTO) order
let order = new
.qty
.order_class
.stop_loss
.send?;
Get Orders
use ;
// Get all orders
let orders = new
.status // "open", "closed", "all"
.limit
.symbols
.side // "buy" or "sell"
.direction
.send?;
// Get order by ID
let order = new
.get_by_id?; // true = include nested orders
Cancel Orders
use ;
// Cancel all open orders
let results = delete_all_orders?;
// Cancel specific order
let status = delete_by_id?;
// Returns HTTP status code (204 on success)
Replace Orders
use ;
let order = new
.qty
.limit_price
.time_in_force
.send?;
Positions
use ;
let positions = new;
// Get all open positions
let all = positions.get_all_open_positions?;
for pos in &all
// Get position by symbol
let pos = positions.get_position_by_symbol?;
// Close all positions
let closed = positions.close_all_positions?; // true = cancel open orders
// Close specific position
let order = positions.close_position_by_id_or_symbol?;
Account
use ;
// Get account info
let account = get_account?;
println!;
println!;
println!;
// Get account configuration
let config = get_account_configurations?;
// Update account configuration
let new_config = new
.fractional_trading
.no_shorting
.send?;
Portfolio
use ;
let history = new
.period // 1D, 1W, 1M, 3M, 1A, all
.timeframe
.extended_hours
.send?;
for in history.timestamp.iter.enumerate
Assets
use ;
// Get all tradable assets
let assets = new
.status
.asset_class
.send?;
// Get specific asset
let asset = new
.get_by_symbol?;
println!;
// Get option contracts
let contracts = new
.underlying_symbols
.expiration_date_gte
.limit
.send?;
Clock & Calendar
use ;
// Get market clock
let clock = get_market_clock?;
println!;
println!;
println!;
// Get market calendar
let calendar = new
.start
.end
.send?;
for day in &calendar
Activities
use ;
let activities = new
.activity_types
.after
.direction
.limit
.send?;
for activity in &activities
Types & Enums
TimeFrame
use TimeFrame;
// Available timeframes
OneMinute // "1Min"
FiveMinutes // "5Min"
FifteenMinutes // "15Min"
ThirtyMinutes // "30Min"
OneHour // "1H"
FourHours // "4H"
OneDay // "1D"
OneWeek // "1W"
OneMonth // "1M"
Order Enums
use ;
// Order sides
Buy
Sell
// Order types
Market
Limit
Stop
StopLimit
TrailingStop
// Time in force
Day // Day order
GoodTilCanceled // GTC
OpeningOrder // OPG - execute at market open
ClosingOrder // CLS - execute at market close
ImmediateOrCancel // IOC
FillOrKill // FOK
// Order classes
Simple
Bracket
OneCancelsOther
OneTriggersOther
Account Type
use AccountType;
Paper // Paper trading (sandbox)
Live // Live trading (real money)
StreamBar (for WebSocket integration)
use StreamBar;
// Used for parsing WebSocket bar data
Error Handling
All API calls return Result<T, ureq::Error>. Handle errors appropriately:
use ;
match new.send
Common error scenarios:
StatusCode(401)- Invalid API credentialsStatusCode(403)- Forbidden (insufficient permissions)StatusCode(404)- Resource not foundStatusCode(422)- Invalid request parametersStatusCode(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.
License
This project is dual-licensed under MIT and Apache 2.0. See LICENSE-MIT and LICENSE-APACHE.