or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

broker-client.mddata-client.mdindex.mdtrading-client.md
tile.json

tessl/pypi-alpaca-py

The Official Python SDK for Alpaca APIs providing access to trading, market data, and broker services

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/alpaca-py@0.42.x

To install, run

npx @tessl/cli install tessl/pypi-alpaca-py@0.42.0

index.mddocs/

alpaca-py Python SDK

alpaca-py is the official Python SDK for Alpaca's commission-free trading API. It provides a comprehensive set of tools for algorithmic trading, market data access, and brokerage account management across stocks, options, and cryptocurrencies.

Package Information

  • Package Name: alpaca-py
  • Package Type: pypi
  • Language: Python
  • Installation: pip install alpaca-py

Core Imports

# Trading API - Orders, positions, account management
from alpaca.trading import TradingClient
from alpaca.trading.stream import TradingStream

# Market Data API - Historical clients
from alpaca.data.historical import (
    StockHistoricalDataClient, CryptoHistoricalDataClient, 
    OptionHistoricalDataClient, NewsClient, ScreenerClient
)

# Market Data API - Live streaming clients
from alpaca.data.live import (
    StockDataStream, CryptoDataStream, 
    OptionDataStream, NewsDataStream
)

# Broker API - Account creation, funding, portfolio management
from alpaca.broker import BrokerClient

# Import all classes from specific modules
from alpaca.trading import *  # All trading classes
from alpaca.data import *     # All data classes  
from alpaca.broker import *   # All broker classes

Basic Usage

Authentication & Client Setup

# Trading client for paper or live trading
trading_client = TradingClient(
    api_key="your-api-key",
    secret_key="your-secret-key", 
    paper=True  # Set to False for live trading
)

# Historical data client  
data_client = StockHistoricalDataClient(
    api_key="your-api-key",
    secret_key="your-secret-key"
)

# Broker client for account management
broker_client = BrokerClient(
    api_key="your-api-key", 
    secret_key="your-secret-key",
    sandbox=True  # Set to False for production
)

Simple Trading Example

from alpaca.trading import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

# Create trading client
trading_client = TradingClient(api_key="key", secret_key="secret", paper=True)

# Submit a market buy order
market_order_data = MarketOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
)

order = trading_client.submit_order(order_data=market_order_data)
print(f"Order submitted: {order.id}")

Market Data Example

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from datetime import datetime

# Create data client
data_client = StockHistoricalDataClient(api_key="key", secret_key="secret")

# Get historical bars
request_params = StockBarsRequest(
    symbol_or_symbols=["AAPL", "TSLA"],
    timeframe=TimeFrame.Hour,
    start=datetime(2023, 1, 1),
    end=datetime(2023, 12, 31)
)

bars = data_client.get_stock_bars(request_params)
print(f"Retrieved {len(bars)} bars")

Architecture

alpaca-py is organized into three main modules that can be used independently or together:

1. Trading Module (alpaca.trading)

Purpose: Execute trades, manage positions, and monitor account status
Key Components: TradingClient, TradingStream
Use Cases: Algorithmic trading, portfolio management, order execution

2. Data Module (alpaca.data)

Purpose: Access historical and real-time market data
Key Components: Historical clients for stocks/crypto/options, live streaming clients
Use Cases: Market analysis, backtesting, real-time data feeds

3. Broker Module (alpaca.broker)

Purpose: Manage customer accounts, funding, and regulatory compliance
Key Components: BrokerClient for account lifecycle management
Use Cases: Account opening, KYC/AML compliance, cash management

Capabilities

Order Management

Complete order lifecycle management across multiple order types:

from alpaca.trading.requests import (
    MarketOrderRequest, LimitOrderRequest, StopOrderRequest,
    StopLimitOrderRequest, TrailingStopOrderRequest
)
from alpaca.trading.enums import OrderSide, TimeInForce, OrderType

# Market Order
market_order = MarketOrderRequest(
    symbol="AAPL", 
    qty=100, 
    side=OrderSide.BUY, 
    time_in_force=TimeInForce.DAY
)

