← 返回 Skills 市场
zijunl

Alpaca Py Cli

作者 Eugene Lin · GitHub ↗ · v2.0.0
cross-platform ⚠ suspicious
777
总下载
0
收藏
1
当前安装
13
版本数
在 OpenClaw 中安装
/install alpaca-py-cli
功能描述
AI agent skill for Alpaca Markets trading. Intelligent setup wizard (alpaca init) guides users through registration. Trade stocks/crypto, manage portfolios,...
使用说明 (SKILL.md)

Alpaca Trading (Python CLI) - OpenClaw Agent Skill

ClawHub GitHub

Trade stocks and crypto programmatically via Alpaca's API using a Python-based CLI tool.

⚠️ Security & Setup Requirements

IMPORTANT - READ BEFORE USE:

This skill stores API keys as environment variables in your shell config file.

What happens during setup:

  • alpaca init displays registration steps for agent automation
  • alpaca auth saves API keys to shell startup files (~/.zshrc, ~/.bashrc, or ~/.profile)
  • This creates persistent environment variables accessible to all shell sessions

Security considerations:

  • ✅ API keys are stored as environment variables (standard practice)
  • ✅ Paper trading by default (virtual money, no risk)
  • ⚠️ Keys in shell config are accessible to any process in that shell
  • ⚠️ Setup modifies user's shell configuration files

Recommended practices:

  1. Get user consent - Explain that setup will modify shell config
  2. Use paper trading keys - Test with virtual money first ($100k virtual)
  3. Least privilege - Use API keys with minimal required permissions
  4. Monitor activity - Check your Alpaca account regularly

For agents:

  • Get explicit user permission before running alpaca auth (saves keys to shell config)
  • alpaca init is safe to run - it only displays instructions
  • Use browser automation to complete registration steps automatically
  • After obtaining keys via browser, call alpaca auth to save them

Links:

Alpaca Trading (Python CLI)

ClawHub GitHub

Trade stocks and crypto programmatically via Alpaca's API using a Python-based CLI tool.

Links:

Overview

Manage your Alpaca Markets trading account using the alpaca CLI tool and Python SDK. Supports both paper trading (simulated) and live trading.

Installation

Recommended: Homebrew Python (avoids urllib3/LibreSSL warnings)

# Install Homebrew Python 3.11+
brew install [email protected]

# Install alpaca-py
/opt/homebrew/bin/pip3.11 install alpaca-py pytz

Alternative: System Python

pip3 install alpaca-py pytz

Note: System Python may show urllib3 warnings on macOS due to LibreSSL compatibility. Use Homebrew Python for a cleaner experience.

Configuration

Quick Setup with CLI

alpaca auth

This will interactively prompt you for:

  • API Key
  • Secret Key (hidden input)
  • Trading mode (Paper or Live)

The command automatically saves your credentials to your shell config file (~/.zshrc, ~/.bashrc, or ~/.profile).

Manual Setup

Alternatively, set these in your shell profile manually:

export ALPACA_API_KEY="your_api_key"
export ALPACA_SECRET_KEY="your_secret_key"
export ALPACA_PAPER="true"  # Use "false" for live trading

Get your API keys from https://alpaca.markets (Dashboard → API Keys)

Paper Trading (recommended for testing):

  • Use paper trading API keys
  • Virtual $100,000 starting balance
  • No real money at risk

Live Trading (real money):

  • Use live trading API keys
  • Real money, real risk
  • Test thoroughly with paper trading first

CLI Commands

Setup & Configuration

Configure Credentials

alpaca auth

Interactive setup wizard that guides you through:

  1. Enter API Key
  2. Enter Secret Key (hidden)
  3. Choose trading mode (Paper/Live)
  4. Automatically saves to shell config

Account & Market Info

Check Account

alpaca account

Shows:

  • Account number and status
  • Portfolio value, cash, buying power
  • P&L (equity, last equity)
  • Trading restrictions (pattern day trader, blocks)

Check Market Status

alpaca clock

Shows:

  • Market status (🟢 OPEN or 🔴 CLOSED)
  • Current time
  • Next open/close times

View Market Calendar

# Show next 30 trading days (default)
alpaca calendar

# Show next 7 trading days
alpaca calendar --days 7

Shows trading days with open/close times (Eastern Time).

View Portfolio History

# Default: 1 month, daily bars
alpaca history

# Last week
alpaca history --period 1W

# Last 3 months with hourly bars
alpaca history --period 3M --timeframe 1H

