alpaca-trading-paper-trading
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAlpaca Paper Trading
Alpaca纸交易(Paper Trading)
Use this skill when you want your AI agent to preview, submit, inspect, and manage paper-trading orders using Alpaca's Trading API.
This skill is written for you, a Trading API user working with your own Alpaca paper-trading account, credentials, and local workspace. Your agent should make assumptions visible, protect secrets, and confirm order details before submission.
This is the generic (implementation-agnostic) version of the paper-trading skill. It describes the workflow, safety gates, and output contract without binding to any specific execution tool. You can use the Alpaca Python SDK (), the REST API directly, JavaScript/TypeScript, Go, C#, or any tool that speaks to the Trading API. CLI-specific and MCP-specific companion skills exist for users who prefer those execution paths — see §10 for links.
alpaca-py当您希望AI Agent使用Alpaca的Trading API来预览、提交、查看和管理纸交易订单时,请使用此技能。
本技能专为您这类Trading API用户设计,您将使用自己的Alpaca纸交易账户、凭证和本地工作区。您的Agent应明确展示所有假设、保护机密信息,并在提交前确认订单详情。
这是纸交易技能的通用(与实现无关)版本。它描述了工作流程、安全关卡和输出约定,不绑定任何特定执行工具。您可以使用Alpaca Python SDK()、直接调用REST API、JavaScript/TypeScript、Go、C#,或任何可对接Trading API的工具。针对偏好特定执行路径的用户,我们还提供了CLI专属版和MCP专属版配套技能——见第10节获取链接。
alpaca-py0 - How your AI agent should use this skill
0 - AI Agent如何使用本技能
-
Start with your job. Identify what the signal is — a backtest output, a manual trade idea, a scheduled trigger, or an automated system event. Your agent reads any associated context (backtest run folder, strategy description, alert payload) to understand the intent.
-
Reiterate the strategy logic. Your agent restates the strategy interpretation in plain language — entry/exit conditions, indicator parameters, position sizing, and any assumptions — and confirms with you that the interpretation is correct before proceeding.
-
Gather and confirm ALL detailed configurations before execution. Your agent collects every order parameter explicitly:
- Timing of execution (immediate, scheduled, conditional)
- Asset class (US equity, US options, crypto)
- Symbol(s)
- Side (buy / sell)
- Quantity or notional amount
- Order type (market, limit, stop, stop_limit, trailing_stop)
- Time-in-force (day, gtc, ioc, fok, opg, cls)
- Limit price and/or stop price if applicable
- Extended-hours flag
- Risk controls (max position size, max notional, stop-loss, take-profit)
- Margin usage
-
Confirm which paper account is being used. Your agent verifies that the paper account's configuration meets the strategy's requirements — options approval level, crypto enabled, margin vs cash account, PDT status. It does not assume features are enabled without checking.
-
Show a complete order preview table before submission. Every order gets a visual preview with all parameters displayed, estimated notional, and buying power check. No order is ever submitted without a preview.
-
Ask about confirmation preference. Your agent asks whether you want explicit confirmation before each order submission, or whether you prefer auto-submit mode. It respects your preference for the session. Default: confirmation ON.
-
Submit the order to the paper-trading environment only. Your agent verifies the environment is paper before every submission. It never submits to live.
-
Return complete post-submission details. After submission, your agent returns the order ID, status, submitted payload summary, and next inspection steps.
-
Monitor and update on order lifecycle.
- Filled → how many shares/contracts, at what price, and how the fill changes portfolio risk.
- Partially filled → current fill vs remaining quantity, average fill price so far.
- Rejected → the rejection reason and specific remediation suggestions.
- Canceled → who canceled (you, system, broker) and why.
-
Never place live trades. If live credentials are detected — base URL without theprefix, or a profile set to live — your agent stops immediately and warns you. This is a hard block, not a soft warning.
paper-
-
明确任务目标:确定信号来源——回测输出、手动交易想法、定时触发或自动化系统事件。Agent会读取相关上下文(回测运行文件夹、策略描述、告警负载)以理解您的意图。
-
复述策略逻辑:Agent用通俗易懂的语言重述对策略的解读——入场/离场条件、指标参数、仓位大小以及所有假设,并在继续执行前确认您认可该解读。
-
执行前收集并确认所有详细配置:Agent会明确收集每一项订单参数:
- 执行时机(立即执行、定时执行、条件触发)
- 资产类别(美国股票、美国期权、加密货币)
- 交易代码(Symbol)
- 交易方向(买入/卖出)
- 数量或名义金额
- 订单类型(市价单、限价单、止损单、止损限价单、跟踪止损单)
- 有效期限(day、gtc、ioc、fok、opg、cls)
- 适用的限价和/或止损价格
- 盘前/盘后交易标志
- 风险控制(最大仓位、最大名义金额、止损、止盈)
- 保证金使用情况
-
确认使用的纸交易账户:Agent会验证纸交易账户的配置是否符合策略要求——期权审批等级、加密交易权限、保证金/现金账户类型、日内交易(PDT)状态。Agent不会在未检查的情况下默认功能已启用。
-
提交前展示完整订单预览表格:每份订单都会以可视化方式预览所有参数、预估名义金额和购买力检查。未预览的订单绝不提交。
-
询问确认偏好:Agent会询问您是否希望在每份订单提交前进行明确确认,还是偏好自动提交模式。Agent会在会话期间遵循您的偏好,默认设置为:开启确认。
-
仅向纸交易环境提交订单:Agent会在每次提交前验证环境为纸交易环境,绝不向实盘环境提交订单。
-
返回完整的提交后详情:提交完成后,Agent会返回订单ID、状态、提交负载摘要以及后续查看步骤。
-
监控并更新订单生命周期:
- 已成交 → 成交的股份/合约数量、成交价格,以及成交对投资组合风险的影响。
- 部分成交 → 当前成交量与剩余数量、截至目前的平均成交价。
- 已拒绝 → 拒绝原因及具体补救建议。
- 已取消 → 取消方(您、系统、经纪商)及取消原因。
-
绝不进行实盘交易:如果检测到实盘凭证——基础URL不含前缀,或配置文件设为实盘——Agent会立即停止操作并向您发出警告。这是强制拦截,而非软性提醒。
paper-
1 - Prerequisites
1 - 前置条件
- Alpaca paper-trading account — free at alpaca.markets
- Paper API key and secret key stored in environment variables (,
APCA_API_KEY_ID) or SDK/CLI profile — never pasted into chatAPCA_API_SECRET_KEY - Paper base URL: (for REST) or appropriate SDK configuration pointing to the paper environment
https://paper-api.alpaca.markets - For options: options trading must be enabled on the paper account with the appropriate approval level (level 1 for covered calls and cash-secured puts, level 2 to buy calls and puts, level 3 for spreads and straddles)
- For crypto: crypto trading must be enabled on the paper account
- SDK / language runtime (choose one):
- Python 3.10+ with (recommended)
alpaca-py - JavaScript/TypeScript with (v4+, first-party and actively maintained)
@alpacahq/alpaca-trade-api - Go with — the
github.com/alpacahq/alpaca-trade-api-go/v3suffix is required; without it you pull the v1 path/v3 - C# with (first-party). Community SDKs exist for Java and others.
Alpaca.Markets - Direct REST API calls via ,
curl,httpx, or any HTTP clientrequests
- Python 3.10+ with
- Network access to Alpaca APIs ()
paper-api.alpaca.markets
- Alpaca纸交易账户 — 可在alpaca.markets免费注册
- 纸交易API密钥和密钥密码 — 存储在环境变量(、
APCA_API_KEY_ID)或SDK/CLI配置文件中,切勿粘贴到聊天窗口APCA_API_SECRET_KEY - 纸交易基础URL:(用于REST调用)或指向纸交易环境的SDK配置
https://paper-api.alpaca.markets - 期权交易要求:纸交易账户需启用期权交易,并具备相应审批等级(Level 1可备兑看涨期权和现金担保看跌期权,Level 2可买入看涨/看跌期权,Level 3可进行价差和跨式期权交易)
- 加密交易要求:纸交易账户需启用加密货币交易
- SDK / 语言运行环境(任选其一):
- Python 3.10+ 搭配 (推荐)
alpaca-py - JavaScript/TypeScript 搭配 (v4+,官方维护)
@alpacahq/alpaca-trade-api - Go 搭配 — 必须包含
github.com/alpacahq/alpaca-trade-api-go/v3后缀,否则会拉取v1版本/v3 - C# 搭配 (官方版本)。社区还提供Java等其他语言的SDK
Alpaca.Markets - 通过、
curl、httpx或任何HTTP客户端直接调用REST APIrequests
- Python 3.10+ 搭配
- 网络权限:可访问Alpaca APIs()
paper-api.alpaca.markets
2 - Gather inputs
2 - 收集输入参数
Required inputs
必填输入项
| Input | Description | Default |
|---|---|---|
| Where the trade idea comes from (backtest, manual, automation) | Must be provided |
| Ticker symbol (e.g., | Must be provided |
| | Must be provided |
| Number of shares/contracts OR dollar amount (use | Must be provided |
| | |
| | |
| 输入项 | 描述 | 默认值 |
|---|---|---|
| 交易想法的来源(回测、手动输入、自动化系统) | 必须提供 |
| 交易代码(例如: | 必须提供 |
| | 必须提供 |
| 股份/合约数量 或 美元金额(股份/合约用 | 必须提供 |
| | |
| | 股票默认 |
Per-asset-class constraints
按资产类别划分的约束
The API rejects combinations outside this matrix, so your agent validates before submitting rather than after:
| Asset class | Order types | Time-in-force | Order classes |
|---|---|---|---|
| | | |
| | | |
| | | |
Treat this as guidance for constructing orders, not as a hard pre-submission gate. Alpaca's sources disagree on the options row: the OpenAPI / descriptions say / with only, while the Options Trading page and the Placing Orders matrix both allow and both allow / on single-leg orders. The two product pages agree against the spec blob, so this table follows them. Default to for options as the conservative choice, but let Alpaca reject rather than pre-blocking something the matrix permits.
TimeInForceOrderTypemarketlimitdaygtcstopstop_limitdayConstraints that cut across order type:
- Extended hours requires type with
limitordayTIF. Everything else is rejected.gtc - Trailing stop accepts only and
day.gtc - Notional orders cannot be combined with and cannot be replaced — cancel and resubmit instead. For equities they additionally require
qtytype withmarketTIF; crypto notional orders are market-type and use the crypto TIF set (day/gtc), so the equitiesiocrestriction does not apply to them.day - Bracket, OCO, and OTO are equities-only, require or
day, and do not support extended hours.gtc - carries up to 4 legs and is how multi-leg options strategies are expressed.
mleg
API会拒绝不符合以下矩阵的组合,因此Agent会在提交前验证,而非提交后:
| 资产类别 | 支持的订单类型 | 支持的有效期限 | 订单类别 |
|---|---|---|---|
| | | |
| | | |
| | | |
将此作为构建订单的参考,而非严格的提交前拦截规则。Alpaca的资料对期权行描述不一致:OpenAPI的/说明仅支持/搭配,但期权交易页面和下单矩阵均允许,且单腿期权允许/。本表格以产品页面的一致描述为准。保守起见,期权默认使用,但对于矩阵允许的类型,由Alpaca自行拒绝,而非提前拦截。
TimeInForceOrderTypemarketlimitdaygtcstopstop_limitday跨订单类型的约束:
- 盘前/盘后交易 要求使用类型,搭配
limit或day有效期限,其他类型均会被拒绝。gtc - 跟踪止损单 仅支持和
day。gtc - 名义金额订单 不能与组合,且不可修改——如需调整需取消后重新提交。股票的名义金额订单额外要求
qty类型搭配market有效期限;加密货币的名义金额订单为市价单,使用加密货币的有效期限设置(day/gtc),因此股票的ioc限制不适用于加密货币。day - 括号单、OCO、OTO 仅适用于股票,要求或
day,不支持盘前/盘后交易。gtc - 最多支持4条腿,用于表达多腿期权策略。
mleg
Optional inputs
可选输入项
| Input | Description | Default |
|---|---|---|
| Required for | None |
| Required for | None |
| For trailing stop orders (one or the other, not both) | None |
| Allow extended-hours execution (equities only; | |
| User-supplied idempotency key (max 128 chars) | Auto-generated UUID |
| Whether your agent asks for explicit confirmation before each order | |
| Max position size, max notional, max loss threshold | None (recommended to set) |
| | Inferred from symbol format |
| | |
| | Inferred from context |
| 输入项 | 描述 | 默认值 |
|---|---|---|
| | 无 |
| | 无 |
| 跟踪止损单使用(二选一,不可同时使用) | 无 |
| 允许盘前/盘后交易(仅适用于股票;需 | |
| 用户提供的幂等键(最多128字符) | 自动生成UUID |
| Agent是否在每份订单提交前请求明确确认 | |
| 最大仓位、最大名义金额、最大亏损阈值 | 无(建议设置) |
| | 从交易代码格式推断 |
| | |
| | 从上下文推断 |
Strategy confirmation checklist
策略确认清单
Before proceeding past the configuration phase, your agent must confirm each of these with you:
- Strategy logic interpretation is correct — the agent's restatement of your strategy matches your intent
- Timing — immediate execution, or scheduled/conditional (e.g., "only if price drops below $180")
- Asset class and symbol are correct — the right ticker, the right contract (for options), the right pair (for crypto)
- Order parameters match the strategy intent — type, side, quantity, prices, TIF all align with what you want
- Paper account is configured for this asset class — options approval, crypto enabled, margin type
- Risk controls are set (or explicitly waived) — you've acknowledged position sizing, stop-loss, and concentration limits
在完成配置阶段前,Agent必须与您确认以下每一项:
- 策略逻辑解读正确 — Agent重述的策略与您的意图一致
- 执行时机 — 立即执行,或定时/条件触发(例如:"仅当价格跌至180美元以下时执行")
- 资产类别和交易代码正确 — 正确的代码、期权合约、加密货币对
- 订单参数符合策略意图 — 类型、方向、数量、价格、有效期限均与您的需求一致
- 纸交易账户已配置对应资产类别权限 — 期权审批等级、加密交易权限、保证金类型
- 已设置风险控制(或明确放弃) — 您已确认仓位大小、止损和集中度限制
3 - Source-of-truth references
3 - 权威参考资料
| Source | URL | Used for |
|---|---|---|
| Trading API overview | https://docs.alpaca.markets/us/docs/trading-api | API capabilities and structure |
| Working with orders | https://docs.alpaca.markets/us/docs/working-with-orders | Order submission, replacement, cancellation |
| Orders on Alpaca | https://docs.alpaca.markets/us/docs/orders-at-alpaca | Order types, TIF values, status lifecycle |
| Paper trading | https://docs.alpaca.markets/us/docs/paper-trading | Paper environment behavior and limitations |
| Working with positions | https://docs.alpaca.markets/us/docs/working-with-positions | Position retrieval and management |
| Working with account | https://docs.alpaca.markets/us/docs/working-with-account | Account state, buying power, day trade count |
| Working with assets | https://docs.alpaca.markets/us/docs/working-with-assets | Tradability checks, asset attributes |
| Options trading | https://docs.alpaca.markets/us/docs/options-trading | Options order specifics, approval levels |
| Crypto trading | https://docs.alpaca.markets/us/docs/crypto-trading | Crypto order specifics, supported pairs |
| Alpaca disclosures | https://alpaca.markets/disclosures | Required disclosure language |
| 来源 | URL | 用途 |
|---|---|---|
| Trading API概述 | https://docs.alpaca.markets/us/docs/trading-api | API功能和结构 |
| 订单操作指南 | https://docs.alpaca.markets/us/docs/working-with-orders | 订单提交、修改、取消 |
| Alpaca订单说明 | https://docs.alpaca.markets/us/docs/orders-at-alpaca | 订单类型、有效期限值、状态生命周期 |
| 纸交易说明 | https://docs.alpaca.markets/us/docs/paper-trading | 纸交易环境的行为和限制 |
| 仓位操作指南 | https://docs.alpaca.markets/us/docs/working-with-positions | 仓位查询和管理 |
| 账户操作指南 | https://docs.alpaca.markets/us/docs/working-with-account | 账户状态、购买力、日内交易次数 |
| 资产操作指南 | https://docs.alpaca.markets/us/docs/working-with-assets | 交易可行性检查、资产属性 |
| 期权交易指南 | https://docs.alpaca.markets/us/docs/options-trading | 期权订单细节、审批等级 |
| 加密交易指南 | https://docs.alpaca.markets/us/docs/crypto-trading | 加密订单细节、支持的交易对 |
| Alpaca披露信息 | https://alpaca.markets/disclosures | 必备披露内容 |
4 - Workflow
4 - 工作流程
Phase 1: Strategy Confirmation
阶段1:策略确认
Step 1 — Identify the signal source.
Your agent determines where the trade idea comes from:
- Backtest output: read the run folder (,
notes.md) to extract the strategy logic, confirmed parameters, and the last signal. Parse the signal for symbol, side, quantity, and any price targets.summary.json - Manual idea: you describe the trade in natural language. Your agent extracts the parameters and asks clarifying questions.
- Automated system: a webhook, alert, or scheduled trigger. Your agent reads the payload and maps it to order parameters.
Step 2 — Reiterate the strategy logic.
Your agent restates the complete strategy interpretation in plain language:
- What triggers a trade (entry condition)
- What exits a trade (exit condition, stop-loss, take-profit)
- Indicator parameters (e.g., "20-day SMA crossover with 50-day SMA")
- Position sizing rules (e.g., "risk 1% of portfolio per trade")
- Any assumptions your agent is making (e.g., "assuming you want to enter at market price")
Step 3 — Confirm the interpretation.
Your agent asks you to confirm or correct the restatement. It does not proceed until you confirm. If you correct it, your agent restates the corrected version and asks again.
步骤1 — 识别信号来源
Agent确定交易想法的来源:
- 回测输出:读取运行文件夹(、
notes.md)提取策略逻辑、已确认参数和最新信号。解析信号中的交易代码、方向、数量及价格目标。summary.json - 手动想法:您用自然语言描述交易,Agent提取参数并询问澄清问题。
- 自动化系统:Webhook、告警或定时触发。Agent读取负载并映射为订单参数。
步骤2 — 复述策略逻辑
Agent用通俗易懂的语言重述完整的策略解读:
- 触发交易的条件(入场条件)
- 结束交易的条件(离场条件、止损、止盈)
- 指标参数(例如:"20日均线与50日均线交叉")
- 仓位大小规则(例如:"每笔交易风险不超过投资组合的1%")
- Agent做出的任何假设(例如:"默认您希望以市价入场")
步骤3 — 确认解读
Agent请求您确认或修正重述内容,在您确认前不会继续执行。如果您进行修正,Agent会重述修正后的版本并再次请求确认。
Phase 2: Configuration Agreement
阶段2:配置达成一致
Step 4 — Gather all order parameters.
Using the inputs table from §2, your agent collects every required and optional parameter. It asks for anything not already specified.
Step 5 — Show parameter attribution.
For each parameter, your agent shows:
- The value being used
- Whether it was provided by you, inferred from context (e.g., asset class from symbol format), or defaulted to a standard value
Example:
Symbol: AAPL (provided)
Side: buy (provided)
Quantity: 50 shares (provided)
Order type: limit (provided)
Limit price: $180.00 (provided)
TIF: day (defaulted — standard for equities)
Extended hrs: false (defaulted)
Client order: a7b3c9d1-... (auto-generated)Step 6 — Confirm timing.
Your agent confirms execution timing:
- Immediate: submit now, during current market session
- Scheduled: submit at a specific time (your agent notes this requires external scheduling)
- Conditional: submit only when a condition is met (your agent notes this requires monitoring logic)
If the timing is not immediate, your agent explains what tooling you'd need and whether it can help set it up (see §4 Phase 8 for deployment guidance).
Step 7 — Confirm asset class specifics.
For US Equity:
- Verify the symbol is tradable via the assets endpoint
- Check fractional share eligibility if quantity includes decimals
- Confirm extended-hours eligibility if is
extended_hours(onlytrueorders qualify)limit - Note T+1 settlement for sell proceeds
For US Options:
- Validate the contract symbol follows OCC symbology:
AAPL250718C00200000- Root symbol (AAPL), expiration (250718 = July 18, 2025), call/put (C/P), strike price × 1000 (00200000 = $200.00)
- Confirm expiration date, strike price, and put/call
- Confirm position intent: buy-to-open, buy-to-close, sell-to-open, sell-to-close
- Note the contract multiplier: 1 contract = 100 shares of the underlying
- Confirm the account's options approval level meets the strategy requirements
- Warn about expiration risk if the expiration is within 5 trading days
For Crypto:
- Confirm the pair format (e.g., ,
BTC/USD)ETH/USD - Note 24/7 market — no market-hours constraints
- Check minimum order size for the pair
- Confirm the account has crypto trading enabled
Step 8 — Confirm risk controls.
Your agent asks about risk controls:
- Max position size: maximum number of shares/contracts in a single position
- Max portfolio allocation: maximum percentage of portfolio equity in one symbol
- Stop-loss: price or percentage at which to exit a losing position
- Take-profit: price or percentage at which to take gains
If you haven't set any risk controls, your agent recommends you consider them. It asks whether you want to set them now or proceed without them. If you proceed without them, your agent notes this in the session log.
Step 9 — Confirm margin usage.
Your agent checks:
- Margin classification via — the account object has no
account.multiplierfield.account_typeis a limited-margin, cash-style account;1is a Reg T margin account with 2x intraday and overnight buying power;2is a PDT account with 4x intraday and 2x overnight4 - Whether shorting is permitted (), since the strategy may require it
account.shorting_enabled - Current buying power () and, for options,
account.buying_poweraccount.options_buying_power - Current equity ()
account.equity - If margin is involved, the maintenance margin requirement ()
account.maintenance_margin
步骤4 — 收集所有订单参数
使用第2节的输入表格,Agent收集所有必填和可选参数,询问未明确指定的内容。
步骤5 — 展示参数来源
对于每个参数,Agent会展示:
- 使用的值
- 该值是由您提供、从上下文推断(例如:从交易代码格式推断资产类别),还是默认为标准值
示例:
交易代码: AAPL (提供)
交易方向: 买入 (提供)
数量: 50股 (提供)
订单类型: 限价 (提供)
限价: $180.00 (提供)
有效期限: 当日有效 (默认 — 股票标准设置)
盘前/盘后: false (默认)
客户端订单ID: a7b3c9d1-... (自动生成)步骤6 — 确认执行时机
Agent确认执行时机:
- 立即执行:当前交易时段内立即提交
- 定时执行:在特定时间提交(Agent会说明这需要外部调度工具)
- 条件触发:仅当满足特定条件时提交(Agent会说明这需要监控逻辑)
如果不是立即执行,Agent会解释所需工具以及是否可协助设置(见第4阶段8的部署指南)。
步骤7 — 确认资产类别细节
美国股票:
- 通过资产端点验证交易代码可交易
- 如果数量包含小数,检查是否支持碎股交易
- 如果设为
extended_hours,确认是否符合盘前/盘后交易资格(仅限价单符合)true - 注意卖出资金T+1到账
美国期权:
- 验证合约代码符合OCC格式:
AAPL250718C00200000- 基础代码(AAPL)、到期日(250718 = 2025年7月18日)、看涨/看跌(C/P)、行权价×1000(00200000 = 200.00美元)
- 确认到期日、行权价和看涨/看跌类型
- 确认仓位意图:买入开仓、买入平仓、卖出开仓、卖出平仓
- 注意合约乘数:1张合约对应100股标的股票
- 确认账户的期权审批等级满足策略要求
- 如果到期日在5个交易日内,提醒到期风险
加密货币:
- 确认交易对格式(例如:、
BTC/USD)ETH/USD - 注意市场24/7开放——无交易时段限制
- 检查交易对的最小订单量
- 确认账户已启用加密货币交易
步骤8 — 确认风险控制
Agent询问风险控制设置:
- 最大仓位:单个仓位的最大股份/合约数量
- 最大投资组合占比:单个交易代码占投资组合权益的最大百分比
- 止损:退出亏损仓位的价格或百分比
- 止盈:锁定收益的价格或百分比
如果您未设置任何风险控制,Agent会建议您考虑设置,并询问是否现在设置或继续无风险控制执行。如果您选择继续,Agent会在会话日志中记录此情况。
步骤9 — 确认保证金使用
Agent检查:
- 通过确认保证金分类——账户对象没有
account.multiplier字段。account_type为有限保证金(类现金账户);1为Reg T保证金账户,日内和隔夜购买力为2倍;2为PDT账户,日内购买力4倍,隔夜2倍4 - 是否允许卖空(),因为策略可能需要
account.shorting_enabled - 当前购买力(),对于期权还需检查
account.buying_poweraccount.options_buying_power - 当前权益()
account.equity - 如果涉及保证金,检查维持保证金要求()
account.maintenance_margin
Phase 3: Paper Account Verification
阶段3:纸交易账户验证
Step 10 — Verify the environment is paper.
Your agent checks the base URL, SDK configuration, or CLI profile to confirm the environment is paper, not live.
| Check | Paper | Live (BLOCKED) |
|---|---|---|
| REST base URL | | |
| SDK config | | |
| CLI profile | paper profile selected | live profile selected |
If live credentials are detected: STOP immediately. Your agent displays a clear warning and refuses to proceed. It does not offer to "switch to paper" on your behalf — you must reconfigure your credentials.
Step 11 — Fetch account status.
Your agent retrieves the account and verifies:
- is
statusorACTIVE— a paper-only account is valid for this skill and must not be blockedPAPER_ONLY - is
trading_blockedfalse - is
account_blockedfalse - is
trade_suspended_by_userfalse - is sufficient for the planned order
buying_power - for margin classification, which is also the only PDT signal available
multiplier
The Trading API account object carries no or field. Your agent must not read them. A of indicates a PDT account; if you need day-trade counts, derive them from rather than the account object.
pattern_day_traderdaytrade_countmultiplier4GET /v2/account/activitiesStep 12 — Verify options readiness (if trading options).
- Gate on , not
options_trading_level. The effective level is the minimum ofoptions_approved_leveland theoptions_approved_levelin account configuration, and Alpaca exposes it directly asmax_options_trading_level. An account approved for level 3 but configured to level 1 can only trade level 1.options_trading_level - Each level includes the ones below it:
- Level 0: options trading disabled
- Level 1: sell covered calls, sell cash-secured puts
- Level 2: buy calls, buy puts
- Level 3: spreads and straddles
- Alpaca does not offer naked short options at any level. If a strategy requires one, stop and say so rather than looking for a higher level.
- If is
options_trading_levelor below what the strategy needs, your agent stops and explains which level is required and how to request an upgrade0
Step 13 — Verify crypto readiness (if trading crypto).
- is
crypto_statusACTIVE - If crypto is not enabled, your agent stops and explains how to enable it on the account
Step 14 — Show account summary.
Your agent displays a summary of the account state:
┌─────────────────────────────────────────┐
│ PAPER ACCOUNT SUMMARY │
├──────────────┬──────────────────────────┤
│ Account ID │ ****-****-****-a1b2 │
│ Status │ ACTIVE │
│ Equity │ $100,000.00 │
│ Buying Power │ $100,000.00 │
│ Cash │ $100,000.00 │
│ Positions │ 3 open │
│ Multiplier │ 2 (Reg T margin) │
│ Options Lvl │ 2 (effective) │
│ Crypto │ ACTIVE │
└──────────────┴──────────────────────────┘步骤10 — 验证环境为纸交易
Agent检查基础URL、SDK配置或CLI配置文件,确认环境为纸交易,而非实盘。
| 检查项 | 纸交易 | 实盘(拦截) |
|---|---|---|
| REST基础URL | | |
| SDK配置 | | |
| CLI配置文件 | 选中纸交易配置文件 | 选中实盘配置文件 |
如果检测到实盘凭证:立即停止。Agent会显示明确警告并拒绝继续执行,不会主动为您"切换到纸交易"——您必须自行重新配置凭证。
步骤11 — 获取账户状态
Agent获取账户信息并验证:
- 为
status或ACTIVE——仅纸交易账户适用于本技能,不得拦截PAPER_ONLY - 为
trading_blockedfalse - 为
account_blockedfalse - 为
trade_suspended_by_userfalse - 足够执行计划订单
buying_power - 用于保证金分类,这也是唯一可用的PDT信号
multiplier
Trading API账户对象没有或字段,Agent不得读取这些字段。为表示PDT账户;如果需要日内交易次数,需从推导,而非从账户对象获取。
pattern_day_traderdaytrade_countmultiplier4GET /v2/account/activities步骤12 — 验证期权交易准备情况(如果交易期权)
- 以为准,而非
options_trading_level。实际等级为options_approved_level和账户配置中options_approved_level的最小值,Alpaca直接暴露为max_options_trading_level。例如,账户获批Level 3但配置为Level 1,仅能进行Level 1交易。options_trading_level - 每个等级包含其下所有等级:
- Level 0:禁用期权交易
- Level 1:卖出备兑看涨期权、卖出现金担保看跌期权
- Level 2:买入看涨/看跌期权
- Level 3:价差和跨式期权交易
- Alpaca不提供任何等级的裸卖空期权。如果策略需要裸卖空,Agent会停止执行并说明情况,而非寻找更高等级。
- 如果为
options_trading_level或低于策略要求,Agent会停止执行并解释所需等级及升级方式0
步骤13 — 验证加密交易准备情况(如果交易加密货币)
- 为
crypto_statusACTIVE - 如果未启用加密交易,Agent会停止执行并解释如何在账户中启用
步骤14 — 展示账户摘要
Agent展示账户状态摘要:
┌─────────────────────────────────────────┐
│ 纸交易账户摘要 │
├──────────────┬──────────────────────────┤
│ 账户ID │ ****-****-****-a1b2 │
│ 状态 │ ACTIVE │
│ 权益 │ $100,000.00 │
│ 购买力 │ $100,000.00 │
│ 现金 │ $100,000.00 │
│ 未平仓仓位 │ 3个 │
│ 保证金乘数 │ 2 (Reg T保证金) │
│ 期权等级 │ 2 (实际有效) │
│ 加密交易状态 │ ACTIVE │
└──────────────┴──────────────────────────┘Phase 4: Order Preview
阶段4:订单预览
Step 15 — Build the order payload.
Your agent constructs the complete API request body with all confirmed parameters. It sets a unique for idempotency.
client_order_idStep 16 — Display the order preview.
Your agent shows a complete order preview table:
┌─────────────────────────────────────────┐
│ ORDER PREVIEW │
├──────────────┬──────────────────────────┤
│ Environment │ PAPER │
│ Symbol │ AAPL │
│ Side │ buy │
│ Quantity │ 10 shares │
│ Order Type │ limit │
│ Limit Price │ $185.50 │
│ Time-in-Force│ day │
│ Extended Hrs │ no │
│ Client Order │ abc-123-def │
│ Est. Notional│ ~$1,855.00 │
│ Buying Power │ $98,500.00 (sufficient) │
└──────────────┴──────────────────────────┘For options, the preview also shows:
- Contract:
AAPL 07/18/2025 $200 Call - Contracts: 2
- Multiplier: 100 shares/contract
- Est. Premium: ~$3.50 × 2 × 100 = $700.00
- Position intent: buy-to-open
For crypto, the preview also shows:
- Pair: BTC/USD
- Market: 24/7 (always open)
- Notional: $500.00 (if notional order)
Step 17 — Confirmation-ON mode.
If is , your agent asks:
confirmation_modeonSubmit this order? (yes / no)
It waits for your explicit before proceeding. Any response other than a clear affirmative is treated as "no" and your agent asks what you'd like to change.
yesStep 18 — Confirmation-OFF mode.
If is , your agent informs you:
confirmation_modeoffConfirmation mode is OFF. This order will be submitted now. The preview is shown above for your review.
Your agent then proceeds to submission.
步骤15 — 构建订单负载
Agent使用所有已确认的参数构建完整的API请求体,并设置唯一的以保证幂等性。
client_order_id步骤16 — 展示订单预览
Agent展示完整的订单预览表格:
┌─────────────────────────────────────────┐
│ 订单预览 │
├──────────────┬──────────────────────────┤
│ 交易环境 │ 纸交易 │
│ 交易代码 │ AAPL │
│ 交易方向 │ 买入 │
│ 数量 │ 10股 │
│ 订单类型 │ 限价 │
│ 限价 │ $185.50 │
│ 有效期限 │ 当日有效 │
│ 盘前/盘后 │ 否 │
│ 客户端订单ID │ abc-123-def │
│ 预估名义金额 │ ~$1,855.00 │
│ 剩余购买力 │ $98,500.00 (充足) │
└──────────────┴──────────────────────────┘对于期权,预览还会显示:
- 合约:
AAPL 07/18/2025 $200 看涨期权 - 合约数量:2张
- 乘数:100股/合约
- 预估权利金:~$3.50 × 2 × 100 = $700.00
- 仓位意图:买入开仓
对于加密货币,预览还会显示:
- 交易对:BTC/USD
- 市场:24/7(全天候开放)
- 名义金额:$500.00(如果是名义金额订单)
步骤17 — 确认开启模式
如果为,Agent会询问:
confirmation_modeon是否提交此订单?(是/否)
Agent会等待您明确回复"是"后再继续执行。任何非明确肯定的回复均视为"否",Agent会询问您需要修改的内容。
步骤18 — 确认关闭模式
如果为,Agent会告知您:
confirmation_modeoff确认模式已关闭。此订单将立即提交,上述预览供您查看。
随后Agent会执行提交操作。
Phase 5: Order Submission
阶段5:订单提交
Step 19 — Submit the order.
Your agent sends the order to the paper trading API via your chosen execution method (SDK, REST, CLI, or MCP tool). The endpoint is against the paper base URL.
POST /v2/ordersStep 20 — Capture the response.
On success, your agent captures:
- (order ID)
id client_order_id- — usually
status, meaning Alpaca received the order and routed it.newmeans received but not yet routed and is common outside trading hours;acceptedandpending_neware documented as rareaccepted_for_bidding created_atsubmitted_at- ,
symbol,side,qty,typetime_in_force - All echoed fields from the API response
Step 21 — Handle submission failure.
If the submission fails, your agent:
-
Captures the full error response (HTTP status code, error message, error code)
-
Shows you the error in plain language
-
Suggests specific remediation.documents exactly two error responses, and they do not mean what their generic HTTP names suggest:
POST /v2/orders- → insufficient buying power or shares, not an auth problem. Show current buying power versus required, or current position versus the quantity being sold
403 Forbidden - → input parameters not recognized. Show which ones, and check them against the per-asset-class matrix in section 2
422 Unprocessable Entity - → rate limited; honor
429 Too Many Requestsand back offRetry-After - → credential problem. Stop; do not retry with the same credentials
401 Unauthorized - Network timeout → verify whether the order was received before doing anything else
A non-tradable or unknown symbol surfaces asfrom the order endpoint, not422. Your agent validates the symbol against404beforehand, where a genuinely unknown symbol does returnGET /v2/assets/{symbol_or_asset_id}. Crypto requires the old symbology without a slash (404), and any slash that remains must be URL-encoded (BTCUSD) or the request is malformed./v2/assets/BTC%2FUSDT -
Saves the failed attempt to the session log
-
Does NOT automatically retry for non-idempotent submissions. If it's unclear whether the order was received (e.g., network timeout), your agent checks existing orders byfirst.
client_order_id
步骤19 — 提交订单
Agent通过您选择的执行方式(SDK、REST、CLI或MCP工具)将订单发送到纸交易API,端点为纸交易基础URL下的。
POST /v2/orders步骤20 — 获取响应
提交成功后,Agent会记录:
- (订单ID)
id client_order_id- — 通常为
status,表示Alpaca已收到订单并路由;new表示已收到但尚未路由,在非交易时段常见;accepted和pending_new为文档记录的罕见状态accepted_for_bidding created_atsubmitted_at- 、
symbol、side、qty、typetime_in_force - API响应中的所有回显字段
步骤21 — 处理提交失败
如果提交失败,Agent会:
-
记录完整的错误响应(HTTP状态码、错误信息、错误代码)
-
用通俗易懂的语言向您展示错误
-
提供具体的补救建议。文档明确记录了两种错误响应,其含义与通用HTTP名称不同:
POST /v2/orders- → 购买力或股份不足,而非认证问题。显示当前购买力与所需金额、或当前仓位与卖出数量的差额。建议减少数量或平仓释放购买力。
403 Forbidden - → 输入参数不被识别。展示问题参数,并对照第2节的按资产类别划分的矩阵检查。
422 Unprocessable Entity - → 请求超限;遵循
429 Too Many Requests提示并退避。Retry-After - → 凭证问题。停止执行;不得使用相同凭证重试。
401 Unauthorized - 网络超时 → 在执行任何操作前,先验证订单是否已被接收。
不可交易或未知代码会在订单端点返回,而非422。Agent会提前通过404验证代码,真正未知的代码会在此处返回GET /v2/assets/{symbol_or_asset_id}。加密货币要求使用不带斜杠的旧格式(404),如果保留斜杠必须进行URL编码(BTCUSD),否则请求会格式错误。/v2/assets/BTC%2FUSDT -
将失败尝试记录到会话日志
-
不得自动重试非幂等提交。如果无法确认订单是否已被接收(例如网络超时),Agent会先通过检查现有订单。
client_order_id
Phase 6: Post-Submission Monitoring
阶段6:提交后监控
Step 22 — Fetch order status.
Immediately after a successful submission, your agent fetches the order by ID () to confirm the current status.
GET /v2/orders/{id}Step 23 — Return post-submission summary.
Your agent shows you:
Order submitted successfully.
Order ID: b1e2f3a4-5678-9012-cdef-abcdef123456
Status: accepted
Symbol: AAPL
Side: buy
Qty: 10
Type: limit
Limit Price: $185.50
TIF: day
Submitted at: 2026-07-26T15:30:00Z
Environment: PAPER
Next steps:
- Ask me to check the status of this order
- Ask me to cancel this order
- Ask me to show your current positions
- Ask me to show your portfolio summaryStep 24 — Order lifecycle updates.
Your agent tracks the order through its lifecycle and reports each transition:
Filled:
✅ Order FILLED
Order ID: b1e2f3a4-...
Symbol: AAPL
Side: buy
Filled Qty: 10 shares
Avg Fill Price: $185.32
Fill Time: 2026-07-26T15:30:05Z
Portfolio impact:
- AAPL position: 10 shares @ $185.32 (new position)
- Position value: $1,853.20
- Portfolio %: 1.85% of equity
- Buying Power: $98,146.80 (was $100,000.00)Partially filled:
⏳ Order PARTIALLY FILLED
Order ID: b1e2f3a4-...
Filled: 6 of 10 shares
Avg Fill Price: $185.35
Remaining: 4 shares (still working)Rejected:
❌ Order REJECTED
Order ID: b1e2f3a4-...
Reason: insufficient buying power
Details: Required ~$1,855.00, available $500.00
Remediation:
- Reduce order quantity
- Close existing positions to free buying power
- If this is unexpected, check your account for pending orders
consuming buying powerCanceled:
🚫 Order CANCELED
Order ID: b1e2f3a4-...
Canceled by: system
Reason: day order expired at market close (16:00 ET)
If you still want this position, consider:
- Resubmitting as a GTC order
- Waiting for the next market openReplaced:
🔄 Order REPLACED
Old Order ID: b1e2f3a4-...
New Order ID: c2d3e4f5-...
Changed:
Limit Price: $185.50 → $186.00
Quantity: 10 → 15步骤22 — 获取订单状态
提交成功后,Agent立即通过ID()获取订单状态以确认当前状态。
GET /v2/orders/{id}步骤23 — 返回提交后摘要
Agent向您展示:
订单提交成功。
订单ID: b1e2f3a4-5678-9012-cdef-abcdef123456
状态: accepted
交易代码: AAPL
交易方向: 买入
数量: 10
订单类型: 限价
限价: $185.50
有效期限: 当日有效
提交时间: 2026-07-26T15:30:00Z
交易环境: 纸交易
后续操作:
- 让我查询此订单状态
- 让我取消此订单
- 让我展示您当前的仓位
- 让我展示您的投资组合摘要步骤24 — 订单生命周期更新
Agent会跟踪订单的生命周期,并报告每个状态转换:
已成交:
✅ 订单已成交
订单ID: b1e2f3a4-...
交易代码: AAPL
交易方向: 买入
成交数量: 10股
平均成交价: $185.32
成交时间: 2026-07-26T15:30:05Z
投资组合影响:
- AAPL仓位: 10股 @ $185.32 (新仓位)
- 仓位价值: $1,853.20
- 投资组合占比: 1.85% 权益
- 剩余购买力: $98,146.80 (原$100,000.00)部分成交:
⏳ 订单部分成交
订单ID: b1e2f3a4-...
已成交: 10股中的6股
平均成交价: $185.35
剩余数量: 4股(仍在处理中)已拒绝:
❌ 订单已拒绝
订单ID: b1e2f3a4-...
原因: 购买力不足
详情: 需要约$1,855.00,可用$500.00
补救建议:
- 减少订单数量
- 平仓释放购买力
- 如果此情况超出预期,检查账户中是否有占用购买力的待处理订单已取消:
🚫 订单已取消
订单ID: b1e2f3a4-...
取消方: 系统
原因: 当日订单在收盘时过期(美国东部时间16:00)
如果您仍希望建立此仓位,可考虑:
- 重新提交为撤销前有效(gtc)订单
- 等待下一个交易日开盘已修改:
🔄 订单已修改
旧订单ID: b1e2f3a4-...
新订单ID: c2d3e4f5-...
修改内容:
限价: $185.50 → $186.00
数量: 10 → 15Phase 7: Portfolio Impact Assessment
阶段7:投资组合影响评估
Step 25 — Fetch updated positions and account.
After a fill, your agent retrieves the current positions () and account () to show the impact.
GET /v2/positionsGET /v2/accountStep 26 — Show portfolio risk summary.
┌─────────────────────────────────────────┐
│ PORTFOLIO RISK SUMMARY │
├──────────────┬──────────────────────────┤
│ Total Equity │ $100,050.00 │
│ Buying Power │ $98,146.80 │
│ Open Pos. │ 4 positions │
│ Open Orders │ 1 working │
│ │
│ Position Concentration: │
│ AAPL │ 1.85% ($1,853.20) │
│ MSFT │ 3.20% ($3,201.00) │
│ TSLA │ 2.10% ($2,100.50) │
│ BTC/USD │ 5.00% ($5,002.30) │
│ │
│ Unrealized P&L (total): +$50.00 │
└──────────────┴──────────────────────────┘- Position concentration: — the Position field is
abs(position.market_value) / equity × 100. (market_valueexists only on the account payload as an all-positions aggregate.)position_market_value - Unrealized P&L:
(current_price - avg_entry_price) × qty - Day trade count: relevant for equity accounts with less than $25k equity
- Open orders: orders still working that may consume additional buying power
步骤25 — 获取更新后的仓位和账户信息
成交后,Agent会获取当前仓位()和账户信息()以展示影响。
GET /v2/positionsGET /v2/account步骤26 — 展示投资组合风险摘要
┌─────────────────────────────────────────┐
│ 投资组合风险摘要 │
├──────────────┬──────────────────────────┤
│ 总权益 │ $100,050.00 │
│ 剩余购买力 │ $98,146.80 │
│ 未平仓仓位 │ 4个 │
│ 待处理订单 │ 1个 │
│ │
│ 仓位集中度: │
│ AAPL │ 1.85% ($1,853.20) │
│ MSFT │ 3.20% ($3,201.00) │
│ TSLA │ 2.10% ($2,100.50) │
│ BTC/USD │ 5.00% ($5,002.30) │
│ │
│ 未实现盈亏(总计): +$50.00 │
└──────────────┴──────────────────────────┘- 仓位集中度: — 仓位字段为
abs(position.market_value) / equity × 100。(market_value仅作为所有仓位的汇总存在于账户负载中。)position_market_value - 未实现盈亏:
(current_price - avg_entry_price) × qty - 日内交易次数: 适用于权益低于25,000美元的股票账户
- 待处理订单: 仍在处理中的订单可能会占用额外购买力
Phase 8: Deployment Guidance
阶段8:部署指南
This phase is optional. Your agent provides this guidance only when you ask about deploying or automating a strategy.
Step 27 — Provide deployment options.
If you ask how to deploy or automate the strategy, your agent outlines these paths:
Local scheduler:
- Use (Linux/macOS),
cron(macOS), or Windows Task Schedulerlaunchd - Write a Python script using that encapsulates the strategy logic
alpaca-py - Schedule it to run at your desired frequency
- Log output to a file for review
Cloud hosting:
- AWS Lambda + EventBridge for serverless scheduled execution
- Google Cloud Functions + Cloud Scheduler
- Railway, Render, or Fly.io for persistent process hosting
- Any platform that can run a Python/Node.js process on a schedule
Webhook-based:
- TradingView alerts → webhook endpoint → your server → Alpaca API
- Custom alert system → webhook → order execution logic
Every deployed path asserts paper at startup. Scheduling, hosting, and webhook triggers differ, but they share one requirement: the artifact that runs unattended proves it is pointed at paper before it can place an order, and exits if it cannot. There is no operator watching to catch a wrong endpoint, and a live account returns the same response shape as a paper one, so nothing downstream will reveal the mistake.
Two rules make that assertion trustworthy:
- Pin the paper endpoint as a literal in code, not as configuration. An endpoint read from an environment variable, a config file, or a CI secret can be changed by someone who never reads this skill. In that means constructing the client as
alpaca-pywithTradingClient(key, secret, paper=True)written literally, neverpaper=True.paper=os.getenv(...) - Abort on any signal that live was intended. If a live endpoint, a live-trading flag, or a live profile is present in the environment, exit non-zero before the first order rather than resolving the conflict silently.
Naming a credential or variable "paper" is not evidence. Only the resolved endpoint is.
Important notes your agent always includes:
- Validate any new automation against paper for a meaningful period before considering live at all
- Your agent does not recommend any specific hosting provider or guarantee uptime
- Automating live trading is a separate, significant decision with additional regulatory and risk considerations
- Monitor automated systems regularly — do not "set and forget"
- Include error handling, logging, and alerting in any automated system
- Consider what happens when your automation encounters an unexpected market condition
本阶段为可选内容。仅当您询问策略部署或自动化时,Agent才会提供此指南。
步骤27 — 提供部署选项
如果您询问如何部署或自动化策略,Agent会列出以下路径:
本地调度:
- 使用(Linux/macOS)、
cron(macOS)或Windows任务计划程序launchd - 编写使用的Python脚本封装策略逻辑
alpaca-py - 按所需频率调度执行
- 将输出记录到文件供查看
云托管:
- AWS Lambda + EventBridge 用于无服务器定时执行
- Google Cloud Functions + Cloud Scheduler
- Railway、Render或Fly.io 用于持久化进程托管
- 任何可运行Python/Node.js进程并支持定时的平台
Webhook触发:
- TradingView告警 → Webhook端点 → 您的服务器 → Alpaca API
- 自定义告警系统 → Webhook → 订单执行逻辑
所有部署路径都需在启动时验证是否为纸交易环境。调度、托管和Webhook触发方式不同,但有一个共同要求:无人值守运行的程序必须先证明其指向纸交易环境,才能下单;如果无法证明则退出。没有操作员会监控并纠正错误端点,且实盘账户的响应格式与纸交易账户相同,下游无法发现错误。
两条规则可确保验证的可靠性:
- 在代码中硬编码纸交易端点,而非作为配置。从环境变量、配置文件或CI密钥读取的端点可能被未阅读本技能的人修改。在中,这意味着显式构造客户端为
alpaca-py,其中TradingClient(key, secret, paper=True)为硬编码,绝不能是paper=True。paper=os.getenv(...) - 如果检测到实盘意图的信号,立即终止。如果环境中存在实盘端点、实盘交易标志或实盘配置文件,在第一笔订单前以非零状态退出,而非静默解决冲突。
将凭证或变量命名为"paper"不能作为证据,只有解析后的端点才是有效证据。
Agent始终会包含的重要提示:
- 在考虑实盘交易前,先在纸交易环境中验证新自动化系统足够长的时间
- Agent不推荐任何特定托管提供商,也不保证可用性
- 自动化实盘交易是独立的重大决策,涉及额外的监管和风险考量
- 定期监控自动化系统——不要"设置后就不管"
- 在任何自动化系统中包含错误处理、日志记录和告警机制
- 考虑自动化系统遇到意外市场情况时的应对方案
5 - Execution rules
5 - 执行规则
Environment safety
环境安全
- This skill operates in the paper-trading environment ONLY.
- If your agent detects live API credentials — base URL is without the
https://api.alpaca.marketsprefix, or the SDK/CLI profile is set to live — it must STOP and warn you immediately.paper- - Your agent must verify the environment before every order submission, not just once per session. Environment state can change if credentials are reconfigured mid-session.
- Your agent never offers to "switch to live" or facilitate the transition from paper to live trading.
- 本技能仅在纸交易环境中运行。
- 如果Agent检测到实盘API凭证——基础URL为且不含
https://api.alpaca.markets前缀,或SDK/CLI配置文件设为实盘——必须立即停止并向您发出警告。paper- - Agent必须在每笔订单提交前验证环境,而非仅在会话开始时验证。会话期间凭证可能被重新配置,导致环境状态变化。
- Agent绝不提供"切换到实盘"的选项,也不协助从纸交易过渡到实盘交易。
Confirmation behavior
确认行为
- At the start of each session, your agent asks whether you want explicit confirmation before each order (default: ON).
- In confirmation-ON mode, your agent shows the order preview and waits for your explicit "yes" before submitting.
- In confirmation-OFF mode, your agent still shows the order preview but submits after a brief display pause. It announces the submission clearly.
- You can toggle confirmation mode at any time during the session by telling your agent.
- Regardless of mode, your agent always shows the order preview. It never submits silently.
- 每次会话开始时,Agent会询问您是否希望在每笔订单提交前进行明确确认(默认:开启)。
- 确认开启模式下,Agent会展示订单预览并等待您明确回复"是"后再提交。
- 确认关闭模式下,Agent仍会展示订单预览,但在短暂显示后提交,并明确告知您提交操作。
- 您可在会话期间随时告知Agent切换确认模式。
- 无论哪种模式,Agent始终会展示订单预览,绝不静默提交。
Idempotency
幂等性
- Your agent sets a unique on every order to prevent duplicate submissions.
client_order_id - If submission fails with a network error and it's unclear whether the order was received, your agent checks existing orders for the before retrying.
client_order_id - values are logged in the session's
client_order_idfor audit.orders.json
- Agent会为每笔订单设置唯一的,防止重复提交。
client_order_id - 如果提交因网络错误失败且无法确认订单是否已被接收,Agent会先通过检查现有订单,再决定是否重试。
client_order_id - 值会记录在会话的
client_order_id中以供审计。orders.json
Rate limiting
请求限制
- Drive throttling from the response headers rather than a hard-coded ceiling. Every response carries ,
X-RateLimit-Limit, andX-RateLimit-Remaining; your agent slows down asX-RateLimit-Resetapproaches zero instead of waiting to be throttled. A figure of 200 requests per minute is widely cited for the Trading API but is not stated in Alpaca's current documentation, so do not hard-code it.Remaining - If rate-limited (HTTP 429), stop and retry with exponential backoff plus jitter (1s, 2s, 4s, 8s, capped), and do not retry before the time given by .
X-RateLimit-Reset - Do not spam order status checks. Poll at reasonable intervals:
- Active market order: every 2 seconds for the first 10 seconds, then every 5 seconds
- Active limit order: every 5 seconds for the first minute, then every 30 seconds
- No order should be polled more than 60 times total
- 根据响应头进行限流,而非硬编码上限。每个响应都包含、
X-RateLimit-Limit和X-RateLimit-Remaining;Agent会在X-RateLimit-Reset接近零时放慢请求速度,而非等到被限流。Trading API广泛被引用的限流为每分钟200次请求,但Alpaca当前文档未明确说明,因此不要硬编码此值。Remaining - 如果被限流(HTTP 429),停止请求并使用指数退避加抖动(1秒、2秒、4秒、8秒,设上限)重试,且不得早于指定的时间重试。
X-RateLimit-Reset - 不要频繁查询订单状态。按合理间隔轮询:
- 活跃市价单:前10秒每2秒查询一次,之后每5秒查询一次
- 活跃限价单:前1分钟每5秒查询一次,之后每30秒查询一次
- 任何订单的轮询次数不得超过60次
Asset class rules
资产类别规则
US Equity:
- Standard market hours: 9:30 AM–4:00 PM ET
- Extended hours require on a
extended_hours: trueorder withlimitordayTIF, and cover three sessions:gtc- Overnight: 8:00 PM–4:00 AM ET, Sunday to Friday
- Pre-market: 4:00 AM–9:30 AM ET, Monday to Friday
- After-hours: 4:00 PM–8:00 PM ET, Monday to Friday
- Not every asset is eligible for the overnight session — confirm on the asset record rather than assuming
- Fractional shares supported for eligible symbols (check attribute)
fractionable - T+1 settlement — sell proceeds are available the next business day
- Short selling requires a margin account and locatable shares
US Options:
- Standard market hours: 9:30 AM–4:00 PM ET
- One contract = 100 shares of the underlying
- Approval level required (1, 2, or 3) — verify before submitting
- Exercise and assignment are automatic at expiration for ITM options
- Options have expiration dates — they lose value over time (theta decay)
- American-style options can be exercised any time before expiration
- Weekly, monthly, and quarterly expirations available for major symbols
Crypto:
- 24/7 market — no market-hours constraints
- Minimum order sizes apply per pair (check the asset endpoint)
- Not all pairs are available — verify before submitting
- No extended-hours concept — always open
- Fractional quantities supported for most pairs
- No short selling of crypto
美国股票:
- 标准交易时段:美国东部时间9:30 AM–4:00 PM
- 盘前/盘后交易要求,搭配
extended_hours: true订单和limit或day有效期限,涵盖三个时段:gtc- 隔夜:美国东部时间周日至周五8:00 PM–4:00 AM
- 盘前:美国东部时间周一至周五4:00 AM–9:30 AM
- 盘后:美国东部时间周一至周五4:00 PM–8:00 PM
- 并非所有资产都符合隔夜交易资格——需在资产记录中确认,不要假设
- 符合条件的代码支持碎股交易(检查属性)
fractionable - T+1结算——卖出资金下一个工作日到账
- 卖空需要保证金账户和可借股份
美国期权:
- 标准交易时段:美国东部时间9:30 AM–4:00 PM
- 1张合约对应100股标的股票
- 需要相应审批等级(1、2或3)——提交前验证
- 到期时,实值期权会自动行权和指派
- 期权有到期日——时间推移会导致价值衰减(theta衰减)
- 美式期权可在到期前任何时间行权
- 主要代码支持周度、月度和季度到期
加密货币:
- 24/7市场——无交易时段限制
- 每个交易对有最小订单量(检查资产端点)
- 并非所有交易对都可用——提交前验证
- 无盘前/盘后概念——始终开放
- 大多数交易对支持小数数量
- 不支持加密货币卖空
Error handling
错误处理
- Auth failure (401): Stop, show the error, suggest re-authenticating. Never retry with the same credentials.
- Insufficient buying power or shares (403): On ,
POST /v2/ordersmeans the tradable balance or share count is insufficient — it is not an auth failure. Show current buying power, required notional, and the shortfall. Suggest reducing quantity or closing positions.403 - Non-tradable symbol (422): The order endpoint reports unrecognized input as . Show the asset status and suggest checking the symbol. Offer to search for the correct symbol.
422is the place aGET /v2/assets/{symbol_or_asset_id}legitimately appears.404 - Market closed (422): Show current market status and next open time using the clock endpoint ().
GET /v2/clock - Rate limit (429): Wait and retry with exponential backoff. Inform you of the delay.
- Network timeout: Check if the order was received (by ) before deciding whether to retry.
client_order_id - Unknown error: Show the full error response. Do not silently swallow errors. Log the error to the session file.
- 认证失败(401): 停止执行,展示错误,建议重新认证。不得使用相同凭证重试。
- 购买力或股份不足(403): 在中,
POST /v2/orders可交易余额或股份数量不足——并非认证失败。展示当前购买力、所需名义金额和差额。建议减少数量或平仓。403 - 不可交易代码(422): 订单端点将未识别的输入报告为。展示资产状态并建议检查代码。提供搜索正确代码的选项。
422才是合法返回GET /v2/assets/{symbol_or_asset_id}的地方。404 - 市场休市(422): 使用时钟端点()展示当前市场状态和下一次开盘时间。
GET /v2/clock - 请求超限(429): 等待并使用指数退避重试,告知您延迟情况。
- 网络超时: 在决定是否重试前,先通过检查订单是否已被接收。
client_order_id - 未知错误: 展示完整错误响应,不得静默忽略错误。将错误记录到会话文件。
6 - Output contract
6 - 输出约定
In-chat response after submission
提交后聊天响应
Order submitted successfully.
Order ID: {order_id}
Status: {status}
Symbol: {symbol}
Side: {side}
Qty: {qty}
Type: {order_type}
TIF: {time_in_force}
Submitted at: {submitted_at}
Environment: PAPER
Next steps:
- Ask me to check the status of this order
- Ask me to cancel this order
- Ask me to show your current positions
- Ask me to show your portfolio summary订单提交成功。
订单ID: {order_id}
状态: {status}
交易代码: {symbol}
交易方向: {side}
数量: {qty}
订单类型: {order_type}
有效期限: {time_in_force}
提交时间: {submitted_at}
交易环境: 纸交易
后续操作:
- 让我查询此订单状态
- 让我取消此订单
- 让我展示您当前的仓位
- 让我展示您的投资组合摘要Run folder artifacts
运行文件夹产物
When the skill is used as part of a session with multiple orders, your agent writes session artifacts to a run folder:
runs/<YYYYMMDD-HHMMSS>-paper-trading/
notes.md # strategy context, confirmation choices, assumptions
orders.json # all orders submitted in this session
order_log.csv # timeline: order_id, timestamp, event, status, details
positions_snapshot.json # positions after last fill
portfolio_summary.md # human-readable portfolio state
review.md # session review and open questionsFile descriptions:
| File | Content | Format |
|---|---|---|
| Strategy description, signal source, confirmation preferences, assumptions made, risk controls applied | Markdown |
| Array of all orders submitted, including request payload and response | JSON |
| Chronological event log: | CSV |
| Positions at the end of the session (from | JSON |
| Human-readable portfolio state: equity, buying power, positions, concentration, P&L | Markdown |
| Session review: what worked, what didn't, open questions, suggested improvements | Markdown |
当本技能用于包含多笔订单的会话时,Agent会将会话产物写入运行文件夹:
runs/<YYYYMMDD-HHMMSS>-paper-trading/
notes.md # 策略上下文、确认选择、假设
orders.json # 本次会话提交的所有订单
order_log.csv # 时间线: order_id, timestamp, event, status, details
positions_snapshot.json # 最后一次成交后的仓位
portfolio_summary.md # 易读的投资组合状态
review.md # 会话回顾和未解决问题文件说明:
| 文件 | 内容 | 格式 |
|---|---|---|
| 策略描述、信号来源、确认偏好、做出的假设、应用的风险控制 | Markdown |
| 提交的所有订单数组,包含请求负载和响应 | JSON |
| chronological事件日志: | CSV |
| 会话结束时的仓位(来自 | JSON |
| 易读的投资组合状态: 权益、购买力、仓位、集中度、盈亏 | Markdown |
| 会话回顾: 有效操作、无效操作、未解决问题、建议改进 | Markdown |
7 - Validation and tests
7 - 验证和测试
Validate behavior against:
- Happy path scenarios for each asset class
- Missing and ambiguous input handling
- Auth and permission failure handling
- Environment safety verification (live credential detection)
- Order lifecycle transitions
- Edge cases: insufficient buying power, non-tradable symbols, market-closed, PDT warnings
- Idempotency and network failure recovery
- Confirmation mode switching
Run these tests mentally or against a paper account whenever modifying this skill.
针对以下场景验证行为:
- 每个资产类别的正常流程场景
- 缺失和模糊输入的处理
- 认证和权限失败的处理
- 环境安全验证(实盘凭证检测)
- 订单生命周期转换
- 边缘情况:购买力不足、不可交易代码、市场休市、PDT警告
- 幂等性和网络故障恢复
- 确认模式切换
每次修改本技能时,需在纸交易账户中进行上述测试,或在脑海中模拟测试。
8 - Disclosures, safety, and data handling
8 - 披露、安全和数据处理
Required disclosure
必填披露
Important disclosure: This material is for informational, educational, and research purposes only. It is not investment advice, a recommendation, an offer, or a solicitation to buy or sell securities, options, cryptocurrencies, or any other financial product. All investing and trading involve risk, including possible loss of principal. Paper trading is simulated and may differ from live trading in fills, market impact, liquidity, fees, latency, and other factors. Review Alpaca's disclosures at https://alpaca.markets/disclosures.
Your agent includes this disclosure in every session summary, report, and portfolio review.
重要披露: 本材料仅用于信息、教育和研究目的,不构成投资建议、推荐、要约或招揽购买或出售证券、期权、加密货币或任何其他金融产品。所有投资和交易均存在风险,包括可能损失本金。纸交易为模拟交易,在成交价格、市场影响、流动性、费用、延迟等方面可能与实盘交易不同。请查看Alpaca的披露信息:https://alpaca.markets/disclosures。
Agent会在每次会话摘要、报告和投资组合回顾中包含此披露内容。
Paper-trading specific
纸交易特定说明
- Paper trading results are simulated. They do not represent actual trading performance.
- Paper fills may differ from live fills in price, timing, partial fills, and rejection behavior.
- Paper trading does not charge real commissions or fees. Live trading may incur costs.
- Moving from paper to live trading is a separate, significant decision that requires additional review of risk tolerance, capital adequacy, and regulatory requirements.
- This skill will never facilitate that transition directly.
- 纸交易结果为模拟结果,不代表实际交易表现。
- 纸交易成交可能与实盘成交在价格、时间、部分成交和拒绝行为上存在差异。
- 纸交易不收取真实佣金或费用,实盘交易可能产生成本。
- 从纸交易过渡到实盘交易是独立的重大决策,需要额外评估风险承受能力、资本充足性和监管要求。
- 本技能绝不会直接协助此过渡。
Options-specific
期权特定说明
When options are involved, your agent includes:
- Options involve significant risk and are not suitable for all investors.
- Options can expire worthless. You can lose the entire premium paid for long options.
- Selling options carries risk that can exceed the premium received, and assignment can force a position at an unfavorable price.
- Complex options strategies (spreads, straddles, strangles) carry additional risks and may have multiple legs with different outcomes.
- Options are subject to exercise and assignment risk, especially near expiration.
- Understand the Greeks (delta, gamma, theta, vega) and how they affect your position before trading.
当涉及期权时,Agent会包含:
- 期权涉及重大风险,并非适合所有投资者。
- 期权可能到期作废,买入期权可能损失全部权利金。
- 卖出期权的风险可能超过收到的权利金,指派可能迫使您以不利价格建立仓位。
- 复杂期权策略(价差、跨式、宽跨式)存在额外风险,可能包含多个不同结果的腿。
- 期权面临行权和指派风险,尤其是临近到期时。
- 在交易期权前,需理解希腊字母(delta、gamma、theta、vega)及其对仓位的影响。
Crypto-specific
加密货币特定说明
When crypto is involved, your agent includes:
- Cryptocurrency trading involves substantial risk due to high volatility.
- Crypto assets are not securities and may have different regulatory protections than traditional securities.
- Crypto markets operate 24/7 and can experience significant price swings at any time.
- Crypto assets are not FDIC insured or SIPC protected.
- Regulatory environment for crypto is evolving and may change.
当涉及加密货币时,Agent会包含:
- 加密货币交易因高波动性存在重大风险。
- 加密资产不属于证券,可能与传统证券有不同的监管保护。
- 加密货币市场24/7开放,任何时间都可能出现大幅价格波动。
- 加密资产不受FDIC保险或SIPC保护。
- 加密货币监管环境不断演变,可能发生变化。
Credentials and data handling
凭证和数据处理
- Your agent reads credentials from environment variables (,
APCA_API_KEY_ID), SDK configuration files, or CLI profile settings.APCA_API_SECRET_KEY - Never paste API keys or secrets into chat. Your agent will refuse to accept them if offered.
- Your agent redacts account IDs, order IDs, and personally identifiable information in any summaries shared outside the session.
- Raw API responses are stored locally only (in the run folder) and classified as account-level confidential.
- Your agent does not send trading data, account data, or credentials to any third party.
- Session artifacts (run folder files) remain on your local filesystem. Review and delete them as appropriate.
- Agent从环境变量(、
APCA_API_KEY_ID)、SDK配置文件或CLI配置文件读取凭证。APCA_API_SECRET_KEY - 绝不将API密钥或密码粘贴到聊天窗口。如果您提供,Agent会拒绝接收。
- Agent会在会话外共享的任何摘要中编辑账户ID、订单ID和个人身份信息。
- 原始API响应仅本地存储(在运行文件夹中),并归类为账户级机密。
- Agent不会将交易数据、账户数据或凭证发送给任何第三方。
- 会话产物(运行文件夹文件)保留在您的本地文件系统中,请根据需要查看和删除。
9 - Anti-patterns
9 - 反模式
- NEVER submit orders to a live trading environment. This skill is paper-only.
- NEVER ask for API keys or secrets in chat. Credentials come from environment variables or config files.
- NEVER print credentials, tokens, account numbers, or profile details in plain text.
- NEVER skip the order preview — always show it, regardless of confirmation mode.
- NEVER retry a failed order submission without first checking if the original was received (use for idempotency).
client_order_id - NEVER give investment advice, recommend specific securities, or imply a strategy is suitable, profitable, or low-risk.
- NEVER assume the paper account has specific features enabled (options, crypto, margin) without checking the account endpoint.
- NEVER hide order parameters, defaults, or execution assumptions from you.
- NEVER treat paper trading results as proof or prediction of live trading performance.
- NEVER auto-submit orders in a loop without user awareness — if placing bulk orders, preview each one (or show a summary table of all orders and get batch confirmation).
- NEVER assume market hours — always check the clock/calendar endpoint before submitting time-sensitive orders.
- NEVER mix paper and live credentials in the same session.
- NEVER place orders for asset classes you haven't confirmed you want to trade.
- 绝不向实盘交易环境提交订单。本技能仅适用于纸交易。
- 绝不在聊天中索要API密钥或密码。凭证来自环境变量或配置文件。
- 绝不明文打印凭证、令牌、账户号码或配置文件详情。
- 绝不跳过订单预览——无论确认模式如何,始终展示预览。
- 绝不在未确认原始订单是否已被接收的情况下重试失败的订单提交(使用保证幂等性)。
client_order_id - 绝不提供投资建议、推荐特定证券,或暗示策略适合、盈利或低风险。
- 绝不在未检查账户端点的情况下,假设纸交易账户已启用特定功能(期权、加密货币、保证金)。
- 绝不向您隐藏订单参数、默认值或执行假设。
- 绝不将纸交易结果视为实盘交易表现的证明或预测。
- 绝不在用户不知情的情况下循环自动提交订单——如果批量下单,需预览每笔订单(或展示所有订单的摘要表格并获取批量确认)。
- 绝不假设交易时段——在提交时间敏感订单前,始终检查时钟/日历端点。
- 绝不在同一会话中混合纸交易和实盘凭证。
- 绝不为未确认的资产类别下单。
10 - Related files
10 - 相关文件
| File | Description |
|---|---|
| API endpoint details, order schemas, status lifecycle diagrams, error codes |
| 文件 | 描述 |
|---|---|
| API端点细节、订单 schema、状态生命周期图、错误代码 |
Companion skills
配套技能
| Skill | Description |
|---|---|
| CLI-specific version using the Alpaca CLI |
| MCP-specific version using Alpaca MCP server tools |
| 技能 | 描述 |
|---|---|
| 使用Alpaca CLI的专属版本 |
| 使用Alpaca MCP服务器工具的专属版本 |
Related skills
相关技能
| Skill | Description |
|---|---|
| Run historical backtests that produce signals for this skill |
| 技能 | 描述 |
|---|---|
| 运行历史回测,生成供本技能使用的信号 |