# Limit Order
limit_order = LimitOrderRequest(
    symbol="TSLA",
    qty=50,
    side=OrderSide.SELL, 
    time_in_force=TimeInForce.GTC,
    limit_price=200.00
)

# Stop Loss Order
stop_order = StopOrderRequest(
    symbol="MSFT",
    qty=25,
    side=OrderSide.SELL,
    time_in_force=TimeInForce.DAY,
    stop_price=300.00
)

# Submit orders
order1 = trading_client.submit_order(market_order)
order2 = trading_client.submit_order(limit_order)  
order3 = trading_client.submit_order(stop_order)

See: Trading Client for comprehensive order management

Position Management

Track and manage open positions with real-time P&L:

# Get all positions
positions = trading_client.get_all_positions()

# Get specific position
position = trading_client.get_open_position("AAPL")
print(f"Qty: {position.qty}, Market Value: {position.market_value}")

# Close all positions
trading_client.close_all_positions(cancel_orders=True)

# Close specific position
trading_client.close_position("AAPL")

See: Trading Client for position management details

Market Data Access

Multi-asset class data retrieval and streaming:

from alpaca.data.requests import StockBarsRequest, CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame

# Stock data
stock_bars = data_client.get_stock_bars(StockBarsRequest(
    symbol_or_symbols="AAPL",
    timeframe=TimeFrame.Minute,
    start=datetime.now() - timedelta(days=1)
))

# Crypto data  
crypto_client = CryptoHistoricalDataClient(api_key="key", secret_key="secret")
crypto_bars = crypto_client.get_crypto_bars(CryptoBarsRequest(
    symbol_or_symbols="BTC/USD", 
    timeframe=TimeFrame.Hour,
    start=datetime.now() - timedelta(days=7)
))

See: Data Client for comprehensive market data access

Real-time Streaming

WebSocket-based live data feeds:

from alpaca.data.live import StockDataStream

# Create stream
stream = StockDataStream(api_key="key", secret_key="secret")

# Define handlers
async def trade_handler(data):
    print(f"Trade: {data.symbol} - {data.price} @ {data.size}")

async def quote_handler(data):
    print(f"Quote: {data.symbol} - Bid: {data.bid_price} Ask: {data.ask_price}")

# Subscribe to data
stream.subscribe_trades(trade_handler, "AAPL", "TSLA") 
stream.subscribe_quotes(quote_handler, "AAPL", "TSLA")

# Start streaming
stream.run()

See: Data Client for streaming setup and usage

Account Management

Comprehensive account information and configuration:

# Get account details
account = trading_client.get_account()
print(f"Buying Power: ${account.buying_power}")
print(f"Portfolio Value: ${account.portfolio_value}")

# Get account configuration
config = trading_client.get_account_configurations()

# Update account settings
from alpaca.trading.models import AccountConfiguration
from alpaca.trading.enums import DTBPCheck

# Get current configuration and modify it
config = trading_client.get_account_configurations()
config.dtbp_check = DTBPCheck.BOTH
config.fractional_trading = True
trading_client.set_account_configurations(config)

See: Trading Client for account management features

Broker Services

Customer account lifecycle and funding management:

from alpaca.broker.requests import CreateAccountRequest
from alpaca.broker.models import Contact, Identity

# Create customer account
account_data = CreateAccountRequest(
    contact=Contact(
        email_address="customer@example.com",
        phone_number="555-123-4567"
    ),
    identity=Identity(
        given_name="John",
        family_name="Doe", 
        date_of_birth=date(1990, 1, 1),
        tax_id="123456789"
    )
)

account = broker_client.create_account(account_data)
print(f"Created account: {account.id}")

See: Broker Client for full broker functionality

Error Handling

from alpaca.common.exceptions import APIError

try:
    order = trading_client.submit_order(order_data)
except APIError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    print(f"Request ID: {e.request_id}")

Documentation Structure

This Knowledge Tile is organized into focused sub-documents:

  • Trading Client - Orders, positions, account management, streaming trades
  • Data Client - Historical data, live streaming, market snapshots, news
  • Broker Client - Account creation, funding, KYC/AML compliance, portfolios

Each sub-document provides comprehensive API coverage with complete function signatures, parameters, return types, and practical usage examples.