/ Каталог / Песочница / Alpaca
● Официальный alpacahq 🔑 Нужен свой ключ

Alpaca

автор alpacahq · alpacahq/alpaca-mcp-server

Let Claude research, backtest, and place trades on stocks, ETFs, options, and crypto via Alpaca — paper-first so you won't blow up your account.

Alpaca's official MCP wraps the Alpaca Trading and Market Data APIs. Pull quotes, bars, fundamentals, and positions; place/modify/cancel orders. Defaults to paper trading, which is exactly how you should learn this. Flip to live only once a strategy is proven.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

alpaca.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": [
        "alpaca-mcp-server"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": [
        "alpaca-mcp-server"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": [
        "alpaca-mcp-server"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": [
        "alpaca-mcp-server"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "alpaca",
      "command": "uvx",
      "args": [
        "alpaca-mcp-server"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "alpaca": {
      "command": {
        "path": "uvx",
        "args": [
          "alpaca-mcp-server"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add alpaca -- uvx alpaca-mcp-server

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: Alpaca

Generate a daily pre-market brief for your watchlist

👤 Active retail traders ⏱ ~10 min beginner

Когда использовать: You want a 30-second morning check on your 20 tickers before the open — overnight moves, earnings, obvious news.

Предварительные требования
  • Alpaca account (free paper) — alpaca.markets → sign up → API keys on the dashboard
  • Watchlist of symbols — Plain list like [AAPL, MSFT, NVDA, ...]
Поток
  1. Pull overnight bar data
    For my watchlist [symbols], get yesterday's close and the latest pre-market quote. Compute % gap.✓ Скопировано
    → Table: symbol, prev_close, pre_open, gap_pct
  2. Flag outliers
    Which tickers are gapping more than 2% in either direction? Rank by gap magnitude.✓ Скопировано
    → Short 'needs attention' list
  3. Add context
    For each outlier, pull the latest news headlines from Alpaca news endpoint.✓ Скопировано
    → Per-ticker bullet with likely cause

Итог: A 1-screen daily pre-market brief, same shape every day, no manual clicking.

Подводные камни
  • Free market data is IEX-only and lags; quotes may not match your broker — Fine for overnight/EOD analysis; if you need SIP feed, upgrade to Alpaca's paid data plan
Сочетать с: notion

Paper-trade a simple rules-based strategy

👤 Algo-trading beginners ⏱ ~30 min intermediate

Когда использовать: You have a rule like 'buy SPY when 5-day return < -3%, sell after +2% or 5 trading days' and want to run it live on paper money.

Предварительные требования
  • Paper account keys configured — Use APCA_API_BASE_URL=https://paper-api.alpaca.markets
  • A written rule — Entry, exit, position size, max loss — all explicit before coding anything
Поток
  1. Check account and positions
    Show my paper account equity, buying power, and current open positions.✓ Скопировано
    → Clean account snapshot
  2. Evaluate entry condition today
    Get SPY's last 5 daily bars. Compute 5-day return. If it's < -3% and I don't already hold SPY, place a market buy for $5000 notional. Otherwise do nothing.✓ Скопировано
    → Either an order id or an explicit 'no action'
  3. Log today's decision
    Append a row to /trades/journal.csv: date, condition_met, action, order_id, fill_price.✓ Скопировано
    → Journal row written

Итог: An auditable daily run of a simple strategy against paper money, with a journal you can review.

Подводные камни
  • Accidentally running against live keys during testing — Keep a very obvious check at the start: confirm the account number matches your paper account before placing any order
  • Claude forgets yesterday's position and double-buys — Always fetch current positions before evaluating entry; never rely on memory
Сочетать с: filesystem

Rebalance a portfolio to target allocations

👤 DIY investors with a target allocation ⏱ ~20 min intermediate

Когда использовать: Quarterly: bring 60/30/10 (US/INTL/bonds) back to target without manually computing share counts.

Предварительные требования
  • Target allocation defined — e.g. VTI 60%, VXUS 30%, BND 10%
Поток
  1. Measure drift
    Get my positions and current prices. Compute current weight per symbol vs target [paste targets]. Show drift in $ and %.✓ Скопировано
    → Per-symbol drift table
  2. Propose trades
    Propose the minimum set of buys/sells to bring weights within 1% of target. Show expected commissions (likely $0) and estimated slippage.✓ Скопировано
    → Order plan
  3. Execute with confirmation
    Before placing: summarize the plan in 3 lines and wait for my 'yes'. On yes, submit as market-on-open orders.✓ Скопировано
    → Orders placed with ids; equity matches target within 1%

Итог: A clean quarterly rebalance with a written record of why each trade happened.

Подводные камни
  • Taxable account: every rebalance triggers gains/losses — Prefer new-contribution rebalancing or tax-lot-aware exits; run only in IRA if unsure
Сочетать с: filesystem

Scan an options chain for short-dated put premium

👤 Option income traders (cash-secured puts / covered calls) ⏱ ~25 min advanced

Когда использовать: You want to find the best cash-secured put to sell on tickers you'd be happy to own, weekly.

Предварительные требования
  • Options-enabled Alpaca account — Enable in account settings; paper works for learning
Поток
  1. Fetch chain + greeks
    Get the options chain for [ticker] expiring next Friday, puts only, strikes within 5% of spot. Include bid, ask, mid, delta, IV.✓ Скопировано
    → Chain table
  2. Rank by annualized yield
    Compute annualized return-on-cash for each strike assuming assignment. Filter delta between -0.15 and -0.30. Rank top 5.✓ Скопировано
    → Ranked short list
  3. Place sell-to-open with a limit at mid
    Place a sell-to-open limit order for 1 contract of the #1 strike at the mid. GTC, day-only.✓ Скопировано
    → Order id returned

Итог: A repeatable weekly income routine with a conservative risk screen.

Подводные камни
  • Selling puts on companies you wouldn't want to own — Hard rule: only trade this strategy on 10 tickers you've pre-approved as long-term holds
  • Illiquid strikes with huge bid-ask — fills never happen at mid — Filter for open_interest > 500 and spread < 5% of mid before ranking
Сочетать с: notion

Комбинации

Сочетайте с другими MCP — эффект x10

alpaca + notion

Daily pre-market brief delivered to a Notion page

Run my pre-market scan for watchlist and create a Notion page in 'Trading / Daily' with the results.✓ Скопировано
alpaca + filesystem

Trade journal: append every order and reason to a local CSV

After any place_order, append {ts, symbol, side, qty, reason} to /trading/journal.csv.✓ Скопировано
alpaca + postgres

Store daily equity curve for backtesting strategies

Every evening, INSERT today's account equity into the equity_curve table.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
get_account First call in any session — confirm you're on paper vs live free
get_positions Check current holdings before any entry logic free
get_bars symbol, timeframe, start, end, limit? Historical OHLCV for analysis and signals free (IEX) or paid (SIP)
get_latest_quote symbol Real-time price before placing an order free
place_order symbol, qty|notional, side, type, time_in_force, limit_price? Submit a new order (always paper-first) free (commission-free)
cancel_order order_id Cancel an open order before it fills free
get_options_chain underlying, expiration, side? Scan strikes for an options strategy free on Alpaca

Стоимость и лимиты

Во что обходится

Квота API
200 req/min on data API (free tier); trading API is effectively unthrottled at retail scale
Токенов на вызов
Account/positions: 200–500 tokens. Bars: scales with limit.
Деньги
Alpaca is commission-free. Paid market data plan ~$9/mo for SIP feed; free IEX feed is fine for most retail use.
Совет
Paper-trade every new strategy for at least 4 weeks before touching live money. It's free.

Безопасность

Права, секреты, радиус поражения

Минимальные скоупы: Account API key + secret — Alpaca doesn't have sub-scopes
Хранение учётных данных: APCA_API_KEY_ID, APCA_API_SECRET_KEY, and APCA_API_BASE_URL in env vars
Исходящий трафик: All calls to api.alpaca.markets or paper-api.alpaca.markets
Никогда не давайте: Sharing live keys with any third-party service, including code hosts

Устранение неполадок

Частые ошибки и исправления

403 forbidden.insufficient-permissions

Your keys are for the wrong environment (live vs paper). Match APCA_API_BASE_URL to the key pair.

Проверить: curl -H 'APCA-API-KEY-ID: ...' -H 'APCA-API-SECRET-KEY: ...' $APCA_API_BASE_URL/v2/account
422 buying_power insufficient

Your paper account reset, or you sized the trade beyond cash. Call get_account and recompute position size.

Bars return empty for recent timestamp

IEX feed has ~15-min delay on free tier, and doesn't serve every symbol. Use SIP or wait.

Order rejected: market closed

Default TIF is day; market-closed orders need time_in_force='opg' or 'cls' or switch to extended hours with extended_hours=true on limit orders.

Альтернативы

Alpaca в сравнении

АльтернативаКогда использоватьКомпромисс
Interactive Brokers MCPYou need international markets or futuresMore complex auth (gateway app required); learning curve
Polygon.io MCPYou only need market data, no tradingNo order execution; paid for full coverage

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills