Alpaca-Py SDK

0.43.2 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `TradingClient` using API keys from environment variables, fetch account details, and submit a basic market order for a stock. It uses a paper trading account by default for risk-free testing.

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}")

view raw JSON →