How to Build an AI Trading Bot: Python and Paper Tests
Build an AI trading bot research prototype with Alpaca Python data examples, per-symbol indicators, risk checks, and a paper testing checklist.
Try free AI trade signals on your watchlist
Build a watchlist, then review each signal’s entry, stop, target, and reasoning. Broker access is optional.
Public subscriptions are paper-only; separately approved private beta accounts may submit live broker orders.
How to build AI trading bot: AI trading tools organize data or propose decisions; their output can be wrong even when it sounds confident.
Build a Research Prototype First
An AI trading bot combines market data, analysis, decision rules, risk checks, and order handling. Start with a read-only prototype that records hypothetical decisions. That gives you a concrete way to inspect data and logic before introducing broker execution. This guide's Python examples retrieve data or calculate research values; they do not submit orders.
Choose one instrument, timeframe, and testable hypothesis. Write down which observations were available at the time of each decision. A model that explains yesterday's outcome after seeing it has not demonstrated predictive value. Keep research, simulated orders, and actual broker records distinct.
Choose a Workflow
| Approach | What you control | What you must verify |
|---|---|---|
| No-code research or signal service | Watchlist, supported settings, and review process | Data coverage, actual plan permissions, exportable records, and failure behavior |
| Python prototype | Data transformations, indicators, tests, and logs | Symbol isolation, timestamps, costs, and assumptions |
| LLM-assisted research | Prompts, supplied evidence, and output validation | Sources, stale data, invented values, and repeatability |
These approaches can overlap. A signal service can provide ideas for a Python paper journal; an LLM can summarize evidence without receiving order authority. Setup speed is not a measure of reliability. Compare the documented account, instrument, and feed requirements rather than assuming every API or platform is free or supports the same workflow.
Architecture and Failure Boundaries
Use separate stages: data → analysis → hypothetical decision → risk review → paper integration → reconciliation. Each stage should reject missing or invalid input and record why. Keep credentials outside source files and never include them in prompts, screenshots, or public logs. An unavailable data feed should produce a recorded skip rather than an invented price.
Before implementing order handling, read the broker's current API documentation and account requirements. A successful data request does not prove trading permission. See the broker evaluation checklist for the distinction between data, orders, and account eligibility.
Alpaca Python: StockHistoricalDataClient and StockBarsRequest
Install the official SDK and pandas in an isolated environment. Supply your existing authorized data credentials through environment variables. This request uses a fixed historical interval and explicitly selects the IEX feed; IEX coverage differs from a consolidated feed and must not be silently treated as the whole market.
The Alpaca historical client reference documents the client and get_stock_bars. The BarSet reference documents the returned data model.
import os
from datetime import datetime, timezone
from alpaca.data.enums import DataFeed
from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame
client = StockHistoricalDataClient(
api_key=os.environ["APCA_API_KEY_ID"],
secret_key=os.environ["APCA_API_SECRET_KEY"],
)
request = StockBarsRequest(
symbol_or_symbols=["AAPL", "SPY"],
timeframe=TimeFrame.Day,
start=datetime(2025, 1, 1, tzinfo=timezone.utc),
end=datetime(2025, 4, 1, tzinfo=timezone.utc),
feed=DataFeed.IEX,
)
bars = client.get_stock_bars(request)
df = bars.df
if df.empty:
raise ValueError("No bars returned; inspect dates and data permissions")
# BarSet.df has symbol and timestamp index levels.
# Select one instrument before any rolling calculation.
aapl = df.xs("AAPL", level="symbol").sort_index().copy()
aapl["sma_20"] = aapl["close"].rolling(20, min_periods=20).mean()
print(aapl[["close", "sma_20"]].tail())
Why select a symbol before calculating indicators?
The multi-index identifies each instrument and timestamp. Applying a moving average directly to a combined AAPL/SPY frame can blend different stocks. Selecting AAPL with xs prevents this; sorting timestamps makes the rolling window chronological. Keep the initial missing SMA values: they mean insufficient history, not a zero-price signal.
This is a data example, not a trading strategy. Check missing bars, duplicates, timezone conventions, corporate-action adjustments, and feed coverage before interpreting results. For intraday research, a completed daily bar cannot be treated as information available earlier that same day.
A Position-Sizing Calculation That Can Return Zero
The example below caps hypothetical whole-share quantity by both a planned stop-distance budget and an allocation budget. Its inputs are illustrative test values, not a recommendation for your account. A zero result means the proposal does not fit the supplied limits. Never round it up to one share merely to make an order possible.
import math
def hypothetical_long_size(equity, entry, stop, risk_fraction, allocation_fraction):
values = (equity, entry, stop, risk_fraction, allocation_fraction)
if not all(math.isfinite(value) for value in values):
return 0
if equity <= 0 or not 0 < stop < entry:
return 0
if not 0 < risk_fraction <= 1 or not 0 < allocation_fraction <= 1:
return 0
by_stop_distance = math.floor(equity * risk_fraction / (entry - stop))
by_allocation = math.floor(equity * allocation_fraction / entry)
return max(0, min(by_stop_distance, by_allocation))
A stop price is a planning input, not a guaranteed fill. Gaps, spread, fees, and liquidity can make actual losses larger than the stop-distance calculation. An execution system also needs buying-power, instrument, order, account, and portfolio checks. This helper implements none of those permissions and must not be used as a standalone execution gate.
Try free AI trade signals on your watchlist
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; separately approved private beta accounts may submit live broker orders.
Backtest Without Hiding Assumptions
Separate the decision timestamp from the assumed fill timestamp. Using a bar's close to generate a decision and also assigning that exact close as its guaranteed execution price introduces an unrealistic assumption. Define your fill model explicitly, include costs and missed fills, and keep development data separate from evaluation data.
Record open positions and mark-to-market exposure; reporting only closed winners and losers hides remaining risk. Include rejected or skipped ideas and document parameter changes. Compare adverse scenarios rather than declaring that a specific win rate, drawdown, or sample count proves success. The backtesting guide explains the wider review process.
Paper Integration Checklist
Alpaca's paper-trading documentation explains the simulation's limitations. Paper trading can test integration behavior; it cannot establish that live liquidity, queue position, or costs will match simulated fills.
- Confirm the configured account and endpoint are paper environments before testing.
- Test invalid quantities, unavailable instruments, stale prices, and rate limits.
- Record order IDs and reconcile acknowledgement, partial fills, cancellation, and final status.
- Test restarts and timeouts. An uncertain submission result needs reconciliation; blind retries can duplicate an order.
- Preserve an independent pause control and record the reason for every rejected decision.
No number of days or trades certifies readiness. Read the paper-trading guide and review the actual provider's limits. This tutorial does not provide a switch to live execution.
Add an LLM as a Research Layer
Supply dated, attributable observations and ask for an explanation with explicit uncertainties. Treat headlines and retrieved pages as untrusted input. Validate instrument identity, source timestamps, output structure, and finite numeric values. Parsing JSON alone does not establish correctness.
Store the prompt, explicit model version, inputs, and accepted or rejected output so a review can reconstruct the decision. Measure API usage and latency from your own runs rather than assuming fixed costs. Missing evidence, invalid output, or a timeout should produce no action. A self-reported confidence score does not establish probability or profitability.
Use Tradewink to Review the Idea
Start with a free watchlist, inspect a signal's reasoning and risk context, and record your independent decision. Broker access is optional for this review workflow. Public subscriptions are paper-only; separately approved private beta accounts may submit live broker orders. Check signals and pricing for current availability and entitlements. Do not interpret this educational example as an offer of public live automation.
How to build AI trading bot: practical checks
Trace each factual claim to its source and timestamp. Freeze the model and prompt for a comparison, retain rejected ideas as well as winners, and evaluate hypothetical records separately from reconciled broker executions.
Read the CFTC AI trading advisory for the underlying definitions and limits. For a next step, use Backtest P&L Reconciliation: Audit Matched Trades and What Is AI Trading? A Complete Guide for 2026.
Frequently Asked Questions
How do I build an AI trading bot in Python?
Begin with a read-only research prototype: retrieve historical data, separate each symbol, compute indicators, and record hypothetical decisions. Add repeatable tests and a paper-account integration before considering any order automation. These examples do not establish profitability or readiness for live trading.
How do StockHistoricalDataClient and StockBarsRequest work?
StockHistoricalDataClient is the Alpaca Python market-data client. StockBarsRequest specifies symbols, timeframe, dates, and feed. Pass the request to get_stock_bars; its BarSet exposes a .df DataFrame with symbol and timestamp index levels. Select one symbol and sort timestamps before rolling calculations.
Why does get_stock_bars return a multi-index DataFrame?
A bars response can contain multiple symbols. The symbol and timestamp index levels identify which instrument each row belongs to. Use df.xs("AAPL", level="symbol").sort_index() for a single-symbol example; rolling over the combined frame can mix prices from different stocks.
Can I build a trading bot for free?
You can prototype locally using open-source tools and data available under your account permissions. Check the actual feed, history, API limits, and paper-account requirements. Data subscriptions, hosting, language-model calls, and operational monitoring can introduce costs; this guide does not promise a free production system.
How long should I paper test a trading bot?
No universal duration or trade count proves readiness. Test data failures, sizing, rejected and partial orders, restart recovery, reconciliation, and adverse conditions. Paper fills and backtests rely on assumptions and do not establish future live results.
Can an LLM decide which orders to submit?
A language-model explanation is untrusted research output. Validate its structure, source timestamps, instrument, and numeric ranges; malformed or stale output should produce no action. An explanation or self-reported confidence score cannot replace independent risk and execution checks.
Risk and Verification Limits
These examples are educational and do not recommend a security, allocation, or trade. They are not a complete execution system. Trading can cause substantial losses; backtests, paper results, and AI explanations do not guarantee future outcomes. API behavior and account rules can change. Check the primary documentation and test the exact environment you use.
Read next
Keep learning with a related guide before putting an idea on your watchlist.
Backtest P&L Reconciliation: Audit Matched Trades
Backtest P&L reconciliation: Match trade quantities and prices before assigning unexplained P&L to an execution cause.
What Is AI Trading? A Complete Guide for 2026
Learn how AI trading systems analyze markets, generate signals, manage risk, and where models can fail. Compare tools with practical checks.
How AI Trading Signals Work: From Data to Trade Idea
Ever wonder how AI generates trading signals? We break down the full pipeline: data ingestion, pattern recognition, scoring, filtering, and delivery.
How to Backtest a Trading Strategy: Step-by-Step Guide for 2026
Backtesting reveals whether your strategy has a real edge. Learn step-by-step how to backtest with historical data, avoid overfitting.
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.
How to Choose a Broker for Algorithmic Trading (2026 Guide)
Compare algo trading brokers by API access, execution quality reports, paper limits and costs. Learn how Rule 605 differs from Rule 606.
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 historical client reference (alpaca.markets)
- BarSet reference (alpaca.markets)
- Alpaca's paper-trading documentation (docs.alpaca.markets)
- CFTC AI trading advisory (cftc.gov)
Tradewink builds explainable market research for self-directed traders. Build a watchlist, inspect signal reasoning and risk context, and paper-track ideas before you decide. Public subscriptions are paper-only; separately approved private beta accounts may submit live broker orders.
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.