A step-by-step prompt you can use to create a fully automated stock trader — no finance degree required.
⚠️ Disclaimer: This is a personal project built for learning and experimentation. Nothing in this article is financial advice. Trading real money involves real risk — only use money you can afford to lose. Past results do not guarantee future performance.
How I built this: I used Claude Code (Anthropic’s AI coding assistant) to write the entire trading bot — from the first line of code to every strategy tweak. And I used OpenClaw as the autonomous agent that runs 24/7 on a cloud server, keeping all the bots alive, scheduling cron jobs, and routing Telegram commands. No DevOps knowledge needed. No traditional coding involved.
What This Bot Does
This is an automated trading bot that runs 24/7, scans 80+ stocks every 15 minutes, and uses Google’s Gemini AI to decide what to buy — and when to rotate into something better. The strategy is simple:
- Hold one stock at a time with all your capital
- Sell when it hits +8% profit — but only if there’s a better opportunity waiting
- If nothing better exists, keep holding with a trailing stop for protection
- Never sell at a loss — just wait it out
No complex formulas. No emotional decisions. The AI reads the news so you don’t have to.
Results so far: 38 closed live trades, 100% win rate, $979 profit. Average hold time: 25 days.
How It Works — The 3-Phase Selection Process
Phase 1 — Technical Scan
Every 15 minutes, the bot scores all 80 stocks using three indicators:
- RSI — is the stock oversold (good to buy) or overbought (avoid)?
- Moving Averages — is the price trending up over 20 days?
- MACD — is momentum bullish right now?
The top 10 highest-scoring stocks move to Phase 2.
Phase 2 — AI News Analysis (Gemini)
For each of the top 10, the bot fetches the last 6 hours of news headlines from Finnhub and sends them to Gemini 2.5 Flash, which returns:
{
"action": "buy",
"confidence": 0.88,
"reason": "Strong Q1 earnings beat driven by AI ad growth..."
}
Only stocks with confidence >= 0.70 qualify. The winner is the one with the highest combined score (technicals + AI confidence).
Phase 3 — Volume Confirmation
The final candidate must have today’s volume at least 80% of its 20-day average. Low-volume moves are often false breakouts — the bot skips them and tries the next candidate.
The bot then buys it with all available cash and sends you a Telegram notification.
The Comparative Exit — Smarter Than a Fixed Target
Most bots sell at a fixed target and move on. But here’s the problem with a single-position strategy: every day you hold past +8% is a day you can’t be in the next winner.
The data proved this. 14 trades ran 15–66% past the 8% target. Three quick 8% trades in 30 days compound to +26%, beating a single +20% hold. But only if there’s actually something better to buy.
The solution: comparative exit. When a position hits +8%:
- The bot runs a full scan of all 80 stocks
- If a better candidate exists (strong technicals + bullish AI sentiment) → sell and rotate
- If nothing better exists → keep holding with a 3% trailing stop from peak
This gives you the best of both worlds: fast turnover when opportunities exist, patient holding when they don’t.
Position at +12%, scanning...
→ Found SMCI with score 0.82 → SELL current, BUY SMCI
→ Telegram: "Rotated ORCL → SMCI (+12.3%)"
Position at +9%, scanning...
→ No strong candidates found → HOLD
→ Peak tracked at $540, trailing stop at $523.80
What You’ll Need
| Tool | Purpose |
|---|---|
| Alpaca | Brokerage API to execute real trades |
| Finnhub | News headlines + earnings calendar |
| Gemini API | AI analysis of headlines |
| Telegram Bot | Buy/sell alerts on your phone |
| Python + cron | Runs the bot every 15 minutes |
| OpenClaw | Autonomous agent that hosts everything on a cloud server |
All APIs have free tiers to get started.
The Secret Ingredient — OpenClaw
The trading bot runs on a Mac Mini at home, not a cloud server. What keeps it alive and running 24/7 is OpenClaw — an open-source autonomous AI agent you can self-host.
Here’s what OpenClaw handles behind the scenes:
- Installs and configures everything on a fresh server automatically via a startup script
- Schedules all cron jobs — the stock bot runs every 15 minutes, earnings checks run nightly, morning reports fire at 9:25 AM ET
- Restores state after server restarts — positions, logs, and config all survive reboots
- Routes Telegram commands — you can message your bot and ask it what it’s doing, check positions, or trigger manual runs
- Runs multiple bots in parallel — stock trading, crypto trading, earnings monitoring, news scanning — all managed from one place
Without OpenClaw, you’d need to manually SSH into a server, set up cron jobs, and babysit restarts. With it, you just push code and everything else is handled.
OpenClaw is open source: github.com/openclaw
The Full Build Prompt
Copy this prompt into Claude or ChatGPT to generate the complete working code:
Build a fully automated US stock trading bot in Python that trades a live Alpaca brokerage account. The bot should run every 15 minutes during market hours via a cron job.
Strategy — Single Concentrated Position with Comparative Exit:
- Hold only 1 stock position at a time
- Deploy all available cash (minus a $1,050 reserve for other bots) into the best stock pick
- When position hits +8% profit, run a full scan of 80 stocks. If a better candidate exists, sell and rotate into it. If nothing better, hold with a 3% trailing stop from peak price.
- Never sell at a loss (no stop loss) — hold until the position is profitable
- While waiting for the active position to hit target, monitor all background positions and sell any that also hit +8%
Stock Selection — 3-Phase Scan:
Phase 1 — Technical scoring on a watchlist of ~80 stocks:
- RSI score: buy signal if RSI < 40, sell signal if RSI > 70 (weight: 30%)
- Moving average momentum: compare price to 20-day MA (weight: 40%)
- MACD: bullish if MACD line is above signal line (weight: 30%)
- Combine into a score from -1 to +1, take the top 10 stocks
Phase 2 — AI sentiment via Gemini 2.5 Flash on the top 10:
- Fetch last 6 hours of news headlines per stock from Finnhub API
- Skip stocks with no recent headlines
- Send headlines to Gemini 2.5 Flash, ask it to return JSON:
{"action": "buy"|"hold", "confidence": 0.0-1.0, "reason": "..."}- Only consider stocks where action is “buy” and confidence >= 0.70
- Add a 1-second delay between each Gemini call to avoid rate limits
- Final score = technical score × 0.5 + Gemini confidence × 0.5
- Skip any stock with earnings reporting within the next 3 days (Finnhub earnings calendar)
Phase 3 — Volume confirmation:
- Only enter if today’s volume is at least 80% of the 20-day average volume
- Low-volume moves are false breakouts — skip and try the next candidate
Comparative Exit Logic:
- When position P&L >= +8%, run the same 3-phase scan (excluding current holding)
- If scan finds a strong candidate: sell current position, buy the new one (rotation)
- If no candidate found: hold current position, track peak price, enforce 3% trailing stop from peak
- Re-evaluate every 15 minutes until either rotated or trailing stop triggers
Execution:
- Use Alpaca Python SDK with a live account
- Buy using fractional notional orders
- Track all positions in a local
state.jsonfile: symbol, entry price, qty, notional, peak_price, timestamp- Check exits first on every run, then look for new entries
Telegram Notifications:
- On buy: symbol, entry price, amount invested, target price (+8%), Gemini’s reason
- On sell: symbol, entry/exit price, P&L in $ and %, reason (take profit / rotation / trailing stop)
- On rotation: “Rotated ORCL → SMCI (+12.3%, candidate score 0.82)”
APIs needed (load from .env using python-dotenv):
ALPACA_LIVE_KEY,ALPACA_LIVE_SECRETFINNHUB_API_KEYGEMINI_API_KEYTELEGRAM_BOT_TOKEN,TELEGRAM_CHAT_IDLog every action to
trader.logwith UTC timestamps. Skip all execution if the market is closed.
Tips Before You Run It
- Test on paper trading first — Alpaca has a free paper (simulated) account, use it before touching real money
- Start small — even $500 is enough to see it work in real conditions
- Don’t fight the no-stop-loss rule — stocks recover. Panic selling locks in losses permanently
- Watch the logs —
trader.logtells you exactly why every decision was made - Trust the rotation — when the bot sells a winner to buy something else, that’s the strategy working, not a bug
Built with Python, Alpaca, Finnhub, and Google Gemini. Code written entirely through Claude Code. Hosted and orchestrated with OpenClaw. Questions? Drop them in the comments.