Build 24/7 Trading Agent with Claude Routines
Create a persistent AI trading bot in Claude Code using Opus 4.7 routines: migrate strategy via files for memory, research with Perplexity, trade on Alpaca, log lessons, notify via ClickUp to beat S&P.
Stateless to Stateful: Memory Architecture for Persistent Agents
Claude Code routines run stateless each time—they wake up without prior context. To make the agent remember rules, strategies, and learn from trades, use files as persistent memory. Every routine reads key files (strategy.md, trade_log.md, research_log.md, portfolio.md), performs analysis/trades, then appends updates like lessons learned or new signals. This creates discipline over time without native state.
"The trading strategy is a piece of the work, but the memory architecture that you're going to use is going to be huge. Every time a routine fires... it wakes up essentially stateless. So, how do you make a stateless agent act disciplined and remember rules and learn over time? You do that with files and with context."
Manage context budget tightly: Each routine has ~200k tokens (despite 1M window, avoid rot). Prioritize: system instructions (10-20k), strategy files (20k), logs/portfolio (variable), research (fresh). Overloading causes dilution—test runs to measure usage.
Tech Stack Setup: APIs and Claude Environment
Start with brokerage: Sign up at alpaca.markets for paper trading (100k virtual funds) or live (verify identity, fund later). Generate API key ID and secret from dashboard—store securely, never in repos. Use paper first.
Research: Perplexity API key from settings > API platform. Alternative: Claude's native web_search/web_fetch, but Perplexity excels for market queries.
Notifications: ClickUp API token from settings > Apps > ClickUp API. Swap for Slack/Telegram if preferred.
Claude side: Download Claude Desktop app (claude.ai desktop download). Requires paid plan ($20+/mo). Use VS Code + Claude Code extension for file visibility during setup (free). Switch to Desktop for routine calendar management.
"Every platform has typically API keys. You just have to find them in the settings somewhere. If you can't find them, just do a quick perplexity or Google search or even ask claude code."
Defining and Migrating Trading Strategy
Extract human/AI strategy explicitly: Document signals (e.g., buy on undervalued fundamentals + momentum; sell on overbought RSI/MACD divergence), research routine (news, filings, earnings), position sizing. From prior OpenClaw agent: Bull bot beat S&P 8% in 30 days with $10k via team of sub-agents (analyst, risk manager).
Brain-dump into Claude Code: New project folder (e.g., trading-routine). Drop migrated files: agent_instructions.md, trading_strategy.md, trade_log.md, research_log.md, weekly_review.md, portfolio.md, signals.md. Chat in plan mode: "Migrate this OpenClaw trading bot to Claude routines—ingest files, organize project, use Perplexity for research."
Claude proposes layout: /memory/ folder for persistent files; slash-commands for skills (e.g., /research, /trade, /log); dry-run mode. Accept plan (auto-mode optional, costlier). It auto-organizes, rotates insecure keys, adds Perplexity integration.
If starting fresh: Prompt Claude as "wealth advisor—devise S&P-beating strategy via fundamentals (per benchmarks: Opus 4.7 scores 64.4% agentic financial analysis)." Leverage benchmarks: Strong on filings/thesis, not day-trading candlesticks.
"Think of this like you're teaching a kid to ride a bike... Start with paper trading... extract all of the strategy... the more context and details that you give it right now, the more it asks you questions, the better."
Guardrails, Phased Rollout, and Routine Scheduling
Embed rules before trading logic: Max 5% portfolio per position, daily loss cap (e.g., 2%), 3 new positions/week max, no options/crypto, only long equity. Toggle paper/live via env vars. Routine always checks memory first, simulates in dry-run.
Phased like bike training: 1) Observe/simulate. 2) Paper trades. 3) Small live positions. 4) Full throttle. Journal every decision for iteration.
Deploy routines in Claude Desktop: Calendar view—schedule cron-like: 6AM pre-market research, 8:30AM open, noon midday, 3PM close, Friday weekly review. Link GitHub repo or folder. Set env vars: ALPACA_KEY, ALPACA_SECRET, PERPLEXITY_KEY, CLICKUP_TOKEN.
Routine flow: Read memory → Perplexity research (news/earnings) → Analyze portfolio/signals → Decide trades (fundamentals-driven) → POST to Alpaca (/orders) → Log updates → ClickUp EOD summary (P&L vs S&P, lessons).
"Guard rails... max 5% of my portfolio per position. You could have a daily loss cap... only buy three new positions per week or no options ever."
Iteration and Production Tips
Monitor via ClickUp summaries, Alpaca dashboard. Manually intervene/tune strategy files post-runs. Opus 4.7 shines: Agentic judgment, self-verifying outputs for ambiguity like markets.
Free resource: 13-page PDF on Claude infra/folder structure (in creator's community classroom).
"4.7 was built for full throttle agentic work, judgment over ambiguity, and self-verifying outputs. So, it's perfect for these types of routines."
Key Takeaways
- Use files in /memory/ for stateless persistence: Read on wake, write lessons/trades on exit.
- Budget tokens like cash: Test <200k per routine, prioritize strategy/logs over fluff.
- Paper trade first, embed hard guardrails (position size, loss caps) in instructions.
- Migrate strategies via brain-dump chats; let Claude reorganize for routines.
- Schedule via Desktop calendar: Pre-market/midday/close for real-time adaptation.
- Perplexity > native search for market research; Alpaca for simple equity trades.
- Phased rollout: Simulate → paper → live small → full.
- EOD summaries to ClickUp for oversight; iterate weekly.
- Leverage Opus 4.7 benchmarks for fundamentals, not day-trading.
- Secure keys in env vars, rotate if exposed.