How to automate Alpaca trading with Python and the API

August 31, 2026
Facebook logo.
Twitter logo.
LinkedIn logo.
Newsletter issue count indicatorNewsletter total issues indicator
How to automate Alpaca trading with Python and the API

How to automate Alpaca trading with Python and the API

Alpaca trading lets you buy and sell US stocks through a Python script instead of clicking buttons in a brokerage app. Alpaca is a commission-free broker with strong API support, which means your code can talk directly to the broker's servers to place orders and pull data. If you've been looking for a way to get started with algorithmic trading, Alpaca is worth considering because it offers a free paper trading account (simulated trading with fake money) and a well-documented Python library.

Most Alpaca reviews summarize features. This article shows how the broker actually works in Python and includes a full working example. If you want a detailed walkthrough of setting up Alpaca paper trading in Python, that guide covers account creation step by step. The Algorithmic Trading With Python guides are also a good free starting point if you want to go beyond the basics covered here.

How Alpaca Trading Works

Alpaca is a brokerage, not a trading platform. A broker handles the actual order and holds your account, while a platform usually adds charting tools, stock screeners, and manual trading features. Alpaca skips the visual tools and instead gives you API endpoints, which are URLs your code can call to send orders and read account data.

This setup works well for Python users because your script can request data, send orders, and read account details from the same broker without switching between apps. If you want to see how that looks in practice, the guide on basic trading algorithms in Python walks through simple examples.

The broker supports US stocks and crypto trading. There are no commissions on stock trades. Alpaca makes money primarily through interest on uninvested cash balances. It also earns money through payment for order flow, which means market makers pay the broker for the chance to execute customer orders. This practice is common among US brokers.

Paper Trading vs. Live Trading

Alpaca offers two environments. Paper trading uses fake money and connects to a simulated version of the market. Live trading uses real money. Both environments use the same API, so code you write for paper trading works in a live account with one configuration change.

That matters because you can test the same code in a simulated account before you risk real money. Many brokers either don't offer paper trading or use a completely different interface for it. With Alpaca, you can run the same script in a simulated account and later switch it to a live account. Keep in mind that simulated fills can be unrealistically smooth. Live markets may fill your orders at different prices or with slight delays, so paper trading is best for testing code and workflow rather than predicting exact results.

Who Should Use Alpaca

Alpaca is a good fit if you write Python and want to automate trades without paying commissions. It's less useful if you need access to international markets, options (Alpaca's options support is still limited), or a visual trading interface. If you need a broker with a broader product range, you might look at Interactive Brokers, though the IB API is more complex to work with.

Setting Up Your Alpaca Trading Environment

Before you write any code, you need an Alpaca account and API keys.

Go to alpaca.markets and sign up. Once you're in the dashboard, go to the API Keys section and generate a key pair. You'll get two strings. One is the API Key ID, and the other is the Secret Key. Store these somewhere safe and never commit them to a public repository. In real projects, store keys in environment variables instead of hard-coding them into the script.

Install the Alpaca Python SDK.

pip install alpaca-py

The alpaca-py library is Alpaca's official Python package. It replaced the older alpaca-trade-api library, so make sure you use the current one.

Configuring Your API Client

Create a Python file and set up the trading client. The example below uses the paper trading environment.

from alpaca.trading.client import TradingClient

API_KEY = "your_api_key_here"
SECRET_KEY = "your_secret_key_here"

# paper=True connects to the simulated environment
client = TradingClient(API_KEY, SECRET_KEY, paper=True)

account = client.get_account()
print(f"Cash available: ${account.cash}")
print(f"Portfolio value: ${account.portfolio_value}")

When you run this, you should see your paper trading balance. Alpaca gives you $100,000 in fake cash by default. If you get an authentication error, double-check that your keys are correct and that you generated them for the paper environment, not the live one.

A Complete Alpaca Trading Example in Python

Let's build a script that fetches recent price data for a stock. Then it places a market order and checks the resulting position (a position is simply a stock you currently own in the account).

Fetching Historical Price Data

