- Alpha Vantage and Polygon.io both work as OpenClaw skills for real-time and historical price data — start with Alpha Vantage's free tier to validate your strategy
- Encode all risk rules directly in the system prompt — position size limits, stop-loss thresholds, and blacklisted tickers — so the agent enforces them on every signal
- Run on Alpaca's paper trading environment for at least 30 days before switching to live — the API is identical, so migration is a single config change
- Automated trading for your own account is legal in most jurisdictions; managing other people's money requires regulatory licensing
- The most dangerous moment is the first live trade — start with position sizes 10x smaller than your intended target and scale up after 60 days of live data
Ninety-three percent of discretionary traders underperform the index over a 10-year period. The primary cause is not bad strategy — it's inconsistent execution. An OpenClaw trading agent applies your exact rules on every bar, every day, without the fear, greed, or fatigue that derails human traders. Here's how to build one from scratch, and what most people get wrong before they blow up a paper account.
Why Automate Stock Trading With an AI Agent
Traditional algorithmic trading platforms require you to express your strategy as rigid code. If your strategy changes — because market conditions change, because you learn something new — you rewrite the code. That's slow. An OpenClaw agent lets you express strategy in plain language in the system prompt, combine it with programmatic data fetching via skills, and update the strategy in minutes without touching any code.
The agent model also handles something that traditional algos can't: contextual reasoning. A rule-based algo executes a moving average crossover regardless of whether there's a Fed announcement in two hours. An OpenClaw agent can be instructed to check the economic calendar before entering positions and to widen stops or stay flat around scheduled volatility events.
As of early 2025, builders running OpenClaw trading agents report consistent advantages in three areas: faster strategy iteration, better handling of edge cases, and the ability to integrate qualitative signals (news sentiment, earnings call transcripts) with quantitative price data in a single agent workflow.
Nothing in this guide constitutes investment advice. Automated trading carries real risk of capital loss. The technical implementation described here is for educational purposes. Consult a licensed financial advisor before trading with real money.
Market Data API Integration
Your trading agent needs two data sources: price data and fundamental data. You'll build each as a separate OpenClaw skill.
Alpha Vantage
Alpha Vantage provides free API access to US equity price data, technical indicators, and basic fundamental data. The free tier allows 25 requests per day — enough for end-of-day strategy testing on a small watchlist. The premium tier at $50/month removes rate limits and adds intraday data down to 1-minute bars. For most personal trading setups, the premium tier is the right starting point.
Polygon.io
Polygon.io offers real-time streaming and REST access to US equities, options, forex, and crypto. The Stocks Starter plan at $29/month gives you real-time data with 15-minute delay on options. For live intraday trading strategies that need tick-level data, Polygon is the stronger choice. The API documentation is among the best in the space — the OpenClaw skill takes about 45 minutes to build correctly.
Here's the core structure of an Alpha Vantage price-fetch skill:
# skills/get_stock_price.py
import requests
import os
def get_stock_price(symbol: str, interval: str = "daily") -> dict:
"""Fetch OHLCV data for a stock symbol."""
api_key = os.environ["ALPHA_VANTAGE_KEY"]
function = "TIME_SERIES_DAILY" if interval == "daily" else "TIME_SERIES_INTRADAY"
params = {
"function": function,
"symbol": symbol.upper(),
"apikey": api_key,
"outputsize": "compact" # last 100 data points
}
if interval != "daily":
params["interval"] = interval
resp = requests.get("https://www.alphavantage.co/query", params=params)
resp.raise_for_status()
data = resp.json()
# Return last 10 bars for agent context
key = list(data.keys())[1]
bars = list(data[key].items())[:10]
return {"symbol": symbol, "interval": interval, "bars": bars}
Register this skill in your agent config and the agent can call it by name. Ask it to fetch AAPL daily bars and it returns the last 10 trading sessions of OHLCV data in structured JSON.
Alpha Vantage has a separate API endpoint for technical indicators — RSI, MACD, Bollinger Bands, and more. Build a separate get_indicator skill that fetches precomputed indicators. This is faster than computing them in the agent context and avoids token-heavy data processing.
Signal Generation Logic
Signal generation is where most beginners over-engineer the wrong thing. The agent doesn't need to invent signals — it needs to evaluate a clear set of conditions and produce a structured trade decision. Write the signal logic in the system prompt, not in code.
A working signal rule set looks like this in the system prompt:
- Fetch daily bars and RSI(14) for each ticker in the watchlist
- A buy signal fires when: RSI crosses above 35 from below, the 20-day SMA is above the 50-day SMA, and volume on the signal day is at least 1.5x the 20-day average volume
- A sell signal fires when: RSI crosses above 70, or price falls more than 7% from the entry price, or 20 trading days have elapsed since entry
- Output a structured JSON decision: {"action": "buy"|"sell"|"hold", "symbol": "TICKER", "reason": "brief explanation"}
The structured JSON output is critical. It lets your execution skill parse the decision reliably without fragile string matching. The agent reasons through the conditions in plain language and then outputs a clean machine-readable decision.
Sound familiar? This is essentially system prompt engineering for trading. The difference from a traditional algo is that the agent can also handle the cases your rules don't explicitly cover — it applies the spirit of the rules, not just the letter.
Risk Management Rules in the System Prompt
This section is the most important one in the guide. Most trading system failures happen not because the signal was wrong, but because position sizing and loss limits weren't enforced. Encode every risk rule explicitly.
A minimum risk management block for the system prompt:
RISK MANAGEMENT RULES — ENFORCE THESE ON EVERY DECISION:
1. Maximum position size: 5% of total portfolio value per position
2. Maximum portfolio exposure: 60% total — never hold more than 12 positions simultaneously
3. Hard stop-loss: Exit any position that falls 8% below entry price — no exceptions
4. Daily loss limit: If total portfolio is down more than 2% in a calendar day, stop all new entries
5. Blacklisted tickers: ["SPCE", "BBBY", "AMC"] — never enter these regardless of signal
6. Earnings blackout: Never enter a position within 3 trading days of a scheduled earnings announcement
7. Pre-trade check: Call get_economic_calendar() before any entry — do not enter if a Fed rate decision is scheduled within 24 hours
Before outputting any trade decision, confirm each rule above is satisfied.
Output "RISK_BLOCK: [rule number]" if any rule prevents the trade.
Here's where most people stop.
They add risk rules to the system prompt and assume the agent will follow them perfectly. It will — most of the time. For any trade above a defined dollar threshold, add a second confirmation skill that re-checks the risk rules programmatically before submitting the order. Defense in depth.
Paper Trading vs Live Trading
Alpaca is the broker of choice for OpenClaw trading agents. It offers commission-free US equity trading with a REST API that's identical between paper and live accounts. The paper trading environment uses real market prices with simulated order fills — it's as close to live as you can get without real money at risk.
The migration path from paper to live is a single change: swap the paper API endpoint and credentials for the live ones in your skill config. The agent, the signal logic, and the risk rules stay identical. This is the correct architecture — your strategy lives in the agent config, not in the broker integration code.
| Factor | Paper Trading | Live Trading |
|---|---|---|
| Capital at risk | None | Real money |
| Fill realism | Simplified (best bid/ask) | Actual market fills |
| Slippage | Not modeled | Real — especially on illiquid names |
| Psychology | Zero emotional pressure | Full emotional pressure |
| Recommended duration before switching | Minimum 30 trading days | — |
One thing paper trading doesn't test is your own psychology when real money is moving. An agent that you've watched make 40 paper trades profitably looks very different when trade 41 is live and shows a 6% drawdown. Know this going in. Your job on day one of live trading is to not override the agent.
Common Mistakes When Building a Trading Agent
- Overfitting signal rules to historical data — a rule that worked perfectly on 2022 data may be capturing a regime-specific pattern that won't repeat. Test on at least two separate market periods before trusting any signal set.
- Not accounting for market hours in scheduling — your cron-triggered agent needs to know market hours. Running a signal check at 3 AM on a Saturday and finding no data shouldn't trigger an error that stops the agent entirely. Add market hours awareness to your skills.
- Putting risk rules only in the system prompt — the system prompt is a strong control but not a guarantee. Add a programmatic pre-trade check skill as a second layer for any live trading setup.
- Using a single data source — if Alpha Vantage has an outage on a signal day, your agent should fail gracefully and log the missed signal rather than making a decision on incomplete data. Build fallback data source logic into your skill.
- Not logging agent reasoning — OpenClaw's conversation history logs the agent's full reasoning for each decision. Enable persistent logging so you can audit every trade decision and trace signal errors back to the specific data and rule that triggered them.
Frequently Asked Questions
Can OpenClaw actually execute stock trades automatically?
OpenClaw executes trades when you build a skill that calls your broker's REST API. Alpaca and Interactive Brokers both provide clean REST interfaces. The agent handles signal generation and risk checks; the skill submits the order. Start with paper trading before connecting to any live account.
What market data APIs work best with OpenClaw stock agents?
Alpha Vantage suits end-of-day strategies with its free tier — adequate for validating a strategy before spending on data. Polygon.io handles real-time and intraday needs better. For fundamental data, a Financial Modeling Prep skill alongside your price data source covers most use cases.
How do I prevent the agent from making catastrophic trades?
Encode risk rules in the system prompt — maximum position size, stop-loss thresholds, daily loss limits, and blacklisted tickers. Add a confirmation skill that re-checks rules programmatically before submitting orders above a defined dollar threshold. Two layers of enforcement beats one.
Is it legal to run an automated stock trading agent with OpenClaw?
Automated trading for your own personal account is legal in most jurisdictions. Managing other people's money algorithmically requires regulatory licensing in most countries. This guide covers personal portfolio automation only. Consult a licensed financial advisor before trading with anything beyond your own funds.
What is the difference between paper trading and live trading in this setup?
Paper trading uses real market prices with simulated fills — no real money moves. Alpaca's paper environment mirrors its live API exactly. Switching to live is a single config change in your broker skill. Run paper trading for at least 30 days across different market conditions before going live.
How often should the stock trading agent check for signals?
For daily strategies, a pre-market morning run plus an end-of-day review is sufficient for most setups. For intraday strategies, 5-minute or 15-minute polling intervals balance responsiveness against API costs. Match polling frequency to your actual strategy time horizon — more frequent checks rarely improve results.
M. Kim has built and deployed AI-assisted trading systems for personal portfolio management, testing strategies across multiple market regimes since 2022. Specializes in combining LLM reasoning with quantitative signals for systematic approaches that stay executable under real market conditions.