Periods: 1D, 1W, 1M, 3M, 1Y, all
Timeframes: 1Min, 5Min, 15Min, 1H, 1D

Shows:

  • Start and end equity
  • Total change ($ and %)
  • Recent history (last 10 data points)

Portfolio Management

View Positions

alpaca positions

Shows all current holdings with:

  • Symbol, quantity, current price
  • Entry price and market value
  • Unrealized P&L ($ and %)
  • Total portfolio value and P&L

Get Stock Quotes

# Single symbol
alpaca quote AAPL

# Multiple symbols
alpaca quote AAPL,TSLA,MSFT

Shows:

  • Bid and ask prices
  • Mid price and spread
  • Quote timestamp

Note: Quotes may show incomplete data when market is closed. Best used during market hours (9:30 AM - 4:00 PM ET).

Order Management

View Orders

# Show open orders (default)
alpaca orders

# Show all recent orders
alpaca orders --status all

# Show last 20 closed orders
alpaca orders --status closed --limit 20

Shows:

  • Order status with emoji indicators (⏳ pending, ✓ filled, ✗ canceled)
  • Symbol, side (BUY/SELL), quantity
  • Order ID and creation time
  • Fill price (if filled)

Place Orders

# Buy shares
alpaca buy AAPL 10

# Sell shares
alpaca sell AAPL 5

Places a market order that executes at market price when market is open.

Cancel Orders

# Cancel specific order
alpaca cancel \x3Corder_id>

# Cancel all open orders
alpaca cancel-all

Position Management

Close Positions

# Close specific position
alpaca close AAPL

# Close all positions (requires confirmation)
alpaca close-all

Note: close-all will prompt for confirmation before closing all positions.

Example Workflows

First Time Setup

# Configure credentials
alpaca auth

# Check account
alpaca account

# Check if market is open
alpaca clock

Trading Workflow

# Check current price
alpaca quote TSLA

# Check account balance
alpaca account

# Buy some shares
alpaca buy TSLA 5

# Check pending orders
alpaca orders

# View positions (after order fills)
alpaca positions

# Get updated quote
alpaca quote TSLA

# Sell some shares
alpaca sell TSLA 2

# Check order history
alpaca orders --status all

Portfolio Analysis

# View current positions
alpaca positions

# View portfolio history
alpaca history --period 1M

# Check market calendar
alpaca calendar --days 7

Risk Management

# Check all open orders
alpaca orders

# Cancel specific order
alpaca cancel \x3Corder_id>

# Cancel all orders
alpaca cancel-all

# Close specific position
alpaca close AAPL

# Close all positions
alpaca close-all

Automated Setup for Agents

When a user wants to start trading but hasn't configured Alpaca yet, agents can automate the entire setup process using browser automation.

Setup Workflow

  1. Run alpaca init - Displays clear registration steps
  2. Use browser automation to complete steps 1-3:
    • Navigate to https://alpaca.markets
    • Click "Sign Up" and fill registration form
    • Verify email (can use email skill to automate)
    • Log in and navigate to Dashboard → API Keys → Paper Trading
    • Generate new API key pair
    • Extract both keys (API Key and Secret Key)
  3. Run alpaca auth - Save the extracted keys to shell config

Example Agent Flow

User: "I want to start trading stocks"

Agent: 
1. Runs: alpaca init (gets registration steps)
2. Uses browser skill to:
   - Open https://alpaca.markets
   - Fill registration form with user info
   - Verify email automatically
   - Navigate to API Keys page
   - Generate and extract keys
3. Runs: alpaca auth (with extracted keys)
4. Confirms: "✓ Setup complete! You have $100k in paper money."

Key Points

  • alpaca init is non-interactive - just displays steps
  • Agents should use browser automation to follow the steps
  • alpaca auth requires user consent (modifies shell config)
  • After setup, verify with alpaca clock or alpaca account

Agent Usage

When the user asks about their portfolio or wants to trade:

  1. Configure credentials: Run alpaca auth for first-time setup
  2. Check market status: Run alpaca clock to see if market is open
  3. Check account: Run alpaca account to see current balance and buying power
  4. Get positions: Run alpaca positions to list current holdings
  5. View orders: Run alpaca orders to see pending/recent orders
  6. Get quotes: Run alpaca quote \x3Csymbols> to check current prices
  7. Place orders: Run alpaca buy/sell to execute trades
  8. Manage risk: Run alpaca cancel/close commands as needed

