This article is for educational purposes only and does not constitute financial advice. Trading involves risk of loss. Past performance does not guarantee future results. Consult a licensed financial advisor before making investment decisions.
AI & Automation14 min readUpdated April 20, 2026
TW

Build an AI Trading Agent with Alpaca API (2026 Tutorial)

Step-by-step tutorial: build an AI trading agent that reads Alpaca market data, generates signals with an LLM, and places paper trades. Code included.

Want to put this into practice?

Tradewink uses AI to scan markets, generate signals with full analysis, and execute trades automatically through your broker.

Start Free

Why Alpaca for an AI Agent?

Alpaca is the most AI-agent-friendly broker in 2026. The API is commission-free, offers fractional shares, supports paper trading out of the box, and ships with a generous free tier. Their Python and REST APIs are straightforward enough that you can wire up an LLM-powered trading loop in under 150 lines of code. Crypto trading is included in the same API.

This tutorial walks through a working minimal AI trading agent that uses Alpaca for market data and execution, and any OpenAI-compatible LLM (GPT-5, Claude via OpenRouter, or Gemini) for signal generation. We'll cover authentication, real-time bars, signal generation, paper trading, and the risk guards you need before anyone trusts this with real money.

Architecture Overview

Every production AI trading agent is built from the same 5 components:

  1. Data layer — pulls market data from a broker or provider
  2. Signal layer — an LLM or ML model that proposes trades
  3. Risk layer — enforces position limits, daily loss caps, PDT rules
  4. Execution layer — places orders through the broker
  5. State layer — tracks positions, P&L, and trade history

For a first build, we combine all five into a single Python script. For a production system, see Tradewink's architecture — 75+ concurrent loops, multi-agent debates, and a self-improving learning layer on top of the same primitives.

Step 1: Alpaca Setup

Sign up at alpaca.markets and create a paper account. Generate API keys from the dashboard. Paper trading is free, runs against simulated fills, and behaves nearly identically to live trading — perfect for agent development.

Install the Python SDK:

pip install alpaca-py openai python-dotenv

Store credentials in .env:

ALPACA_API_KEY=your_key
ALPACA_SECRET_KEY=your_secret
OPENAI_API_KEY=your_openai_key

Step 2: Market Data Client

Pull recent bars for a universe of tickers:

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

load_dotenv()
data_client = StockHistoricalDataClient(
    os.environ["ALPACA_API_KEY"],
    os.environ["ALPACA_SECRET_KEY"],
)

def get_bars(symbol: str, days: int = 30) -> list[dict]:
    end = datetime.now()
    start = end - timedelta(days=days)
    req = StockBarsRequest(
        symbol_or_symbols=symbol,
        timeframe=TimeFrame.Day,
        start=start,
        end=end,
    )
    bars = data_client.get_stock_bars(req)
    return [
        {
            "date": b.timestamp.strftime("%Y-%m-%d"),
            "open": b.open,
            "high": b.high,
            "low": b.low,
            "close": b.close,
            "volume": b.volume,
        }
        for b in bars[symbol]
    ]

Step 3: LLM Signal Generation

Feed bars to an LLM with a structured prompt:

from openai import OpenAI
import json

llm = OpenAI()

def generate_signal(symbol: str, bars: list[dict]) -> dict:
    prompt = f"""You are a conservative swing-trading analyst.
Analyze the last 30 days of price data for {symbol}.

Data (most recent last): {json.dumps(bars[-10:])}

Return JSON with exactly these fields:
- direction: "long", "short", or "none"
- confidence: 0-100
- entry: suggested entry price
- stop: stop-loss price
- target: profit target price
- reasoning: one sentence explaining the trade thesis

Only recommend "long" or "short" if confidence is above 65. Otherwise return "none"."""

    response = llm.chat.completions.create(
        model="gpt-5-nano",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
    )
    return json.loads(response.choices[0].message.content)

Step 4: Risk Guards

Never let an LLM submit orders without hard-coded risk checks:

def check_risk(signal: dict, account_equity: float, open_positions: int) -> bool:
    if signal["direction"] == "none":
        return False
    if signal["confidence"] < 65:
        return False
    if open_positions >= 5:  # max concurrent positions
        return False
    # Position size must risk no more than 1% of equity
    risk_per_share = abs(signal["entry"] - signal["stop"])
    if risk_per_share <= 0:
        return False
    max_shares = (account_equity * 0.01) / risk_per_share
    if max_shares < 1:
        return False
    signal["shares"] = int(max_shares)
    return True

Step 5: Order Execution

Place the order through Alpaca's trading API:

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

trade_client = TradingClient(
    os.environ["ALPACA_API_KEY"],
    os.environ["ALPACA_SECRET_KEY"],
    paper=True,  # IMPORTANT: start with paper
)

def submit_order(symbol: str, signal: dict) -> None:
    side = OrderSide.BUY if signal["direction"] == "long" else OrderSide.SELL
    order = MarketOrderRequest(
        symbol=symbol,
        qty=signal["shares"],
        side=side,
        time_in_force=TimeInForce.DAY,
    )
    trade_client.submit_order(order)
    print(f"Submitted {side.value} {signal['shares']} {symbol}")

Step 6: Main Loop

Tie it all together:

UNIVERSE = ["NVDA", "AAPL", "AMD", "MSFT", "TSLA", "META"]

