Home › Guides

Build an Alpaca paper trading bot in Python (alpaca-py, step by step)

tat$$lapper drawing used on the Alpaca bot guide: a pale form in a scribble field

Alpaca gives every account a free paper (simulated) trading environment with an API. That makes it a good place to learn bot-building without risking money. This guide gets a small bot running in Python.

1. Get paper API keys

Sign up at Alpaca, switch the dashboard to Paper, and generate an API key pair. Store the keys as environment variables, never in your code:

export APCA_API_KEY_ID="your-paper-key"
export APCA_API_SECRET_KEY="your-paper-secret"

2. Install the SDK

python -m venv .venv && source .venv/bin/activate
pip install alpaca-py pandas

3. Connect and check the account

import os
from alpaca.trading.client import TradingClient

trading = TradingClient(os.environ["APCA_API_KEY_ID"],
                        os.environ["APCA_API_SECRET_KEY"], paper=True)
acct = trading.get_account()
print(acct.status, acct.buying_power)

paper=True points at the paper endpoint. Keep it that way while you're learning.

4. Read daily bars

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

data = StockHistoricalDataClient(os.environ["APCA_API_KEY_ID"],
                                 os.environ["APCA_API_SECRET_KEY"])
req = StockBarsRequest(symbol_or_symbols="SPY", timeframe=TimeFrame.Day,
                       start=datetime.now(timezone.utc) - timedelta(days=120),
                       feed=DataFeed.IEX)   # free data feed
bars = data.get_stock_bars(req).df.loc["SPY"]

5. Compute a simple signal

fast = bars["close"].rolling(10).mean()
slow = bars["close"].rolling(30).mean()
want_long = fast.iloc[-1] > slow.iloc[-1]

This moving-average cross is a teaching example, not a recommendation.

6. Place a paper order, with a kill switch first

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

if Path("STOP").exists():
    raise SystemExit("STOP file present: not trading")

positions = {p.symbol for p in trading.get_all_positions()}
if want_long and "SPY" not in positions:
    trading.submit_order(MarketOrderRequest(symbol="SPY", notional=1000,
                         side=OrderSide.BUY, time_in_force=TimeInForce.DAY))
elif not want_long and "SPY" in positions:
    trading.close_position("SPY")

7. Run it on a schedule

Run the script once a day after the open with cron (Linux/macOS) or Task Scheduler (Windows). Log every decision to a file so you can review it later.

What to add before you trust it

Skip the boilerplate

The Alpaca Trading Bot Starter Kit ($24) has all of the above already wired: config from env vars, dry-run, a STOP-file kill switch, optional risk caps, a backtester and 29 tests against a mocked API. It runs on paper by default; live mode is opt-in and needs an explicit confirmation flag. The Trader Bundle ($39) adds the read-only Safety Kit and a Paper Trading Journal template.

Starter Kit — $24Trader Bundle — $39

Educational software, not financial advice. Trading involves risk of loss, and backtests or paper results don't predict live results. Not affiliated with Alpaca.

tat$$lapper sticker: a round ink-and-marker face

Trading tools

Templates & services

Apps

Guides

Sites by Joseph Quigley · Springfield, MA · figbot1-deq33z@mail.grokbot.com · Trading products are educational software, not financial advice.

Also by the same creator: tat$$lapper art pack · coloring book · merch.