Safety Tips

  • Always test with paper trading first (ALPACA_PAPER=true)
  • Use alpaca auth to safely configure credentials (secret key is hidden)
  • Check alpaca clock before trading to see if market is open
  • Check quotes before placing orders to understand current prices
  • Check account.buying_power before placing orders
  • Use TimeInForce.DAY to auto-cancel unfilled orders at market close
  • Monitor positions regularly with alpaca positions
  • Check order status with alpaca orders
  • Review portfolio performance with alpaca history
  • Use alpaca cancel-all to quickly cancel all pending orders
  • Use alpaca close-all with caution (requires confirmation)
  • Set stop-loss orders for risk management
  • Never share your API keys publicly

Market Hours

US stock market hours (Eastern Time):

  • Regular hours: 9:30 AM - 4:00 PM ET
  • Pre-market: 4:00 AM - 9:30 AM ET
  • After-hours: 4:00 PM - 8:00 PM ET

Orders placed outside market hours will be queued and executed when market opens.

Quotes may show incomplete or stale data when market is closed.

Use alpaca clock to check current market status.

Troubleshooting

urllib3 Warning (LibreSSL)

If you see:

NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently using LibreSSL

Solution: Install and use Homebrew Python 3.11+ which uses OpenSSL:

brew install [email protected]
/opt/homebrew/bin/pip3.11 install alpaca-py pytz

Then update the script shebang to use Homebrew Python:

sed -i '' '1s|#!/usr/bin/env python3|#!/opt/homebrew/bin/python3.11|' ~/.openclaw/workspace/skills/alpaca-py-cli/scripts/alpaca

Missing pytz

If you see:

ModuleNotFoundError: No module named 'pytz'

Solution:

pip3 install pytz
# or
/opt/homebrew/bin/pip3.11 install pytz

Command Not Found

If alpaca command is not found, use the full path:

~/.openclaw/workspace/skills/alpaca-py-cli/scripts/alpaca

Or add to PATH in your shell config:

export PATH="$HOME/.openclaw/workspace/skills/alpaca-py-cli/scripts:$PATH"

Files

  • CLI Tool: ~/.openclaw/workspace/skills/alpaca-py-cli/scripts/alpaca
  • Config: Environment variables in ~/.zshrc (or ~/.bashrc, ~/.profile)

Official Documentation

Initialization (For Agents)

See the "Automated Setup for Agents" section above for the complete workflow.

Quick summary:

  1. Run alpaca init to see registration steps
  2. Use browser automation to complete registration and extract API keys
  3. Run alpaca auth to save keys (with user consent)
  4. Verify with alpaca clock or alpaca account

The new alpaca init command is non-interactive and agent-friendly - it simply displays clear steps that an agent can follow using browser automation.