def run_agent():
    account = trade_client.get_account()
    equity = float(account.equity)
    positions = trade_client.get_all_positions()
    open_count = len(positions)

    for symbol in UNIVERSE:
        # Skip if we already hold the ticker
        if any(p.symbol == symbol for p in positions):
            continue

        bars = get_bars(symbol, days=30)
        signal = generate_signal(symbol, bars)
        print(f"{symbol}: {signal}")

        if check_risk(signal, equity, open_count):
            submit_order(symbol, signal)
            open_count += 1

if __name__ == "__main__":
    run_agent()

Run it with python agent.py. It will analyze each ticker, generate an LLM signal, apply risk checks, and submit paper orders when conditions are met.

What's Missing (Production Gaps)

This minimal example is a teaching tool, not a production system. Before risking real capital, you need:

  • Market-hours awareness — only submit orders when markets are open
  • Position monitoring — check stops and targets for open positions
  • Structured exits — submit bracket orders with stop and target on entry
  • Slippage modeling — account for real-world fill quality
  • Backtesting — validate the signal generator on historical data before paper trading
  • Persistent state — a database for trade history, not just in-memory
  • Error handling — broker outages, rate limits, expired sessions
  • PDT rule enforcement — 3 round trips in 5 business days for accounts under $25K
  • Multi-agent validation — a second LLM to challenge the first one's signals before execution

Each of these is a week of work. Tradewink ships with all of it built in, plus multi-agent debate, regime detection, and self-improvement. Building from scratch is educational; deploying a hardened system is a different project.

Going Further

  • Options: Alpaca supports basic options trading — extend submit_order with OptionLegRequest for single-leg trades.
  • Crypto: Same API, different client class (CryptoHistoricalDataClient and crypto symbols like BTC/USD).
  • Websockets: Replace polling with StockDataStream for real-time bars under a second of latency.
  • Multi-agent signals: Run two or three LLMs and only trade when they agree — this is what Tradewink's conviction scoring does at scale.
  • Discord alerts: Send signals to Discord for manual confirmation before execution — see the Discord trading bot guide for the pattern.

Safety Checklist Before Going Live

  1. Paper-trade for at least 90 days and 100+ trades.
  2. Compare paper results to a buy-and-hold benchmark on the same universe.
  3. Confirm every order includes a stop-loss and position cap.
  4. Start with 10-20% of the capital you ultimately want to deploy.
  5. Monitor the agent for the first two weeks of live trading — LLMs behave differently under real fills.
  6. Keep a manual kill switch. An API key revocation is fastest.

AI trading agents are powerful, but the gap between "works in paper" and "survives in live markets" is real. Build carefully.

Frequently Asked Questions

Is it legal to build an AI trading bot with Alpaca?

Yes. Alpaca is a FINRA-registered broker-dealer that provides API access specifically for algorithmic and automated trading. Using their API for your own account is legal. Managing capital for others without registration is not — if you're building a multi-user system, research Investment Adviser Act registration first.

How much does it cost to run an AI agent on Alpaca?

Alpaca trading is commission-free. The costs you'll actually pay are LLM API fees (a few cents per analysis with cheap models, up to $0.10+ per call for top-tier), market-data fees if you need real-time (Alpaca offers free IEX data; Pro data is ~$100/mo), and your cloud hosting. Most single-user agents cost under $30/month to operate.

How do I avoid the Pattern Day Trader rule?

Either keep your account above $25,000, or limit round-trip trades to 3 per 5 business days. A round-trip is opening and closing the same position on the same day. Build this into your risk layer — track intraday open/close events and block the 4th round-trip automatically.

Should I use an LLM or a traditional ML model for signals?

Depends on the task. LLMs are great for unstructured data (earnings transcripts, news, SEC filings) and for flexible rule synthesis. Traditional ML (gradient boosting, walk-forward regression) is more reliable for tabular price/volume features. Production systems combine both — see [Tradewink's architecture](https://www.tradewink.com/architecture) for an example of this hybrid approach.

What's the difference between this tutorial and Tradewink?

This tutorial is a minimal single-file agent for learning. Tradewink is a production AI trading platform with 75+ concurrent loops, multi-agent AI debate, 8 broker integrations, risk management, PDT enforcement, trade reflection and self-improvement, Discord delivery, and a web dashboard. The tutorial teaches the primitives; Tradewink is what those primitives look like after four years of production hardening.

Trading Insights Newsletter

Weekly deep-dives on strategy, signals, and market structure — written for active traders. No spam, unsubscribe anytime.

Ready to trade smarter?

Get AI-powered trading signals delivered to you — with full analysis explaining every trade idea.

Get free AI trading signals

Daily stock and crypto trade ideas with full analysis — delivered to your inbox. No spam, unsubscribe anytime.

Enter the email address where you want to receive free AI trading signals.

TW

Tradewink builds autonomous AI trading systems that combine real-time market analysis, multi-broker execution, and self-improving machine learning models.

Tradewink is not a registered investment adviser, broker-dealer, or financial planner. All data, signals, and analytics on this page are for informational purposes only and do not constitute investment advice, financial advice, or a recommendation to buy or sell any security.

Past performance does not guarantee future results. Trading involves substantial risk of loss, including the possibility of losing more than your initial investment. You are solely responsible for your own trading decisions.