Alpaca-Py SDK
Alpaca-py is the official Python SDK for interacting with Alpaca's comprehensive suite of APIs, including Trading, Market Data, and Broker services. It enables developers to build sophisticated algorithmic trading strategies, access real-time and historical market data for stocks, crypto, and options, and even develop custom investment applications. The library features an object-oriented design, leveraging request objects for API calls and Pydantic for robust data validation. It is actively maintained with a rapid release cadence, ensuring support for new Alpaca API features and improvements.
Warnings
- breaking The `get_corporate_actions` method's response structure changed significantly in v0.42.0 to include ID/CUSIPs fields, potentially altering the order of response/dataframe columns. Relying on column order is no longer safe.
- deprecated The `get_corporate_announcements` method was deprecated in v0.42.1.
- breaking Migration from the older `alpaca-trade-api` SDK to `alpaca-py` involves significant architectural changes, including a new object-oriented design and different import paths.
- gotcha Alpaca-py utilizes an object-oriented design where most API calls require specific 'request objects' (e.g., `MarketOrderRequest`, `StockBarsRequest`) instead of direct keyword arguments. Failing to provide the correct request object will result in errors.
- gotcha API keys (ALPACA_API_KEY_ID and ALPACA_SECRET_KEY) are crucial for authentication. Hardcoding them is insecure and against best practices.
- gotcha Alpaca-py employs multiple client classes for different API services and asset types (e.g., `TradingClient`, `StockHistoricalDataClient`, `CryptoHistoricalDataClient`). You must instantiate the correct client for your desired operation.
Install
-
pip install alpaca-py
Imports
- TradingClient
from alpaca.trading.client import TradingClient
- StockHistoricalDataClient
from alpaca.data.historical import StockHistoricalDataClient
- MarketOrderRequest
from alpaca.trading.requests import MarketOrderRequest
- OrderSide
from alpaca.trading.enums import OrderSide
- TimeFrame
from alpaca.data.timeframe import TimeFrame
- StockBarsRequest
from alpaca.data.requests import StockBarsRequest
- alpaca_trade_api
Not applicable in alpaca-py
Quickstart
import os
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
# Ensure API keys are set as environment variables for security
API_KEY = os.environ.get('ALPACA_API_KEY_ID', '')
API_SECRET = os.environ.get('ALPACA_SECRET_KEY', '')
if not API_KEY or not API_SECRET:
print("Error: ALPACA_API_KEY_ID and ALPACA_SECRET_KEY environment variables must be set.")
exit()
# Initialize TradingClient (paper=True for paper trading account)
trading_client = TradingClient(api_key=API_KEY, secret_key=API_SECRET, paper=True)
try:
# Get account information
account = trading_client.get_account()
print(f"Account ID: {account.id}")
print(f"Status: {account.status}")
print(f"Equity: {account.equity}")
# Place a market order (example: buy 1 share of AAPL)
market_order_data = MarketOrderRequest(
symbol='AAPL',
qty=1,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
market_order = trading_client.submit_order(market_order_data)
print(f"\nSubmitted Market Order:")
print(f" Order ID: {market_order.id}")
print(f" Symbol: {market_order.symbol}")
print(f" Side: {market_order.side}")
print(f" Quantity: {market_order.qty}")
except Exception as e:
print(f"An error occurred: {e}")