Video summary

How To Actually Build a Trading Bot With Claude Code (Fully Automated)

Main summary

Key takeaways

Technology

AutoTrader Tutorial: Fully Automated Trading Bot (No Manual Coding)

A guide to building a fully automated trading bot using Claude Code + Cloud Code in VS Code, connected to a real broker (Alpaca). The system includes:

  • Regime detection (hidden Markov models)
  • Dynamic allocation
  • Risk controls (including hard circuit breakers)
  • Backtesting (walk-forward)
  • A live dashboard for monitoring

What the Bot Does (Core Behavior)

The bot is designed to operate as a real trading system—not a simple indicator script.

  • Detects market regime/environment (e.g., crash, bear, neutral, bull, euphoria) using Hidden Markov Models (HMMs).
  • Automatically adjusts portfolio allocations based on the detected regime.
  • Places real orders via brokerage (Alpaca), after validation using paper trading.
  • Manages risk with circuit breakers, implemented as a hardcoded safety layer independent of the AI/model decisions.
  • Adapts dynamically as market conditions change.

Emphasis: it’s not an “RSI crossover” style bot; it includes order execution + validation + risk management.


Completed Product (Dashboard Features)

The finished dashboard includes:

  • Detected regime + confidence score
  • Portfolio value and buying power (live from brokerage)
  • Regime counts summarized by category
  • Price/volume visualization with regime overlays
  • Signal feed listing the bot’s historical trades (allocations, entry, stops, P&L)
  • Risk controls panel, showing:
    • Circuit breakers
    • Drawdown limits
    • Leverage status
  • A list of possible regimes: crash, bear, neutral, bull, euphoria

System Architecture (5 Components)

The bot is described as five layers:

  1. Brain: HMM-based market environment/regime classifier
  2. Allocation: volatility/regime-driven position sizing and strategy orchestration
  3. Safety (risk net): circuit breakers + kill-switch behavior (hardcoded thresholds)
  4. Brokerage: Alpaca API integration for order placement and account/position tracking
  5. Dashboard: real-time monitoring UI

Key Technological Details & Safeguards

1) Regime Detection (HMM) with Anti Look-Ahead Bias

  • Uses HMMs with price action and volume to classify the current market environment.
  • The number of regimes is determined automatically by testing values between 3 and 7 (not hardcoded).
  • Regime labeling is sorted by mean return.
  • Look-ahead bias mitigation:
    • Notes that the default HMM predict can process the full sequence and cause leakage.
    • Replaces it with the forward algorithm only to avoid look-ahead.

2) Regime Stability Filter

Adds a persistence requirement so the bot doesn’t react to noise:

  • Requires at least three consecutive bars before acting.
  • If regimes flicker too often (described as “flickers more than four times in the past 20 bars”), the bot:
    • avoids action or reduces effectiveness
    • indirectly reduces position sizes
  • Logs regime changes as warnings when uncertainty is high.

3) Allocation Strategy (Regime → Exposure / Leveraging)

The allocation layer changes exposure based on volatility regime. Example mentioned:

  • Low volatility → invest ~95% of the portfolio with ~1.25x leverage
  • Medium volatility → stay invested if trend conditions are met (customizable)

Tutorial guidance: swap in your own strategy logic while keeping the allocation framework.

4) Walk-Forward Backtesting + Validation

Implements a robust backtesting approach:

  • Walk-forward optimization/backtesting with:
    • In-sample: 252 trading days
    • Out-of-sample: ~6 months
  • Uses “blind” testing on historical forward segments to reduce pure hindsight fitting.
  • Includes realism modeling:
    • Slippage simulation
  • Computes metrics:
    • total return, Sharpe ratio, max drawdown, win rate, total trades
    • broken down by regime and confidence buckets
  • Benchmark comparisons:
    • Buy and hold
    • 200-day SMA trend following
    • Random entry/random allocation changes under the same risk rules
  • Adds stress tests:
    • injects random crash events (~10–15% drops in a day) to test robustness
  • Notes this stage is the longest due to iteration needed to pass benchmarks/stress tests.

5) Risk Management Layer (“Veto Power” Over Strategy)

Hardcoded circuit breakers override strategy decisions regardless of model outputs.

Example thresholds mentioned:

  • Down 2% in a day → cut sizes in half
  • Down 3% → close everything
  • Down 5% in a week → halve sizes
  • Down 10% from peak → stop the system completely
    • writes a block file requiring manual deletion to resume

Additional position-level controls:

  • Each trade risks max ~1% of portfolio (configurable)
  • Leverage controls (configurable)
  • Order validation and correlation checks:
    • before opening new positions, the bot checks whether the new trade is correlated with existing positions to avoid redundant exposure

Project Setup with Cloud Code (Implementation Workflow)

  • Uses VS Code + Cloud Code extension.
  • Begins with project scaffolding (Python “Regime Trader”) with a standardized structure including:

    • settings/credentials/HMM engine
    • regime strategies (volatility/volume allocation)
    • risk manager (position sizing, leverage, drawdown limits)
    • Alpaca API wrapper / order executor
    • market data + feature engineering + logging + alerts
    • backtester + performance calculations
    • tests
    • requirements + environment handling
  • Emphasizes security and environment isolation:

    • uses .env for Alpaca API key + secret key
    • .env is ignored to avoid credential leakage
    • instructs not to share API keys with Claude/Cloud Code chat

Brokerage Integration (Alpaca)

  • Create an Alpaca account and start with paper trading.
  • Connect by providing:
    • Alpaca base URL/endpoint
    • API key
    • secret key
  • Test by placing a paper trade (example: Nvidia market buy), then confirming it appears in the Alpaca dashboard.
  • Notes:
    • Alpaca supports stocks/options/crypto (tutorial says not futures)
    • fee/alternative mentioned: Alpaca is generally free up to volume limits; consider IBKR if volume is very high

Execution Loop (Automation)

After wiring components (described as “phase seven”), the runtime sequence includes:

  • load config
  • connect to Alpaca + verify account
  • check market hours
  • train HMMs
  • initialize risk manager + position tracker + data feeds
  • run the main loop per bar close (default described as 5-minute bars)
  • includes shutdown handling and error handling for:
    • broker/API failures
    • feed drops

Monitoring & UI

  • Combines monitoring/logging and an optional Streamlit dashboard.
  • Demonstrates final dashboard output on a paper account when markets are open:
    • regime detection output (e.g., “bear regime with 100% confidence”)
    • risk status (circuit breaker/leverage)
    • trade tracking and P&L

Explicit Guidance Emphasized in the Tutorial

  • Paper trade for at least a month, and monitor:
    • why the bot rebalanced
    • why it stayed put
    • when the risk manager overruled actions
  • Iteration workflow:
    • adjust allocation/strategy parameters per regime
    • backtest across tickers and time periods
    • review rebalance behavior
    • continuously improve using Cloud Code
  • Strategy validation is central:
    • extensive testing, including “no look-ahead” checks, is required before live trading.

Main Speakers / Sources

  • Main speaker/source: the video author/instructor (references “my previous videos,” and provides directions throughout)
  • Technical framework mentioned:
    • Claude Code / Cloud Code
    • Hidden Markov Models (HMMs)
    • Alpaca brokerage API
    • Streamlit (for dashboard)
  • Testing/statistics approach referenced:
    • walk-forward backtesting engines
    • look-ahead bias mitigation via forward algorithm

Original video