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.
Getting Started14 min readUpdated March 30, 2026
KR
Kavy Rattana

Founder, Tradewink

How to Automate Stock Trading with Alpaca in 2026

Step-by-step guide to connecting Alpaca to an AI trading system for fully automated stock trading. Covers API setup, paper trading, risk limits, and going live.

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 Automated Trading?

The automated trading landscape has expanded dramatically. Cloud-based algorithmic trading deployments reached $11.02 billion in 2025 (54.47% of total algo trading spend), and retail investors now represent 20-25% of U.S. equity volume — with daily inflows hitting $1.3 billion during H1 2025. This surge in retail automation has made broker APIs like Alpaca not just a convenience but a competitive necessity for traders who want to execute at algorithmic speeds without building institutional infrastructure.

Alpaca has become the dominant broker for algorithmic and retail automated trading for several concrete reasons:

  • Commission-free stock and ETF trading — no per-trade fee eats into backtested performance
  • Paper trading environment that mirrors live trading exactly — test without real money
  • REST and WebSocket APIs — simple, well-documented, production-grade reliability
  • Fractional shares — execute precisely sized positions without rounding to whole share counts
  • Wide platform support — integrates with virtually every trading automation tool including Python, JavaScript, and hosted services
  • No minimum deposit for paper trading; $500 minimum for a live account

No other U.S. broker offers this combination of commission-free execution, fractional share support, and developer-friendly APIs at the retail level. Interactive Brokers offers more sophisticated order types but has a steeper learning curve and higher minimums. TD Ameritrade (now Schwab) has APIs but they are not designed for high-frequency programmatic use. Alpaca was built from the ground up for automation.

Step 1: Account Setup and API Key Generation

  1. Sign up at alpaca.markets (free — no deposit required for paper trading)
  2. Complete identity verification (required even for paper trading per regulatory requirements)
  3. Log in and navigate to "Paper Trading" in the top navigation
  4. Click "API Keys" in the right sidebar
  5. Click "Generate New Key" — you receive a Key ID and a Secret Key
  6. Critical: Copy and save the Secret Key immediately. Alpaca does not show it again after creation. If you lose it, you must generate a new key pair.

Live Trading Keys

When you are ready to trade with real money:

  1. Fund your account (minimum $500 for most features; $2,000 for margin; $25,000 to avoid PDT restrictions)
  2. Navigate to "Live Trading" and generate a separate Live API key
  3. Never use a live key in a test environment — the distinction is critical for safety

Store both keys using environment variables or a secrets manager. Never hardcode them in your scripts.

Step 2: Understanding Alpaca Order Types

Alpaca supports all standard order types. Understanding when to use each is fundamental to good automation:

Market Orders

Filled immediately at the best available price. Use for liquid stocks when speed matters more than price precision.

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

Limit Orders

Filled only at your specified price or better. Essential for illiquid stocks and when slippage control matters.

LimitOrderRequest(symbol='AAPL', qty=10, limit_price=180.00, side=OrderSide.BUY, time_in_force=TimeInForce.DAY)

Stop Orders

Triggers a market order when price reaches the stop level. Used for stop-losses.

Stop-Limit Orders

Triggers a limit order when price reaches the stop level. More controlled than a pure stop order in fast markets.

Bracket Orders

A single entry that includes both a profit target and a stop-loss. This is the recommended approach for automated trading — it guarantees both exits are in place the moment you enter.

from alpaca.trading.requests import MarketOrderRequest, TakeProfitRequest, StopLossRequest

bracket_order = MarketOrderRequest(
    symbol='AAPL',
    qty=10,
    side=OrderSide.BUY,
    time_in_force=TimeInForce.DAY,
    order_class='bracket',
    take_profit=TakeProfitRequest(limit_price=190.00),
    stop_loss=StopLossRequest(stop_price=175.00)
)
client.submit_order(bracket_order)

Step 3: Building a Simple Strategy Loop

A basic automated trading loop has five components: data fetch, signal generation, position check, order submission, and sleep/repeat. Here is a minimal but complete example:

import time
from alpaca.trading.client import TradingClient
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
from datetime import datetime, timedelta

