Build an AI Trading Bot for US Options (Alpaca API)
By Shakti Tiwari — Nifty Option Trader, Research Analyst & XGBoost Expert
A few years ago, running an automated options strategy in the US meant an expensive broker API, a colocated server, and institutional-grade budgets. Today a retail trader can wire a machine-learning signal to live US options orders with a free Alpaca account, a Python script, and a laptop — or even an Android phone running Termux. This guide walks through the architecture of a realistic AI options bot: signal generation, risk gating, order routing through Alpaca, and the guardrails that keep automation from becoming an expensive mistake.
Why Alpaca for US Options Automation
Alpaca is a US broker built API-first. Relevant points for options builders:
- Options trading via API — Alpaca supports options order placement (multi-leg support depends on your account's options trading level).
-
Paper trading environment — a full simulated account at
paper-api.alpaca.marketswith the same API surface as live. You can develop and test the entire bot without risking a dollar. - Free market data tier — enough for daily/minute equity bars to feed a model; upgraded feeds are available if you need more.
-
Simple Python SDK —
alpaca-pycovers trading, data, and account endpoints.
The paper environment is the killer feature. Every bot in this article should live on paper for weeks before any live deployment.
Architecture of a Sane Options Bot
Keep it modular. Five components:
- Data layer — pulls SPY/QQQ bars and any external features (VIX from yfinance, for example).
- Signal layer — your model (XGBoost classifier, rules engine, or hybrid) emits a probability or score.
- Risk gate — hard-coded checks that can veto any trade: max open positions, max daily loss, market-hours check, earnings/FOMC blackout dates.
- Execution layer — translates an approved signal into an Alpaca options order (choose contract, strike, expiry, limit price).
- Journal — logs every decision, including trades not taken, to a CSV or SQLite file for later analysis.
The risk gate sits between the model and the broker. The model proposes; the gate disposes.
Getting Connected
from alpaca.trading.client import TradingClient
trading = TradingClient(API_KEY, SECRET_KEY, paper=True)
account = trading.get_account()
print(account.status, account.buying_power)
With paper=True everything routes to the simulated account. Keep keys in environment variables, never in code you might push to GitHub.
Selecting the Option Contract
An AI signal like "SPY likely up by Friday" still needs contract selection logic. A simple, defensible approach for a directional signal:
- Expiry: nearest expiry with at least as many days as your signal horizon (avoid 0DTE until the bot is proven).
- Strike: slightly out-of-the-money, e.g. the first strike above spot for calls, keeping delta moderate.
- Structure: debit spreads instead of naked longs — buy the near strike, sell one further out. Defined risk means a code bug can only lose the debit paid.
Alpaca uses standard OCC symbols (e.g. SPY261218C00600000 — SPY, expiry date, C/P, strike ×1000). Build the symbol programmatically and validate it against the contracts endpoint before ordering.
from alpaca.trading.requests import LimitOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce
order = LimitOrderRequest(
symbol="SPY261218C00600000",
qty=1,
side=OrderSide.BUY,
time_in_force=TimeInForce.DAY,
limit_price=2.50,
)
trading.submit_order(order)
Always use limit orders for options. Market orders on options can fill at ugly prices, especially away from the money.
The Risk Gate: Non-Negotiable Rules
Hard-code these before the first paper trade:
- Max concurrent positions (e.g. 3) and max premium at risk per trade (e.g. 1–2% of account).
- Daily kill switch: if realized + unrealized loss crosses a threshold, cancel open orders and stop trading until manual reset.
- Time windows: no new entries in the first 15 minutes after the open or the last 10 before the close, when options quotes are widest.
- Event blackouts: skip FOMC days and CPI mornings unless the strategy is explicitly built for them.
- Sanity checks: refuse any order whose limit price deviates wildly from the mid-quote, and refuse duplicate orders within a cooldown period.
Most catastrophic bot failures are not bad models — they are loops that fire the same order fifty times, or a missing market-hours check. Boring defensive code is what keeps the account alive.
Scheduling and Running It
On a VPS, a cron entry running the script every N minutes during market hours (9:30 AM–4:00 PM ET) is enough for non-HFT strategies. On Android, Termux plus cron or a simple loop with sleep works for end-of-day or hourly logic. Log everything to disk; when the bot misbehaves, the journal is how you find out why.
From Paper to Live — Slowly
A reasonable promotion path: run on paper until you have a meaningful sample of trades, compare paper fills against real quote data to estimate slippage, then go live with the minimum size (one contract) and the kill switch armed. Scale only after live behavior matches paper behavior. Automation amplifies whatever discipline — or lack of it — you encode.
Takeaway
An AI options bot on Alpaca is genuinely achievable for a retail developer: free paper account, Python SDK, defined-risk spreads, and a hard-coded risk gate between the model and the broker. Spend 20% of your effort on the model and 80% on risk controls, journaling, and testing — that ratio is what separates a durable bot from a cautionary tale.
This article is for education only and is not financial, investment, or trading advice.
Join our Telegram: https://t.me/shaktitrade
Contact: https://optiontradingwithai.in
Top comments (0)