Installation (The Easy Part)
pip install alpaca-py
That's it. If this breaks, your Python environment is probably fucked - fix that first.
API Keys Setup (Don't Commit These to GitHub)
Sign up at Alpaca and grab your API keys. You get paper trading keys immediately, live keys after they approve your account.
## Use environment variables or you'll commit your keys to GitHub like an idiot
import os
from alpaca.trading.client import TradingClient
trading_client = TradingClient(
api_key=os.environ['ALPACA_API_KEY'],
secret_key=os.environ['ALPACA_SECRET_KEY'],
paper=True # Start here unless you enjoy losing money
)
Paper trading API keys work differently than live trading - check which environment you're hitting because the URLs are different and you'll get confused.
Basic Order Placement (And What Goes Wrong)
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from alpaca.common.exceptions import APIError
## Create the request first (this catches typos before API calls)
order_request = MarketOrderRequest(
symbol="AAPL",
qty=10,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
## This will fail if markets are closed, you have insufficient funds,
## or Alpaca decides to have "connectivity issues"
try:
order = trading_client.submit_order(order_request)
print(f"Order submitted: {order.id}")
except APIError as e:
# The error messages are usually unhelpful
print(f"Order failed: {e}")
# Common failures:
# - Markets closed (check market hours)
# - Insufficient buying power
# - Symbol not found (check spelling)
# - Position limit exceeded
[Market Data](https://docs.alpaca.markets/docs/market-data-overview) (When It Actually Works)

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime
import time
## Need API keys for stock data (crypto is free though)
data_client = StockHistoricalDataClient(
api_key=os.environ['ALPACA_API_KEY'],
secret_key=os.environ['ALPACA_SECRET_KEY']
)
request = StockBarsRequest(
symbol_or_symbols=["AAPL", "MSFT"],
timeframe=TimeFrame.Day,
start=datetime(2023, 1, 1),
end=datetime(2023, 12, 31)
)
try:
bars = data_client.get_stock_bars(request)
df = bars.df # Converts to Pandas DataFrame
print(f"Got {len(df)} bars")
except APIError as e:
if "rate limit" in str(e).lower():
# You'll hit this if you're polling too aggressively
time.sleep(60) # Wait and try again
else:
print(f"Data request failed: {e}")
[WebSocket Streams](https://docs.alpaca.markets/docs/websocket-streaming) (They Disconnect, Plan for It)

from alpaca.data.live import StockDataStream
## WebSocket connections are fragile - they will disconnect
stream = StockDataStream(
api_key=os.environ['ALPACA_API_KEY'],
secret_key=os.environ['ALPACA_SECRET_KEY']
)
async def quote_data_handler(data):
# This will get called for each quote
print(f"{data.symbol}: ${data.bid_price}")
## Subscribe to quotes
stream.subscribe_quotes(quote_data_handler, "AAPL")
## This will run forever (until it disconnects)
try:
stream.run()
except KeyboardInterrupt:
print("Shutting down...")
except Exception as e:
# Connection dropped - happens all the time
print(f"Stream disconnected: {e}")
# You need to handle reconnection yourself
Production Reality Check
Rate limits will bite you. You get 200 requests per minute for trading, less for data. Build retry logic with exponential backoff or your algorithm will break every time you actually need it to work.
Paper trading vs live is completely different. Your amazing paper trading results mean nothing. Live markets have slippage, partial fills, and random outages during the exact moment your algorithm tries to do something important.
Error handling is critical. The API will fail in creative ways - markets close, your connection drops, Alpaca has "issues", or you run out of buying power. Plan for everything to break at the worst possible time.
Use environment variables for API keys - seriously, don't hardcode them. The SDK figures out if you're using paper or live trading based on which keys you provide, so double-check your configuration or you might accidentally place real trades with your test algorithm.
The Bottom Line
Alpaca-py delivers what it promises: a straightforward way to build trading algorithms without the complexity of traditional broker APIs. The modern Pydantic-based approach prevents many common bugs, and the extensive documentation actually helps instead of confusing you further.
But remember - having a working API client is just the beginning. The hard part is building strategies that actually make money, which is an entirely different challenge. Start with paper trading, expect your live results to be worse, and plan for everything to break at the worst possible moment.