TRADING_CLIENT = TradingClient('YOUR_KEY_ID', 'YOUR_SECRET', paper=True)
DATA_CLIENT = StockHistoricalDataClient('YOUR_KEY_ID', 'YOUR_SECRET')

def get_sma(symbol: str, period: int) -> float:
    """Fetch last N daily bars and return simple moving average of close prices."""
    end = datetime.now()
    start = end - timedelta(days=period * 2)
    request = StockBarsRequest(symbol_or_symbols=symbol, timeframe=TimeFrame.Day, start=start, end=end)
    bars = DATA_CLIENT.get_stock_bars(request).df
    return bars['close'].tail(period).mean()

def has_position(symbol: str) -> bool:
    """Check if we currently hold a position in the symbol."""
    try:
        TRADING_CLIENT.get_open_position(symbol)
        return True
    except Exception:
        return False

def run_strategy():
    symbol = 'SPY'
    sma_fast = get_sma(symbol, 10)
    sma_slow = get_sma(symbol, 30)

    if sma_fast > sma_slow and not has_position(symbol):
        # Golden cross — enter long
        TRADING_CLIENT.submit_order(
            MarketOrderRequest(symbol=symbol, notional=1000, side=OrderSide.BUY, time_in_force=TimeInForce.DAY)
        )
        print(f'Entered long {symbol}')

    elif sma_fast < sma_slow and has_position(symbol):
        # Death cross — exit
        TRADING_CLIENT.close_position(symbol)
        print(f'Exited {symbol}')

while True:
    try:
        run_strategy()
    except Exception as e:
        print(f'Strategy error: {e}')
    time.sleep(60)  # Check every minute

This is a dual moving average crossover strategy — simple but illustrative. The same structure applies to any signal-based strategy.

Step 4: Paper vs Live Trading

Paper trading on Alpaca is not a simulation — it uses real market prices and real order book data. Fills occur at realistic bid/ask spreads. The primary differences from live trading:

AspectPaper TradingLive Trading
CapitalVirtual (starts at $100,000)Real dollars
FillsRealistic but no true market impactTrue market impact for large orders
SlippageSlightly understated for illiquid stocksFull real-world slippage
PsychologyNo emotional pressureReal loss aversion kicks in
API behaviorIdentical to liveIdentical to paper

Paper trading is not optional. Run your system in paper mode for at minimum 30 days and at minimum 50 trades before considering live deployment. The goal is not just to see if the strategy is profitable — it's to shake out bugs, edge cases, and unexpected behavior in your code.

Step 5: Webhook Triggers for Event-Driven Trading

Rather than polling on a fixed interval, event-driven systems react to market events as they happen. Alpaca supports WebSocket data streams for real-time bar and trade data:

from alpaca.data.live import StockDataStream

stream = StockDataStream('YOUR_KEY_ID', 'YOUR_SECRET')

async def on_bar(bar):
    """Called every time a new 1-minute bar closes for subscribed symbols."""
    symbol = bar.symbol
    close = bar.close
    volume = bar.volume
    # Run your signal logic here
    print(f'{symbol}: close={close}, volume={volume}')

stream.subscribe_bars(on_bar, 'AAPL', 'SPY', 'QQQ')
stream.run()

Webhook-based architectures (where a separate service sends an HTTP POST to your trading bot) are also common for integration with external signal providers. A typical webhook handler verifies a secret token, parses the signal payload, and submits the corresponding order to Alpaca.

Step 6: Error Handling and Risk Guards

Automated trading systems must handle failures gracefully. Common failure modes and how to address them:

API Rate Limits

Alpaca has rate limits (200 requests/minute for data, unlimited for trading). If your polling loop runs too fast, you will hit 429 errors. Add exponential backoff:

import time

def submit_with_retry(client, order_request, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.submit_order(order_request)
        except Exception as e:
            if '429' in str(e) and attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # 1s, 2s, 4s
            else:
                raise

Daily Loss Limit Circuit Breaker

Every automated system needs a hard stop that kills trading if daily losses exceed a threshold. Check portfolio P&L at the start of each cycle:

def check_daily_loss_limit(client, max_loss_pct: float = 0.02) -> bool:
    """Returns True if safe to trade, False if daily loss limit hit."""
    account = client.get_account()
    equity = float(account.equity)
    last_equity = float(account.last_equity)
    daily_pnl_pct = (equity - last_equity) / last_equity
    if daily_pnl_pct < -max_loss_pct:
        print(f'Daily loss limit hit: {daily_pnl_pct:.2%}. Halting trading.')
        return False
    return True

Position Count Guard

Cap the number of simultaneous open positions:

def can_open_new_position(client, max_positions: int = 5) -> bool:
    positions = client.get_all_positions()
    return len(positions) < max_positions

PDT Compliance

For accounts under $25,000, track your day trade count before every round trip. Alpaca exposes account.daytrade_count via the account object. Gate new day trades when you are at 3.

Step 5: Go Live

When you are satisfied with paper trading results:

  1. Switch your Alpaca API key to a Live Trading key
  2. Fund your account ($500 minimum; $25,000 to avoid PDT restrictions)
  3. Start with 25-50% of your intended position sizes for the first week
  4. Monitor the first few live trades manually before trusting full automation

How Tradewink Integrates with Alpaca

Tradewink supports Alpaca as a first-class broker integration. Setup takes under two minutes via Discord:

  1. Run /broker setup alpaca in your Tradewink Discord server
  2. Enter your Alpaca Paper Trading API Key ID and Secret Key
  3. Configure risk parameters: position size %, daily loss limit, max concurrent trades
  4. Tradewink will confirm the connection and begin routing trades through Alpaca automatically

Tradewink handles all the complexity described in this guide — bracket orders, PDT tracking, daily loss circuit breakers, position sizing — so you can focus on the strategy rather than the infrastructure. Switching from paper to live trading is a single toggle in your user preferences.

Common Pitfalls

  • Skipping paper trading: Don't risk real money until you've validated the system with at least 30-50 trades
  • Ignoring slippage: Real fills are slightly worse than paper fills, especially for fast momentum entries
  • No kill switch: You must be able to immediately halt all trading and close all positions in an emergency
  • PDT violations: Accounts under $25k get flagged as Pattern Day Traders after 4 round trips in 5 days — build PDT tracking into your system from day one
  • Not handling market hours: Alpaca's REST API will return errors if you submit non-extended-hours orders outside market hours — always check if the market is open before submitting

Frequently Asked Questions

Do I need to deposit money to start automating trades with Alpaca?

No. Alpaca provides a paper trading environment that requires no deposit. You can generate Paper Trading API keys immediately after account verification and run your entire automation setup against a simulated $100,000 account using real market prices. You only need to deposit real money when you are ready to switch to a live trading key.

What is the difference between Alpaca paper trading and live trading from an API perspective?

The API is identical for both environments — same endpoints, same request formats, same response structures. The only difference is the base URL and which key pair you use. Paper trading uses realistic fills based on real bid/ask data but without true market impact. Live trading executes real orders with real capital. This means you can build and test your entire automation stack without touching a live environment until you are confident.

How do I prevent my automated strategy from violating the PDT rule?

Check `account.daytrade_count` before every day trade round trip. If the count is at 3 and your account is below $25,000, skip day trade entries and only take swing trades (positions held overnight). Alpaca updates this counter in real time. Platforms like Tradewink handle this automatically — the day trading scanner pauses when you are at the PDT limit and resumes when the rolling 5-day window resets.

What order type should I use for automated stop-losses in Alpaca?

Use bracket orders for entries — they attach both a take-profit limit order and a stop-loss stop order to your entry in a single API call. This guarantees both exits are live the moment you enter, even if your automation server goes offline. For stops in volatile markets, stop-limit orders give you more price control than pure stop orders but carry the risk of not filling if the price gaps through your limit.

Can I use Alpaca for crypto and options trading automation as well?

Alpaca supports crypto trading (24/7) through the same API, making it particularly useful for automated crypto strategies. Options trading is available via Alpaca's options API, though it has fewer supported order types than equities. For full multi-asset automation including options spreads and futures, you may need to supplement Alpaca with additional broker integrations — which is exactly what Tradewink does, supporting 8 brokers through a unified interface.

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.

KR

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