Alpaca-Py SDK
raw JSON → 0.43.2 verified Fri May 15 auth: no python
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.
pip install alpaca-py Common errors
error ModuleNotFoundError: No module named 'alpaca.data'; 'alpaca' is not a package ↓
cause This error occurs when the script is named 'alpaca.py', causing a naming conflict with the 'alpaca' module.
fix
Rename your script to something other than 'alpaca.py' to avoid the naming conflict.
error ModuleNotFoundError: No module named 'alpaca' ↓
cause This error occurs when the 'alpaca-py' package is not installed or is installed in a different Python environment.
fix
Ensure 'alpaca-py' is installed in the correct environment by running 'pip install alpaca-py'.
error AttributeError: partially initialized module 'charset_normalizer' has no attribute 'md__mypyc' (most likely due to a circular import) ↓
cause This error is due to a circular import issue within the 'charset_normalizer' module.
fix
Upgrade the 'charset_normalizer' package to the latest version using 'pip install --upgrade charset_normalizer'.
error pydantic.error_wrappers.ValidationError: 2 validation errors for Order legs -> 0 -> status value is not a valid enumeration member; permitted: 'new', 'partially_filled', 'filled', 'done_for_day', 'canceled', 'expired', 'replaced', 'pending_cancel', 'pending_replace', 'accepted', 'pending_new', 'accepted_for_bidding', 'stopped', 'rejected', 'suspended', 'calculated' (type=type_error.enum; enum_values=[<OrderStatus.NEW: 'new'>, <OrderStatus.PARTIALLY_FILLED: 'partially_filled'>, <OrderStatus.FILLED: 'filled'>, <OrderStatus.DONE_FOR_DAY: 'done_for_day'>, <OrderStatus.CANCELED: 'canceled'>, <OrderStatus.EXPIRED: 'expired'>, <OrderStatus.REPLACED: 'replaced'>, <OrderStatus.PENDING_CANCEL: 'pending_cancel'>, <OrderStatus.PENDING_REPLACE: 'pending_replace'>, <OrderStatus.ACCEPTED: 'accepted'>, <OrderStatus.PENDING_NEW: 'pending_new'>, <OrderStatus.ACCEPTED_FOR_BIDDING: 'accepted_for_bidding'>, <OrderStatus.STOPPED: 'stopped'>, <OrderStatus.REJECTED: 'rejected'>, <OrderStatus.SUSPENDED: 'suspended'>, <OrderStatus.CALCULATED: 'calculated'>]) ↓
cause This error occurs because the 'held' status of bracket legs is not included in the 'OrderStatus' enumeration in the 'alpaca-py' library.
fix
This error can be ignored as it does not affect the functionality of the order submission.
error SyntaxError: can't assign to operator ↓
cause This error occurs when using hyphens in variable names, which is not allowed in Python.
fix
Replace hyphens with underscores in variable names, e.g., use 'key_id' instead of 'key-id'.
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. ↓
fix Always access data by field/column names (e.g., `response.field_name` or `df['column_name']`) instead of positional indexing.
deprecated The `get_corporate_announcements` method was deprecated in v0.42.1. ↓
fix Use the `get_corporate_actions` method instead for retrieving corporate action data.
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. ↓
fix Review the official `alpaca-py` documentation for updated client initialization, request object patterns, and module import paths. Many examples from the old SDK are incompatible.
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. ↓
fix Consult the `alpaca-py` documentation for the correct request object class corresponding to each API method (e.g., `TradingClient.submit_order` requires a subclass of `OrderRequest`).
gotcha API keys (ALPACA_API_KEY_ID and ALPACA_SECRET_KEY) are crucial for authentication. Hardcoding them is insecure and against best practices. ↓
fix Store API keys securely as environment variables (recommended) or use a secrets management system. The SDK will automatically pick them up if named correctly, or they can be passed explicitly during client initialization.
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. ↓
fix Identify whether you need to perform trading operations, retrieve historical stock data, or historical crypto data, and instantiate the corresponding client (e.g., `TradingClient`, `StockHistoricalDataClient`, `CryptoHistoricalDataClient`).
Install compatibility last tested: 2026-05-15 v0.43.4 (up to date)
python os / libc status wheel install import disk mem side effects
3.10 alpine (musl) wheel - 1.96s 181.7M 41.5M noisy
3.10 slim (glibc) wheel 10.9s 1.48s 174M 41.5M noisy
3.11 alpine (musl) wheel - 2.46s 198.6M 47.0M noisy
3.11 slim (glibc) wheel 9.6s 2.22s 190M 47.0M noisy
3.12 alpine (musl) wheel - 2.39s 183.5M 46.1M noisy
3.12 slim (glibc) wheel 9.3s 2.46s 175M 46.1M noisy
3.13 alpine (musl) wheel - 2.30s 182.5M 49.6M noisy
3.13 slim (glibc) wheel 9.4s 2.19s 174M 49.6M noisy
3.9 alpine (musl) wheel - 1.86s 189.3M 41.9M noisy
3.9 slim (glibc) wheel 13.1s 1.70s 184M 41.9M noisy
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 wrong
import alpaca_trade_apicorrectNot 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}")