Alpaca Trading (Python CLI) - OpenClaw Agent Skill


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 - INLINECODE1 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
- Use paper trading keys - Test with virtual money first ($100k virtual)
- Least privilege - Use API keys with minimal required permissions
- Monitor activity - Check your Alpaca account regularly
For agents:
- - Get explicit user permission before running
alpaca auth (saves keys to shell config) - INLINECODE3 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:
- - ClawHub: https://clawhub.ai/skills/alpaca-py-cli
- GitHub: https://github.com/zijunl/alpaca-py-cli
- Alpaca Markets: https://alpaca.markets
Alpaca Trading (Python CLI)


Trade stocks and crypto programmatically via Alpaca's API using a Python-based CLI tool.
Links:
- - ClawHub: https://clawhub.ai/skills/alpaca-py-cli
- GitHub: https://github.com/zijunl/alpaca-py-cli
- Alpaca Markets: https://alpaca.markets
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)
CODEBLOCK0
Alternative: System Python
CODEBLOCK1
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
CODEBLOCK2
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:
CODEBLOCK3
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
CODEBLOCK4
Interactive setup wizard that guides you through:
- 1. Enter API Key
- Enter Secret Key (hidden)
- Choose trading mode (Paper/Live)
- Automatically saves to shell config
Account & Market Info
Check Account
CODEBLOCK5
Shows:
- - Account number and status
- Portfolio value, cash, buying power
- P&L (equity, last equity)
- Trading restrictions (pattern day trader, blocks)
Check Market Status
CODEBLOCK6
Shows:
- - Market status (🟢 OPEN or 🔴 CLOSED)
- Current time
- Next open/close times
View Market Calendar
CODEBLOCK7
Shows trading days with open/close times (Eastern Time).
View Portfolio History
CODEBLOCK8
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
CODEBLOCK9
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
CODEBLOCK10
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
CODEBLOCK11
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
CODEBLOCK12
Places a market order that executes at market price when market is open.
Cancel Orders
CODEBLOCK13
Position Management
Close Positions
CODEBLOCK14
Note: close-all will prompt for confirmation before closing all positions.
Example Workflows
First Time Setup
CODEBLOCK15
Trading Workflow
CODEBLOCK16
Portfolio Analysis
CODEBLOCK17
Risk Management
CODEBLOCK18
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 - 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
CODEBLOCK19
Key Points
- -
alpaca init is non-interactive - just displays steps - Agents should use browser automation to follow the steps
- INLINECODE13 requires user consent (modifies shell config)
- After setup, verify with
alpaca clock or INLINECODE15
Agent Usage
When the user asks about their portfolio or wants to trade:
- 1. Configure credentials: Run
alpaca auth for first-time setup - Check market status: Run
alpaca clock to see if market is open - Check account: Run
alpaca account to see current balance and buying power - Get positions: Run
alpaca positions to list current holdings - View orders: Run
alpaca orders to see pending/recent orders - Get quotes: Run
alpaca quote <symbols> to check current prices - Place orders: Run
alpaca buy/sell to execute trades - 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 INLINECODE29
- Check order status with INLINECODE30
- Review portfolio performance with INLINECODE31
- 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:
CODEBLOCK20
Solution: Install and use Homebrew Python 3.11+ which uses OpenSSL:
CODEBLOCK21
Then update the script shebang to use Homebrew Python:
CODEBLOCK22
Missing pytz
If you see:
CODEBLOCK23
Solution:
CODEBLOCK24
Command Not Found
If alpaca command is not found, use the full path:
CODEBLOCK25
Or add to PATH in your shell config:
CODEBLOCK26
Files
- - CLI Tool: INLINECODE36
- Config: Environment variables in
~/.zshrc (or ~/.bashrc, ~/.profile)
Official Documentation
- - Python SDK: https://alpaca.markets/docs/python-sdk/
- API Reference: https://docs.alpaca.markets/reference/
- Trading API: https://docs.alpaca.markets/docs/trading-api
- Market Data API: https://docs.alpaca.markets/docs/market-data
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 - Use browser automation to complete registration and extract API keys
- Run
alpaca auth to save keys (with user consent) - Verify with
alpaca clock or INLINECODE43
The new alpaca init command is non-interactive and agent-friendly - it simply displays clear steps that an agent can follow using browser automation.
Alpaca Trading (Python CLI) - OpenClaw Agent 技能


通过基于 Python 的 CLI 工具,使用 Alpaca API 以编程方式交易股票和加密货币。
⚠️ 安全与设置要求
重要 - 使用前请阅读:
此技能将 API 密钥作为环境变量存储在您的 shell 配置文件中。
设置过程中会发生什么:
- - alpaca init 显示代理自动化的注册步骤
- alpaca auth 将 API 密钥保存到 shell 启动文件(~/.zshrc、~/.bashrc 或 ~/.profile)
- 这会创建所有 shell 会话均可访问的持久环境变量
安全考虑:
- - ✅ API 密钥作为环境变量存储(标准做法)
- ✅ 默认使用模拟交易(虚拟资金,无风险)
- ⚠️ shell 配置文件中的密钥可被该 shell 中的任何进程访问
- ⚠️ 设置会修改用户的 shell 配置文件
推荐做法:
- 1. 获取用户同意 - 解释设置将修改 shell 配置
- 使用模拟交易密钥 - 先用虚拟资金测试(10 万美元虚拟资金)
- 最小权限 - 使用具有最小必要权限的 API 密钥
- 监控活动 - 定期检查您的 Alpaca 账户
对于代理:
- - 在运行 alpaca auth(将密钥保存到 shell 配置)前,获取用户明确许可
- alpaca init 可安全运行 - 它仅显示说明
- 使用浏览器自动化自动完成注册步骤
- 通过浏览器获取密钥后,调用 alpaca auth 保存它们
链接:
- - ClawHub:https://clawhub.ai/skills/alpaca-py-cli
- GitHub:https://github.com/zijunl/alpaca-py-cli
- Alpaca Markets:https://alpaca.markets
Alpaca Trading (Python CLI)


