Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Alpaca

Overview

Alpaca Markets provides a commission-free trading API for US equities and crypto. Roboquant integrates with Alpaca for both live/paper trading (broker) and real-time/historical market data (feed).

Prerequisites

Install the Alpaca dependencies alongside roboquant:

pip install roboquant[extra]

Set your API credentials as environment variables (or put them in a .env file that you don’t put under version control):

export ALPACA_API_KEY="your-api-key"
export ALPACA_SECRET_KEY="your-secret-key"

AlpacaFeed — Market Data

The AlpacaHistoricStockFeed fetches historical stock data from Alpaca’s API. It supports stocks with configurable bar sizes and timeframes.

Basic Usage

import os
from dotenv import load_dotenv

from datetime import datetime, timedelta
from roboquant.feeds.alpaca import AlpacaHistoricStockFeed, AlpacaHistoricCryptoFeed

load_dotenv()

api_key = os.environ["ALPACA_API_KEY"]
secret_key = os.environ["ALPACA_SECRET"]


# Fetch 1-minute bars for the last 5 trading days
feed = AlpacaHistoricStockFeed(api_key, secret_key)
feed.retrieve_bars("F", "TSLA", "JPM", start="2026-03-01", end="2026-03-02")
print(feed)

feed = AlpacaHistoricCryptoFeed(api_key, secret_key)
feed.retrieve_trades("BTC/USDT", start="2026-04-01", end="2026-04-10")
print(feed)

Live feed

A live feed works very similar to the Alpaca historic feed and uses the same crdentials.

from roboquant.feeds.alpaca import AlpacaLiveFeed

feed = AlpacaLiveFeed(api_key, secret_key)
feed.subscribe_quotes("F", "TSLA", "MSFT")

# You can also track crypto prices
# feed = AlpacaLiveFeed(api_key, secret_key, market="crypto")
# feed.subscribe_trades("BTC/USD", "ETH/USD")

timeframe = Timeframe.next("1 minute")
for event in feed.play(timeframe):
    if event.is_empty():
        print("Are you sure the market is open?")
    else:
        print(event.time, event.items)

AlpacaBroker — Live & Paper Trading

The AlpacaBroker allows you to execute orders against an Alpaca live or paper trading account. It can be used standalone or passed into run for live or paper trading execution.

from roboquant.brokers.alpaca import AlpacaBroker

broker = AlpacaBroker(
    api_key=api_key,
    secret_key=secret_key
)

account = broker.sync()
print(account)