Alpaca provides market data through a separate client. Here's how to pull about one week of calendar data, which usually gives you the last 5 trading days for Apple (AAPL). The code uses timedelta(days=7) because weekends and holidays produce no market data, so 7 calendar days typically covers 5 trading sessions.

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

data_client = StockHistoricalDataClient(API_KEY, SECRET_KEY)

request = StockBarsRequest(
    symbol_or_symbols="AAPL",
    timeframe=TimeFrame.Day,
    start=datetime.now() - timedelta(days=7),
    end=datetime.now()
)

bars = data_client.get_stock_bars(request)
df = bars.df

print(df[["open", "high", "low", "close", "volume"]])

This returns a pandas DataFrame, which is a table-like Python object for working with rows and columns of data. Each row holds one day's data, including the opening price, closing price, and trading volume.

You can use this data to calculate simple measurements such as moving averages (the average price over a recent window of days). You can also compare recent prices and build trading rules from them. The data comes from Alpaca's own feed, so you don't need a separate data subscription for basic daily bars.

One thing to watch is time. datetime.now() returns your local time, but market data APIs work on exchange time (US Eastern). For more reliable results, use timestamps that include timezone information. In most cases Alpaca handles this gracefully, but it's a good habit to be explicit about timezones in production code.

Placing an Order

Now let's buy 10 shares of AAPL at the current market price.

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

order_request = MarketOrderRequest(
    symbol="AAPL",
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY
)

order = client.submit_order(order_request)
print(f"Order submitted: {order.id}")
print(f"Status: {order.status}")

TimeInForce.DAY means the order expires at the end of the trading day if it hasn't been filled. In paper trading, market orders usually fill quickly during market hours, but simulated fills don't perfectly match real market conditions. If you submit this outside market hours, the order will wait until the next market open.

A market order accepts the best available price at the moment it executes. That price can differ from the last quoted price you saw, especially for thinly traded stocks or during fast market moves. If you want more control, use LimitOrderRequest instead and specify a limit_price, which tells the broker to fill the order only at that price or better.

Checking Your Positions

After the order fills, you can check what you own.

positions = client.get_all_positions()

for position in positions:
    print(f"{position.symbol}: {position.qty} shares")
    print(f"  Current price: ${position.current_price}")
    print(f"  Unrealized P/L: ${position.unrealized_pl}")

This loops through every stock you currently hold and prints the quantity, current price, and unrealized profit or loss, which means how much money you would make or lose if you sold right now. The field name unrealized_pl comes from the API itself. For a more complete strategy that combines Alpaca with a full trading setup, see the linked walkthrough.

Common Problems With Alpaca Trading

Alpaca's API is fairly simple, but beginners often run into a few recurring problems.

Rate limits. Alpaca limits how many API calls you can make per minute. If you check order status in a tight loop, you'll hit the limit and get errors. Use websockets instead, which keep an open connection so updates arrive automatically rather than requiring repeated requests.

Market hours. The US stock market is open from 9:30 AM to 4:00 PM Eastern Time, Monday through Friday. Alpaca does support extended hours trading, but you need to set extended_hours=True on your order and use limit orders. Market orders aren't allowed during extended hours.

Pattern day trader rule. If your account has less than $25,000, US regulations limit you to three day trades (buying and selling the same stock on the same day) within any five-business-day period. This is a federal rule, not an Alpaca-specific restriction. Alpaca's paper trading environment may also enforce this limit, so check its current documentation if you plan to day trade in simulation.

Data coverage. The free data plan uses prices from one exchange, not the full market. If you need a more complete view of US stock prices, Alpaca also offers a paid feed that combines data from major US exchanges.

Where to Go From Here

You now have a working Alpaca trading setup in Python. You can fetch data, place orders, and check your positions. Next, write trading rules around these pieces. For example, your script might buy when a stock's recent average price rises above a chosen level, or it might adjust your holdings on a set schedule.

Before you use real money, test your rules on historical data and run them in paper trading for a while. You can learn more about that process in the guide on building and testing a trading strategy in Python.

The free Algorithmic Trading With Python guides explain how to write rule-based trading scripts, test them on past data, and put them into practice.