通过基于 Python 的 CLI 工具,使用 Alpaca API 以编程方式交易股票和加密货币。
链接:
- - ClawHub:https://clawhub.ai/skills/alpaca-py-cli
- GitHub:https://github.com/zijunl/alpaca-py-cli
- Alpaca Markets:https://alpaca.markets
概述
使用 alpaca CLI 工具和 Python SDK 管理您的 Alpaca Markets 交易账户。支持模拟交易(模拟)和实盘交易。
安装
推荐:Homebrew Python(避免 urllib3/LibreSSL 警告)
bash
安装 Homebrew Python 3.11+
brew install python@3.11
安装 alpaca-py
/opt/homebrew/bin/pip3.11 install alpaca-py pytz
备选:系统 Python
bash
pip3 install alpaca-py pytz
注意: 由于 LibreSSL 兼容性问题,系统 Python 在 macOS 上可能显示 urllib3 警告。使用 Homebrew Python 可获得更干净的体验。
配置
使用 CLI 快速设置
bash
alpaca auth
这将交互式提示您输入:
- - API 密钥
- 秘密密钥(隐藏输入)
- 交易模式(模拟或实盘)
该命令自动将您的凭据保存到 shell 配置文件(~/.zshrc、~/.bashrc 或 ~/.profile)。
手动设置
或者,在您的 shell 配置文件中手动设置:
bash
export ALPACAAPIKEY=yourapikey
export ALPACASECRETKEY=yoursecretkey
export ALPACA_PAPER=true # 实盘交易使用 false
从 https://alpaca.markets(仪表盘 → API 密钥)获取您的 API 密钥
模拟交易(推荐用于测试):
- - 使用模拟交易 API 密钥
- 虚拟 10 万美元起始余额
- 无真实资金风险
实盘交易(真实资金):
- - 使用实盘交易 API 密钥
- 真实资金,真实风险
- 先用模拟交易彻底测试
CLI 命令
设置与配置
配置凭据
bash
alpaca auth
交互式设置向导,引导您完成:
- 1. 输入 API 密钥
- 输入秘密密钥(隐藏)
- 选择交易模式(模拟/实盘)
- 自动保存到 shell 配置
账户与市场信息
检查账户
bash
alpaca account
显示:
- - 账户编号和状态
- 投资组合价值、现金、购买力
- 盈亏(权益、上次权益)
- 交易限制(日内交易者模式、冻结)
检查市场状态
bash
alpaca clock
显示:
- - 市场状态(🟢 开盘或 🔴 收盘)
- 当前时间
- 下次开盘/收盘时间
查看市场日历
bash
显示接下来 30 个交易日(默认)
alpaca calendar
显示接下来 7 个交易日
alpaca calendar --days 7
显示带有开盘/收盘时间(东部时间)的交易日。
查看投资组合历史
bash
默认:1 个月,日线
alpaca history
上周
alpaca history --period 1W
过去 3 个月,小时线
alpaca history --period 3M --timeframe 1H
周期: 1D、1W、1M、3M、1Y、all
时间框架: 1Min、5Min、15Min、1H、1D
显示:
- - 起始和结束权益
- 总变化(金额和百分比)
- 近期历史(最近 10 个数据点)
投资组合管理
查看持仓
bash
alpaca positions
显示所有当前持仓,包含:
- - 代码、数量、当前价格
- 入场价格和市值
- 未实现盈亏(金额和百分比)
- 总投资组合价值和盈亏
获取股票报价
bash
单个代码
alpaca quote AAPL
多个代码
alpaca quote AAPL,TSLA,MSFT
显示:
注意: 市场收盘时报价可能显示不完整数据。最佳使用时间为交易时段(美国东部时间上午 9:30 - 下午 4:00)。
订单管理
查看订单
bash
显示未成交订单(默认)
alpaca orders
显示所有近期订单
alpaca orders --status all
显示最近 20 个已关闭订单
alpaca orders --status closed --limit 20
显示:
- - 订单状态,带表情符号指示(⏳ 待处理、✓ 已成交、✗ 已取消)
- 代码、方向(买入/卖出)、数量
- 订单 ID 和创建时间
- 成交价格(如已成交)
下订单
bash
买入股票
alpaca buy AAPL 10
卖出股票
alpaca sell AAPL 5
下达市价单,在市场开盘时以市价执行。
取消订单
bash
取消特定订单
alpaca cancel
取消所有未成交订单
alpaca cancel-all
持仓管理
平仓
bash
平仓特定持仓
alpaca close AAPL
平仓所有持仓(需要确认)
alpaca close-all
注意: close-all 在平仓所有持仓前会提示确认。
示例工作流程
首次设置
bash
配置凭据
alpaca auth
检查账户
alpaca account
检查市场是否开盘
alpaca clock
交易工作流程
bash
检查当前价格
alpaca quote TSLA
检查账户余额
alpaca account
买入一些股票
alpaca buy TSLA 5
检查待处理订单
alpaca orders
查看持仓(订单成交后