安全使用建议
This skill appears to do what it claims (control Alpaca via a Python CLI), but it will write your API keys into shell startup files and can persist changes to your shell environment. Before installing or letting an agent run setup: 1) Decide to use paper-trading keys (recommended) and only grant minimal permissions. 2) Require explicit, manual user consent for running alpaca auth/init — do not allow autonomous agent runs that perform auth. 3) Inspect any changes the setup will make to ~/.zshrc, ~/.bashrc, or ~/.profile and consider storing keys in a secure vault or restricted file instead of exporting them globally. 4) Verify the pip packages (alpaca-py, pytz) come from the official sources. 5) Ask the skill/author to clarify the setup.json/README step that edits a script in ~/.openclaw/workspace (the bundle contains no scripts) before running automatic shebang edits. If you want a lower-risk workflow, run setup and auth manually on an isolated environment (or container) and revoke keys after testing.
功能分析
Type: OpenClaw Skill Name: alpaca-py-cli Version: 2.0.0 This skill is classified as suspicious due to its inherent high-risk capabilities, specifically the modification of shell configuration files (~/.zshrc, ~/.bashrc, ~/.profile) to persistently store sensitive API keys for financial trading. While the skill's documentation (SKILL.md, README.md, setup.json) provides extensive and explicit warnings against autonomous agent actions and emphasizes the need for user consent for setup, the capability to alter shell configuration and handle financial credentials represents a significant security concern if misused or if an agent fails to adhere to the provided safety instructions. There is no evidence of malicious intent such as data exfiltration or backdoor installation; rather, the documentation actively attempts to mitigate prompt injection risks by instructing agents to seek explicit user permission for sensitive operations.
能力评估
Purpose & Capability
Name/description (Alpaca trading CLI) match the declared requirements: python3 and Alpaca API credentials (ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_PAPER) are appropriate for this purpose.
Instruction Scope
SKILL.md explicitly instructs running interactive commands (alpaca init / alpaca auth) that save credentials to shell startup files. That is within the skill's scope, but it is high-impact: setup will modify ~/.zshrc/ ~/.bashrc/ ~/.profile and create environment variables readable by any process in those shells. The docs correctly warn agents not to run setup autonomously and require user consent. Minor inconsistency: setup.json and README reference a scripts path (~/.openclaw/workspace/skills/.../scripts/alpaca) and suggest editing a shebang there, but no script file is present in the skill bundle — this mismatch should be clarified before proceeding.
Install Mechanism
There is no install spec (instruction-only). Dependencies are Python packages (alpaca-py, pytz) installable via pip; no arbitrary remote archive downloads or unusual installers are required. Risk is limited to installing standard pip packages.
Credentials
Required environment variables are exactly the Alpaca API credentials expected for a trading CLI. The skill does not request unrelated secrets. The documentation warns that these variables will be stored in shell config (reasonable for a CLI but increases exposure).
Persistence & Privilege
Skill does not request always:true and does not ask to modify other skills or system-wide agent settings. The only persistence is writing API keys into user shell startup files (explicitly documented). This is a normal behavior for a CLI but is a lasting change and increases blast radius if agents or other processes have shell access.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install alpaca-py-cli
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /alpaca-py-cli 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.0.0
Major update: Simplify init for agent automation. Remove interactive wizard, make it non-interactive with clear steps for browser automation. Reduce code by 21%. Add comprehensive agent automation workflow documentation. Philosophy change: manual and auto are the same for agents.
v1.7.2
- Updated internal metadata in _meta.json; no changes to skill features or documentation. - No user-facing changes.
v1.0.1
- Updated SKILL.md documentation to clarify that the `close-all` command prompts for confirmation before closing all positions. - No changes to code or functionality; this release is documentation-only.
v1.7.0
SECURITY UPDATE: Addressed ClawHub security scan findings. Declared required environment variables in metadata. Added explicit warnings about shell config modifications. Clarified that setup requires user interaction and consent. Added comprehensive security documentation. Agents must NOT run setup autonomously.
v1.6.1
Updated skill description and README. Enhanced documentation with comparison table, latest features highlight, and clearer value proposition for AI agents. Emphasizes intelligent setup wizard and token-efficient design.
v1.6.0
Major refactor: Moved detailed guidance from SKILL.md to CLI runtime. Reduced token usage by ~250 lines while improving user experience. The init wizard now shows comprehensive step-by-step instructions during execution. Agents just run 'alpaca init' and let the CLI handle everything.
v1.5.0
Major documentation update: Added comprehensive agent workflow guide for init command. Includes detailed automatic/manual mode workflows, agent best practices, example conversations, error handling, and security guidelines. Makes it crystal clear how agents should guide users through setup.
v1.4.0
Renamed setup-wizard to init. Shorter, more intuitive command following common CLI conventions (git init, npm init). Easier for agents to remember and use.
v1.3.0
Added intelligent setup-wizard command. Agents can now automatically detect email access and choose between automatic (browser + email) or manual setup. Defaults to paper trading for safety. Full automation coming soon.
v1.2.1
Emphasized AI Agent Skill nature. Updated README to clearly explain this is for OpenClaw agents with natural language examples and agent usage patterns.
v1.2.0
Added GitHub and ClawHub links. Enhanced documentation with badges, better formatting, and cross-references between GitHub and ClawHub.
v1.1.0
Added calendar and history commands. Calendar shows upcoming trading days with market hours. History displays portfolio performance over time with configurable periods and timeframes.
v1.0.0
Initial release: Python-based CLI for Alpaca Markets trading with paper/live support, portfolio management, stock quotes, and order execution. Includes Homebrew Python support to avoid urllib3/LibreSSL warnings.
元数据
Slug alpaca-py-cli
版本 2.0.0
许可证
累计安装 4
当前安装数 1
历史版本数 13
常见问题

Alpaca Py Cli 是什么?

AI agent skill for Alpaca Markets trading. Intelligent setup wizard (alpaca init) guides users through registration. Trade stocks/crypto, manage portfolios,... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 777 次。

如何安装 Alpaca Py Cli?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install alpaca-py-cli」即可一键安装,无需额外配置。

Alpaca Py Cli 是免费的吗?

是的,Alpaca Py Cli 完全免费(开源免费),可自由下载、安装和使用。

Alpaca Py Cli 支持哪些平台?

Alpaca Py Cli 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Alpaca Py Cli?

由 Eugene Lin(@zijunl)开发并维护,当前版本 v2.0.0。

💬 留言讨论