Alpaca Paper Trading Bot Setup: Complete Guide (2026)
Set up an Alpaca paper trading bot from scratch: API credentials, order types, position tracking, and failure handling without risking real money.
The idea, illustrated
Explore the ideas visually
Step through the key sections, then read the complete guide below.
Step 1 of 4: Setting Up an Alpaca Paper Trading Bot. Paused.
Practice with a free paper-trading account
Build a watchlist, then review each signal’s entry, stop, target, and reasoning. Broker access is optional.
Public subscriptions are paper-only. Live beta enrolment, copy-trading expansion, and live MCP orders are frozen; a paid plan does not unlock them.
Setting Up an Alpaca Paper Trading Bot
Alpaca provides a dedicated paper trading environment with separate credentials and endpoints. This guide walks through complete bot setup: from account creation to order execution, position reconciliation, and automated monitoring.
Paper trading simulates fills without market impact or real money risk. Use it to validate bot logic, test failure scenarios, and build operational confidence before considering live execution. Public Tradewink subscriptions integrate with Alpaca paper accounts only. For a broader comparison of free trading bot options, see the free AI trading bot guide.
Practice with a free paper-trading account
Use the rules in this guide to evaluate a signal’s entry, stop, target, and reasoning before deciding what, if anything, to do.
Public subscriptions are paper-only. Live beta enrolment, copy-trading expansion, and live MCP orders are frozen; a paid plan does not unlock them.
Step 1: Create Alpaca Paper Account
Alpaca offers two account types: Paper Only (simulation) and a funded brokerage account with paper access. For bot development, start with Paper Only:
- Visit Alpaca Paper Trading
- Sign up with email (no identity verification required for paper)
- Navigate to API keys section
- Generate paper API credentials
Critical: Paper and live accounts have different API keys and endpoints. Never test with live credentials. Store keys in environment variables or a secrets manager, never in source code.
Environment Variables
Create a .env file (add to .gitignore):
ALPACA_API_KEY=your_paper_key_here
ALPACA_SECRET_KEY=your_paper_secret_here
ALPACA_BASE_URL=https://paper-api.alpaca.markets
Step 2: Install Required Libraries
Use a virtual environment to isolate dependencies:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install alpaca-py python-dotenv pandas
The alpaca-py SDK provides typed interfaces for the Alpaca API. Check SDK documentation for current version and features.
Step 3: Test Authentication and Account Access
Verify credentials before building trading logic:
import os
from dotenv import load_dotenv
from alpaca.trading.client import TradingClient
from alpaca.trading.requests import GetAccountRequest
load_dotenv()
client = TradingClient(
api_key=os.getenv("ALPACA_API_KEY"),
secret_key=os.getenv("ALPACA_SECRET_KEY"),
paper=True # Explicit paper mode
)
# Test authentication
account = client.get_account()
print(f"Account Status: {account.status}")
print(f"Buying Power: ${account.buying_power}")
print(f"Portfolio Value: ${account.portfolio_value}")
If this fails, verify:
- API keys are copied correctly
- Using paper endpoint (not live)
- Keys are from the paper dashboard
- Account status is "ACTIVE"
Step 4: Understand Alpaca Order Types
Alpaca supports multiple order types. Test each in paper before using in automation:
Market Orders
Execute immediately at best available price. No price guarantee:
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
market_order = MarketOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
order = client.submit_order(market_order)
print(f"Order ID: {order.id}")
print(f"Status: {order.status}")
Limit Orders
Specify maximum buy price or minimum sell price. May not fill:
from alpaca.trading.requests import LimitOrderRequest
limit_order = LimitOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.BUY,
limit_price=450.00,
time_in_force=TimeInForce.DAY
)
order = client.submit_order(limit_order)
Bracket Orders
Entry with automatic stop loss and take profit. Both exit legs activate only after entry fills completely:
from alpaca.trading.requests import (
LimitOrderRequest,
StopLossRequest,
TakeProfitRequest
)
from alpaca.trading.enums import OrderClass
bracket_order = LimitOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.BUY,
limit_price=450.00,
time_in_force=TimeInForce.DAY,
order_class=OrderClass.BRACKET,
stop_loss=StopLossRequest(stop_price=445.00),
take_profit=TakeProfitRequest(limit_price=455.00)
)
order = client.submit_order(bracket_order)
See Alpaca order types for complete documentation on trailing stops, stop-limit orders, and time-in-force variants.
Step 5: Implement Position Tracking
Track open positions and reconcile before new entries:
def get_positions():
"""Fetch all current positions."""
positions = client.get_all_positions()
return {
pos.symbol: {
"qty": float(pos.qty),
"avg_entry": float(pos.avg_entry_price),
"current_price": float(pos.current_price),
"unrealized_pl": float(pos.unrealized_pl),
}
for pos in positions
}
def has_position(symbol):
"""Check if we have an existing position."""
positions = get_positions()
return symbol in positions
# Check before entry
if not has_position("SPY"):
# Safe to enter new position
pass
Step 6: Monitor Order Status
Orders transition through states: new → partially_filled → filled → canceled/rejected. Don't assume instant fills:
import time
def wait_for_fill(order_id, max_wait_seconds=60):
"""Wait for order to fill or reject."""
start_time = time.time()
while time.time() - start_time < max_wait_seconds:
order = client.get_order_by_id(order_id)
if order.status in ["filled", "canceled", "rejected"]:
return order
time.sleep(1) # Check every second
# Order still pending after max_wait
return client.get_order_by_id(order_id)
# Usage
order = client.submit_order(market_order)
final_order = wait_for_fill(order.id)
if final_order.status == "filled":
print(f"Filled at {final_order.filled_avg_price}")
elif final_order.status == "rejected":
print(f"Rejected: {final_order.reject_reason}")
Step 7: Handle Failures and Reconciliation
Network errors, timeouts, and rejected orders require explicit handling:
Client Order IDs
Use idempotent IDs to detect duplicate submissions:
from uuid import uuid4
def create_order_with_tracking(order_request):
"""Submit order with unique client ID."""
client_order_id = str(uuid4())
order_request.client_order_id = client_order_id
try:
order = client.submit_order(order_request)
# Store mapping: client_order_id -> broker order_id
return order
except Exception as e:
# On timeout/error, check if order was created
existing = client.get_order_by_client_id(client_order_id)
if existing:
return existing
raise
Position Reconciliation
After errors or restart, reconcile before proceeding:
def reconcile_state():
"""Verify positions match expected state."""
positions = get_positions()
open_orders = client.get_orders(status="open")
state = {
"positions": positions,
"open_orders": [
{
"id": order.id,
"symbol": order.symbol,
"qty": float(order.qty),
"side": order.side,
"status": order.status,
}
for order in open_orders
],
"timestamp": time.time(),
}
return state
# Run at startup and after errors
state = reconcile_state()
print(f"Active positions: {len(state['positions'])}")
print(f"Open orders: {len(state['open_orders'])}")
Step 8: Build a Complete Bot Loop
Combine components into a monitored execution loop:
import signal
import sys
class TradingBot:
def __init__(self, client):
self.client = client
self.running = True
# Register signal handlers for graceful shutdown
signal.signal(signal.SIGINT, self.stop)
signal.signal(signal.SIGTERM, self.stop)
def stop(self, signum, frame):
"""Handle shutdown gracefully."""
print("Shutting down...")
self.running = False
def check_entry_signal(self):
"""Your strategy logic here."""
# Example: random condition
# Replace with real technical analysis
return False # Placeholder
def run(self):
"""Main bot loop."""
print("Bot starting...")
while self.running:
try:
# Reconcile state
state = reconcile_state()
# Check if we can enter new position
if len(state["positions"]) == 0:
if self.check_entry_signal():
# Build and submit order
order = MarketOrderRequest(
symbol="SPY",
qty=1,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY
)
submitted = create_order_with_tracking(order)
print(f"Order submitted: {submitted.id}")
# Check existing positions
for symbol, pos in state["positions"].items():
# Implement exit logic here
pass
time.sleep(60) # Check every minute
except Exception as e:
print(f"Error in main loop: {e}")
time.sleep(60)
# Run bot
bot = TradingBot(client)
bot.run()
Step 9: Testing Checklist
Before trusting your bot, verify these scenarios:
- Authentication works with paper credentials
- Orders submit successfully
- Order status updates correctly
- Positions reconcile after fills
- Duplicate submission is detected
- Timeout/network errors are handled
- Bot restarts without creating duplicates
- Graceful shutdown cancels pending work
- Rejected orders are logged
- Paper fills match order type expectations
Paper Trading Limitations
Alpaca paper trading simulates fills but cannot reproduce:
- Real market liquidity and depth
- Slippage and price improvement
- Queue position and latency
- Regulatory fees and costs
- Multi-leg execution timing
- Extended hours behavior differences
See Alpaca paper trading docs for complete simulation details. Paper results do not guarantee live performance.
Integrating with Tradewink
Tradewink can complement your Alpaca bot:
- Use Tradewink signals for entry ideas
- Connect your Alpaca paper account for automated execution
- Track performance in the Tradewink dashboard
- Review signals and paper results side-by-side
Follow the Alpaca paper connection walkthrough for step-by-step integration. Public plans submit paper orders only.
From Paper to Live Trading
Before considering live trading:
- Run paper bot for 30+ days
- Test all failure scenarios
- Verify position sizing logic
- Review total costs including fees
- Understand market impact of your order sizes
- Have monitoring and kill switches in place
Review risk management essentials and the algo trading broker guide for production considerations.
Frequently Asked Questions
Do I need a funded account to use Alpaca paper trading?
No. Alpaca Paper Only accounts can be created with just an email and do not require identity verification or funding. Paper and live accounts use separate API credentials.
How long do Alpaca paper API keys last?
Paper API keys do not expire but can be regenerated at any time. Rotate keys if they are exposed or compromised. Never commit keys to source control.
Can paper trading test options strategies?
Yes. Alpaca paper trading supports options orders subject to the same bracket restrictions as equities. Test multi-leg strategies thoroughly as execution order and timing differ from live markets.
What happens to unfilled limit orders at market close?
DAY orders expire at session end. Check order status before the next session to avoid assuming yesterday's order is still active. GTC orders remain open across sessions until filled or canceled.
How do I simulate slippage in paper trading?
Alpaca paper fills use bid/ask simulation. Real slippage depends on order size, market conditions, and liquidity. Test with realistic order sizes and review market depth data to estimate live impact.
Can I run multiple bots with one paper account?
Yes, but concurrent bots need coordination to avoid duplicate orders and position conflicts. Use distinct client_order_id prefixes and implement locking for position checks.
How do I debug rejected orders?
Check order.reject_reason for broker error details. Common causes: insufficient buying power, invalid symbol, unsupported order type, quantity restrictions, or account restrictions. Review Alpaca's order validation rules.
Trading involves substantial risk, including loss of principal. This article is educational, not investment advice. Paper results do not guarantee live performance. Test thoroughly before any live trading. Tradewink is not a registered investment adviser.
Read next
Keep learning with a related guide before putting an idea on your watchlist.
How to Automate Stock Trading with Alpaca in 2026
Automate stock trading with Alpaca: run an offline Python preview, understand paper limits and order states, and reconcile failures before execution.
Build an AI Trading Agent with Alpaca Python: Paper Only
Build an Alpaca Python paper agent: validate IEX bars and model JSON, preview bounded bracket orders, and reconcile order state. Dry run by default.
Paper Trading App Workflow: Review Stock Signals
Use a paper trading app workflow to review stock signals, record entry, stop, target, and rationale, then revisit decisions without a broker connection.
Try AI signals on your watchlist
Send yourself a signal preview, then add tickers to see ranked entries, exits, and risk notes in Tradewink.
Related Signal Types
Sources cited in this guide
- Alpaca Paper Trading (app.alpaca.markets)
- SDK documentation (github.com)
- Alpaca order types (docs.alpaca.markets)
- Alpaca paper trading docs (docs.alpaca.markets)
Tradewink builds explainable AI trading signals for US stocks and ETFs. Build a watchlist, see what Winkie rejected and why, and paper-track ideas before you decide. Public subscriptions are paper-only. Live beta enrolment, copy-trading expansion, and live MCP orders are frozen; a paid plan does not unlock them.
How this guide is reviewed
Tradewink reviews educational content against its documented market-data sources, risk controls, and product methodology. See our data sources and evaluation methodology for the evidence and limitations behind the platform, and our editorial standards for how guides are sourced, dated, and corrected.

Comments
Comments are reader opinions, not investment advice. A moderator reviews your first comment before it appears, and moderators can remove any comment later.
Loading comments…