Agent skill

Alpaca Trading Paper Trading CLI

by alpacahq in alpacahq/alpaca-skills

Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI.

Apache-2.0Auto-check passedBusiness, Finance & HR

Install Alpaca Trading Paper Trading CLI

skills CLI
$ npx skills add alpacahq/alpaca-skills --skill alpaca-trading-paper-trading-cli -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install alpacahq/alpaca-skills alpaca-trading-paper-trading-cli --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/alpacahq/alpaca-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/trading-api/paper-trading-cli .claude/skills/alpaca-trading-paper-trading-cli && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
alpaca-trading-paper-trading-cli
GitHub stars
154
Token cost
~9k tokens
SKILL.md length
3,850 words
Files
2
Skills in repo
14
Repo updated
First seen
Licence
Apache-2.0

At a glance

Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI.

  • Works in 11 steps: How your AI agent should use this skill → Prerequisites → Gather inputs → …
  • You want your AI agent to take a strategy signal and execute it as a paper trade through the Alpaca command-line interface
  • SKILL.md covers 0 - How your AI agent should…, 1 - Prerequisites, 2 - Gather inputs and 3 - Source-of-truth references, plus 4 more sections
  • Calls go, brew and bash; reaches paper-api.alpaca.markets and api.alpaca.markets; needs ALPACA_API_KEY and ALPACA_PAPER_API_KEY

What it does

Alpaca Trading Paper Trading CLI is an agent skill from alpacahq/alpaca-skills. Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI. Supports US equities, options, and crypto. Use this skill when you want your AI agent to take a strategy signal and execute it as a paper trade through the Alpaca command-line interface.

Its SKILL.md is about 9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 1 other file (for example `reference.md`).

It sits in Business, Finance & HR, covering Trading and backtesting. It works with Alpaca. The repository describes itself as: Agent skills for Alpaca's Trading API and Broker API: drop-in SKILL.md files for AI coding assistants. The licence is Apache-2.0.

When your agent uses it

  • You want your AI agent to take a strategy signal and execute it as a paper trade through the Alpaca command-line interface
  • Tasks that involve Trading and backtesting

Example prompts

  • “/alpaca-trading-paper-trading-cli”

Workflow steps

11 steps, taken from the step headings in SKILL.md.

  1. How your AI agent should use this skill
  2. Prerequisites
  3. Gather inputs
  4. Source-of-truth references
  5. Workflow
  6. Execution rules
  7. Output contract
  8. Validation and tests
  9. Disclosures, safety, and data handling
  10. Anti-patterns
  11. Related files

What it can do on your machine

Read from SKILL.md and the folder at commit 39111ab. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • go
    • brew
    • bash

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • paper-api.alpaca.markets
    • api.alpaca.markets

    Also links to:

    • docs.alpaca.markets
    • alpaca.markets

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • ALPACA_API_KEY
    • ALPACA_PAPER_API_KEY
    • ALPACA_SECRET_KEY
    • ALPACA_PAPER_SECRET_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Alpaca Trading Paper Trading CLI loads about 9k tokens when it runs. Until then it costs about 77 tokens; SKILL.md has 3,850 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~77
When it runs · the whole SKILL.md, loaded when a task matches
~9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from alpacahq/alpaca-skills at commit 39111ab, republished under its Apache-2.0 licence (© alpacahq). 3,850 words, ~8,983 tokens.

Download SKILL.mdSave it as .claude/skills/alpaca-trading-paper-trading-cli/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
alpaca-trading-paper-trading-cli
description
Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI. Supports US equities, options, and crypto. Use this skill when you want your AI agent to take a strategy signal and execute it as a paper trade through the Alpaca command-line interface.

Alpaca Paper Trading — CLI Version

Use this skill when you want your AI agent to preview, submit, inspect, and manage paper-trading orders using the Alpaca CLI.

This skill is written for you, a Trading API user working with your own Alpaca paper-trading account, CLI profile, and local workspace. Your agent executes all operations through the alpaca command-line tool, giving you full visibility into every command and its output.

This is the CLI-specific version. A generic (implementation-agnostic) version and an MCP-server version are also available as companion skills.


0 - How your AI agent should use this skill

  1. Start with the signal source. Identify the origin of the trade idea — a backtest result, manual idea, scheduled trigger, or strategy output.
  2. Reiterate strategy logic and confirm with you. Summarize the thesis, expected behavior, and conditions under which the order should execute. Wait for your confirmation before proceeding.
  3. Gather and confirm ALL configurations. Timing, asset class, symbol, side, qty/notional, order type, TIF, limit/stop prices, extended-hours flag, risk controls, and margin usage — every parameter must be stated and confirmed.
  4. Confirm the CLI resolves to the paper endpoint. Run alpaca doctor and require its Trading: line to read https://paper-api.alpaca.markets. If it shows the live endpoint, STOP immediately and alert you.
  5. Show a complete order preview using a formatted table. Include the exact CLI command that will run.
  6. Ask whether you want explicit confirmation before each order (default: ON). Respect your preference for the session.
  7. Submit via alpaca order submit with the paper profile.
  8. Return order ID, status, submitted payload, and next inspection commands so you can independently verify.
  9. Monitor order lifecycle with alpaca order get. Report fills, rejections, cancellations with portfolio impact.
  10. Never place live trades. Verify the resolved paper endpoint before every submission. If any ambiguity exists about the environment, STOP.

1 - Prerequisites

Alpaca CLI installed and on PATH
bash
alpaca version

Install if needed:

bash
# Homebrew (macOS / Linux)
brew install alpacahq/tap/cli

# Or with Go — requires $GOPATH/bin (typically ~/go/bin) on your PATH
go install github.com/alpacahq/cli/cmd/alpaca@latest

The CLI is in Alpha Preview. Commands, flags, and output formats may change between releases, which is why your agent discovers flags at runtime rather than trusting any list in this file.

Paper profile configured
bash
alpaca profile login
# or with API key
alpaca profile login --api-key

Discover login options:

bash
alpaca profile login --help
Connectivity verified
bash
alpaca doctor

Your agent runs this before every trading session. If it fails, no orders are submitted.

Asset-class requirements
Asset classRequirement
US equitiesPaper account active
OptionsOptions trading enabled on paper account
CryptoCrypto trading enabled on paper account
Environment
  • A Go toolchain, only if installing via go install; the Homebrew formula ships a prebuilt binary and needs no Go
  • uuidgen or equivalent (for client order IDs)

External jq is not required. The CLI ships a built-in --jq flag that filters its own JSON output.


2 - Gather inputs

Your agent collects the following before proceeding to order construction:

ParameterDescriptionDefaultRequired
signal_sourceOrigin of trade idea (backtest, manual, scheduled, strategy)—Yes
symbolTicker symbol (e.g., AAPL, BTC/USD, AAPL250718C00200000)—Yes
asset_classus_equity, us_option, cryptous_equityYes
sidebuy or sell—Yes
qtyNumber of shares/contracts/coins—Yes (or notional)
notionalDollar amount (fractional shares). Market orders with day TIF only; cannot combine with qty—Yes (or qty)
order_typemarket, limit, stop, stop_limit, trailing_stop — supported values vary by asset classmarketYes
time_in_forceday, gtc, ioc, fok, opg, cls — supported values vary by asset classday for equities and options; gtc for cryptoYes
order_classsimple, bracket, oco, oto (equities); simple, mleg (options); simple (crypto)simpleNo
limit_priceRequired for limit/stop_limit—Conditional
stop_priceRequired for stop/stop_limit—Conditional
trail_percentFor trailing_stop—Conditional
trail_priceFor trailing_stop—Conditional
extended_hoursAllow pre/post-market fillsfalseNo
client_order_idIdempotency key, max 128 charactersAuto-generated by Alpaca if omittedNo
profileAlpaca CLI profile name. Set it via the ALPACA_PROFILE environment variable for the whole session — never with the -p/--profile flag. See the warning in Step 10Currently active paper profileNo
output_formatJSON is the default; --csv for CSV, --jq '<expr>' to filterJSONNo
confirmation_modeRequire explicit yes before each orderONNo
max_position_pctMax % of portfolio in single positionNoneNo
max_order_valueHard cap on single order notionalNoneNo
Strategy confirmation checklist

Before building the order, your agent confirms:

  • Strategy logic is clearly stated
  • You understand what the order will do
  • Entry criteria are met (if from backtest/signal)
  • Exit criteria / stop-loss plan discussed
  • Position sizing is intentional
  • Risk controls reviewed

3 - Source-of-truth references

Your agent uses these authoritative sources for validation:

SourceURLUsed for
Create an orderhttps://docs.alpaca.markets/us/reference/postorderOrder parameters, per-asset-class constraints, status codes
Alpaca CLI docshttps://docs.alpaca.markets/us/docs/alpacas-cliCLI commands, flags, syntax
Order typeshttps://docs.alpaca.markets/us/docs/orders-at-alpacaOrder type behavior and requirements
Paper tradinghttps://docs.alpaca.markets/us/docs/paper-tradingPaper environment specifics
Options tradinghttps://docs.alpaca.markets/us/docs/options-tradingOptions order requirements and approval levels
Crypto tradinghttps://docs.alpaca.markets/us/docs/crypto-tradingCrypto order specifics
Alpaca disclosureshttps://alpaca.markets/disclosuresDisclosure language
CLI discovery rule

Your agent verifies flags at runtime rather than trusting this file:

bash
alpaca --help-all              # full command tree with every flag
alpaca order submit --help     # flags for one command
alpaca order submit --schema   # response shape, without calling the API

The CLI is in Alpha Preview, so flags and output shapes can change between releases. Anything in this skill that contradicts --help output is stale; trust the CLI.


4 - Workflow

Phase 1: Strategy Confirmation

Step 1 — Identify the signal source.

Your agent asks: "Where does this trade idea come from?" Options include:

  • A completed backtest (link to run folder if available)
  • A manual trade idea you described
  • A scheduled or recurring strategy trigger
  • Output from another skill or system

Step 2 — Reiterate the strategy logic.

Your agent summarizes:

  • Thesis (why this trade)
  • Expected outcome
  • Time horizon
  • Exit conditions or stop-loss plan

Step 3 — Confirm interpretation.

Your agent asks: "Is this interpretation correct? Should I proceed to configure the order?"


Phase 2: Configuration Agreement

Step 4 — Confirm asset class and symbol.

Your agent validates the symbol format:

  • Equities: AAPL, MSFT
  • Options: OCC format AAPL250718C00200000
  • Crypto: BTC/USD, ETH/USD

Format is necessary but not sufficient — a well-formed symbol can still be untradable or delisted. Your agent confirms it against the asset record:

bash
alpaca asset get --symbol-or-asset-id AAPL

It requires status = active and tradable = true, and checks fractionable before proposing a notional or fractional-quantity order. For options, it resolves real contracts with alpaca option contracts --underlying-symbols AAPL rather than hand-assembling an OCC string.

Step 5 — Confirm side, quantity, and order type.

Step 6 — Confirm time-in-force and pricing parameters.

Time-in-force is not uniform across asset classes. Your agent validates the combination before building the command, because the API rejects the invalid ones:

Asset classOrder typesTime-in-forceOrder classes
US equitiesmarket, limit, stop, stop_limit, trailing_stopday, gtc, opg, cls, ioc, foksimple, bracket, oco, oto
US optionsmarket, limit, stop, stop_limit (stop types single-leg only)day, gtcsimple, mleg
Cryptomarket, limit, stop_limitgtc, ioc — but stop_limit is gtc-only, and ioc applies only to market and limitsimple

The CLI supplies the time-in-force default itself based on symbol shape: a symbol containing / (i.e. a crypto pair) defaults to gtc, everything else to day. Submitting a crypto order without --time-in-force therefore sends gtc, not day.

Alpaca's own sources disagree on the options row, so treat it as guidance rather than a hard gate. The OpenAPI spec's TimeInForce/OrderType descriptions say options are market/limit with day only; the Options Trading page and the Placing Orders matrix both allow gtc and both allow stop/stop_limit on single-leg orders. The two product pages agree with each other against the spec blob, so this table follows them. Your agent still defaults to day as the conservative choice and lets Alpaca reject rather than pre-blocking an order that the matrix permits.

Additional constraints that cut across order type:

  • Extended hours requires limit type with day or gtc TIF. Every other type and TIF is rejected outright.
  • Trailing stop accepts only day and gtc.
  • Notional orders are market-type with day TIF only, cannot be combined with qty, and cannot be replaced — cancel and resubmit instead.
  • Bracket, OCO, and OTO classes require day or gtc, do not support extended hours, and are equities-only.
  • Options do not support extended hours at all. Multi-leg strategies use the mleg order class with up to 4 legs, and stop/stop_limit types are single-leg only.

Step 7 — Confirm extended hours and client order ID preferences.

Alpaca supports three sessions outside regular hours, all of which require extended_hours: true on a limit order:

SessionWindow (ET)Days
Overnight8:00pm – 4:00amSunday to Friday
Pre-market4:00am – 9:30amMonday to Friday
After-hours4:00pm – 8:00pmMonday to Friday

Not every asset trades overnight; your agent confirms eligibility on the asset record rather than assuming.

Step 8 — Review risk controls.

Your agent presents any position-sizing or max-value constraints and validates:

  • Order notional vs. buying power
  • New position concentration vs. portfolio
  • Existing exposure to the same symbol

Step 9 — Final configuration summary.

Your agent displays a complete parameter table and asks: "All parameters confirmed?"


Phase 3: Paper Account Verification via CLI

Step 10 — Confirm the CLI resolves to the paper endpoint:

bash
alpaca doctor

alpaca doctor prints the fully-resolved trading endpoint under Connectivity::

Connectivity:
  Trading:  https://paper-api.alpaca.markets

Your agent requires that line to read https://paper-api.alpaca.markets. The profile name is not a substitute. The CLI resolves paper vs. live in a fixed order — ALPACA_LIVE_TRADE first, then the active profile's live_trade field, then a paper default — so an exported ALPACA_LIVE_TRADE=true sends a profile named "paper" straight to the live endpoint. alpaca doctor reports the result of that whole chain.

⚠️ alpaca doctor ignores the -p/--profile flag. It accepts the flag and silently discards the value, always reporting the default profile. Every other command honors -p. So alpaca doctor -p live reports the paper endpoint while alpaca order submit -p live trades against the live one, and the guard passes while the order goes out live.

Your agent therefore never passes -p/--profile to any command. To target a non-default profile it sets ALPACA_PROFILE once for the whole session, which doctor does honor, so the check and the order resolve identically. If any command in the session is about to receive -p, your agent stops instead.

If the Trading: line shows https://api.alpaca.markets, your agent STOPS immediately:

⚠️ LIVE ENDPOINT DETECTED. Your agent will not proceed. Unset ALPACA_LIVE_TRADE (or set it to false, which forces paper even on a live profile), select a paper profile with alpaca profile switch <paper-profile-name>, and restart.

Step 11 — Confirm connectivity from the same alpaca doctor output.

Your agent confirms all checks pass. If any fail, it reports the failure and does not proceed. It does not re-run alpaca doctor; one invocation covers both this step and Step 10. alpaca doctor exits 0 when every check passes and 1 when any check fails.

Step 12 — Fetch account status:

bash
alpaca account get

Your agent parses and verifies:

  • status = ACTIVE
  • account_blocked = false
  • trading_blocked = false
  • trade_suspended_by_user = false
  • multiplier — margin classification, and the only PDT signal the account object carries: 1 is a limited-margin cash-style account, 2 is a Reg T margin account, 4 is a PDT account with 4x intraday buying power

The Trading API account object has no pattern_day_trader or daytrade_count field. Your agent must not read them; infer PDT status from multiplier instead.

Step 13 — Check buying power:

bash
alpaca account get --jq '.buying_power'

Your agent compares estimated order value against available buying power. If insufficient, it warns you before proceeding.

Step 14 — For options orders, check approval level:

bash
alpaca account get --jq '{options_approved_level, options_trading_level, options_buying_power}'

Your agent gates on options_trading_level, which is the effective level — the minimum of options_approved_level and the max_options_trading_level in account configuration. Approval alone does not authorize trading if configuration caps it lower.

LevelPermits
0Options trading disabled
1Covered calls, cash-secured puts
2Long calls and puts (adds to level 1)
3Spreads and straddles (adds to level 2)

Spreads require level 3, not level 2.

Step 15 — Show account summary.

Your agent presents:

┌─────────────────────────────────────┐
│ Paper Account Summary               │
├─────────────────────────────────────┤
│ Endpoint:      paper-api (PAPER)    │
│ Profile:       my-paper             │
│ Status:        ACTIVE               │
│ Equity:        $50,000.00           │
│ Buying Power:  $100,000.00          │
│ Multiplier:    2 (Reg T margin)     │
│ Options Level: 2 (effective)        │
│ Crypto:        ACTIVE               │
└─────────────────────────────────────┘

Phase 4: Order Preview

Step 16 — Build the CLI command but DO NOT execute yet.

Your agent constructs the full command and displays it, then validates it with --dry-run, which prints the request body the CLI would send without submitting anything:

bash
alpaca order submit \
  --symbol AAPL \
  --side buy \
  --qty 10 \
  --type limit \
  --limit-price 185.50 \
  --time-in-force day \
  --client-order-id a1b2c3d4-e5f6-7890-abcd-ef1234567890 \
  --dry-run

The command your agent shows you in the preview must be byte-identical to the one it later executes, minus --dry-run.

Step 17 — Display formatted order preview table:

┌─────────────────────────────────────────────┐
│ ORDER PREVIEW — NOT YET SUBMITTED           │
├─────────────────────────────────────────────┤
│ Symbol:         AAPL                        │
│ Side:           BUY                         │
│ Quantity:       10 shares                   │
│ Order Type:     LIMIT                       │
│ Limit Price:    $185.50                     │
│ Time in Force:  DAY                         │
│ Extended Hours: No                          │
│ Est. Value:     $1,855.00                   │
│ Buying Power:   $100,000.00 → $98,145.00   │
│ Client ID:      a1b2c3d4-...               │
│ Endpoint:       paper-api (PAPER)           │
├─────────────────────────────────────────────┤
│ ⚠️  This is a PAPER trade — no real money   │
└─────────────────────────────────────────────┘

Step 18 — If confirmation is ON: wait for explicit "yes" before proceeding.

Step 19 — If confirmation is OFF: show the preview, then submit automatically.


Phase 5: Order Submission

Step 20 — Execute the CLI command:

bash
CLIENT_ORDER_ID="$(uuidgen)"

alpaca order submit \
  --symbol AAPL \
  --side buy \
  --qty 10 \
  --type limit \
  --limit-price 185.50 \
  --time-in-force day \
  --client-order-id "$CLIENT_ORDER_ID"

Your agent captures CLIENT_ORDER_ID before submitting, so the order stays recoverable if the command dies before printing a response.

Step 21 — Save raw CLI output to the run folder:

bash
# Output saved to runs/<timestamp>-paper-trading-cli/raw/order_submit_response.json

Step 22 — Parse response for key fields:

  • id (order ID)
  • status (expected: new or accepted)
  • created_at
  • filled_at (null for pending)
  • filled_qty
  • filled_avg_price

Step 23 — On failure:

  • Capture the structured JSON error from stderr and the CLI exit code — 0 success, 1 error, 2 auth failure
  • Show remediation guidance (e.g., "insufficient buying power", "symbol not found", "market closed")
  • Save error to runs/<timestamp>/raw/error.json
  • Suggest corrective actions

If the failure is ambiguous — a timeout, a killed process, any case where your agent cannot tell whether the order reached Alpaca — it must not resubmit. It looks the order up by the client order ID it generated in Step 20:

bash
alpaca order get-by-client-id --client-order-id "$CLIENT_ORDER_ID"

A hit means the order exists and resubmitting would duplicate it. Only a confirmed miss justifies a retry.


Phase 6: Post-Submission Monitoring

Step 24 — Check order status:

bash
alpaca order get --order-id {order_id}

Your agent reports:

  • Current status
  • Fill progress (partial fills)
  • Average fill price

Step 25 — List recent orders for context:

bash
alpaca order list --status open

Step 26 — Return order summary to you:

┌─────────────────────────────────────────────┐
│ ORDER SUBMITTED ✓                           │
├─────────────────────────────────────────────┤
│ Order ID:      abc-123-def-456              │
│ Status:        NEW                          │
│ Symbol:        AAPL                         │
│ Side/Qty:      BUY 10                       │
│ Type:          LIMIT @ $185.50              │
│ Submitted:     2026-07-26T14:30:00Z         │
├─────────────────────────────────────────────┤
│ Next commands:                              │
│  alpaca order get --order-id abc-123      │
│  alpaca order cancel --order-id abc-123     │
│  alpaca position list                     │
└─────────────────────────────────────────────┘

Step 27 — Order lifecycle updates:

EventAgent action
filledReport fill price, calculate slippage vs. limit, show position impact
partially_filledReport filled qty, remaining qty, average price
rejectedSurface rejection reason, suggest fix
canceledConfirm cancellation, show final state
expiredReport expiration (TIF elapsed), suggest re-entry
replacedConfirm replacement parameters, show new order ID

Phase 7: Portfolio Impact

Step 28 — Fetch positions:

bash
alpaca position list

Or for a specific symbol:

bash
alpaca position get --symbol-or-asset-id AAPL

Step 29 — Fetch updated account:

bash
alpaca account get

Step 30 — Show portfolio risk summary:

┌─────────────────────────────────────────────┐
│ PORTFOLIO IMPACT                            │
├─────────────────────────────────────────────┤
│ New Position:   AAPL — 10 shares @ $185.30  │
│ Position Value: $1,853.00                   │
│ Portfolio %:    0.74%                       │
│ Buying Power:   $98,147.00 (was $100,000)   │
│ Total Equity:   $250,000.00                 │
│ Open Orders:    1                           │
└─────────────────────────────────────────────┘

Show full SKILL.md (1,587 more words)Show less
Phase 8: Order Management

Step 31 — Cancel a specific order:

bash
alpaca order cancel --order-id {order_id}

Your agent confirms cancellation and reports final order state.

Step 32 — Cancel all open orders.

cancel-all is unscoped: it cancels every open order on the account, including orders this session never created. The CLI executes it immediately with no confirmation prompt of its own, so your agent supplies the gate. It first shows exactly what will be destroyed:

bash
alpaca order list --status open --jq '[.[] | {id, symbol, side, qty, type, limit_price}]'

Your agent lists those orders, states the count, and requires an explicit "yes" — even when confirmation_mode is OFF, since that setting governs order entry rather than mass cancellation. Only then:

bash
alpaca order cancel-all

Your agent confirms total canceled and lists affected orders. The same gate applies to alpaca position close-all, which liquidates the entire portfolio.

Step 33 — Replace an order (modify price/qty):

Discover available flags first:

bash
alpaca order replace --help

Then execute:

bash
alpaca order replace --order-id {order_id} --qty 5 --limit-price 186.00

Your agent reports the new order ID and updated parameters.


Phase 9: Deployment Guidance (on request)

When you ask about automation, your agent provides guidance for:

Bash script wrapper. Unattended submission goes through a wrapper that proves the paper endpoint before it orders. Nothing scheduled calls alpaca order submit directly, so the guard cannot be bypassed by whichever scheduler invokes it:

bash
#!/bin/bash
# /usr/local/bin/paper-trade.sh
set -euo pipefail

SYMBOL="${1:?usage: $0 SYMBOL SIDE QTY}"
SIDE="${2:?usage: $0 SYMBOL SIDE QTY}"
QTY="${3:?usage: $0 SYMBOL SIDE QTY}"

# Verify the CLI resolves to the paper endpoint
if ! alpaca doctor | grep -q 'Trading:.*https://paper-api\.alpaca\.markets'; then
  echo "ERROR: CLI is not pointed at the paper endpoint. Exiting." >&2
  exit 1
fi

alpaca order submit \
  --symbol "$SYMBOL" \
  --side "$SIDE" \
  --qty "$QTY" \
  --type market \
  --time-in-force day \
  --client-order-id "$(uuidgen)"

Cron job. Cron calls the wrapper, never the raw CLI:

bash
# /etc/cron.d/paper-trade
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
ALPACA_PROFILE=paper
0 9 * * 1-5 root /usr/local/bin/paper-trade.sh AAPL buy 1 >> /var/log/paper-trades.log 2>&1

Cron runs with a near-empty environment and does not source your shell profile, so PATH, ALPACA_PROFILE, and credentials must be set explicitly — in the crontab as above, or sourced inside the wrapper from a file readable only by the job's user. A scheduled job that inherits nothing is the case where an unguarded submit is most dangerous: there is no operator watching and no prompt, which is why the endpoint check belongs in the script rather than in the schedule.

systemd timer / launchd plist: Your agent generates the appropriate service file for your OS, pointing it at the same wrapper.

CI/CD pipeline. Install the CLI, authenticate from the runner's secret store, and invoke the same wrapper — never alpaca order submit as a bare step:

yaml
- name: Submit paper order
  env:
    ALPACA_API_KEY: ${{ secrets.ALPACA_PAPER_API_KEY }}
    ALPACA_SECRET_KEY: ${{ secrets.ALPACA_PAPER_SECRET_KEY }}
    ALPACA_PROFILE: paper
  run: ./scripts/paper-trade.sh AAPL buy 1

CI is the easiest place to end up live by accident: the runner has no profile of yours, the keys come from whichever secret someone wired up, and a live key in a secret named for paper looks identical to a correct one at the call site. Naming the secret PAPER proves nothing, which is why the wrapper's alpaca doctor check — not the variable names — is what establishes the endpoint.

Key automation notes:

  • The CLI never prompts. There are no "are you sure?" dialogs to suppress, in automation or interactively — which is exactly why the confirmation gates in this skill are the agent's responsibility, not the CLI's.
  • --quiet suppresses warnings, hints, and color. It is not what makes output machine-readable; JSON is the default with or without it. Use it in cron and CI to keep logs clean.
  • ALPACA_OUTPUT=json|csv sets the default output format for a whole script.
  • Every unattended path — cron, systemd, launchd, CI — submits through the guarded wrapper. No scheduler or pipeline calls alpaca order submit directly, so the endpoint check cannot be skipped by adding a new trigger.
  • Log all output for an audit trail.
  • Use --client-order-id for idempotency in retry scenarios.

5 - Execution rules

General rules
  1. Paper only. Never submit orders against the live endpoint. Verify the resolved endpoint before every submission.
  2. Confirm before submit. Default is explicit confirmation ON. Respect user preference.
  3. Preserve intent. Never modify order parameters without your explicit agreement.
  4. Atomic operations. Each order submission is independent. Failures don't affect other orders.
  5. Full transparency. Show every CLI command before and after execution.
  6. Idempotency. Always generate a --client-order-id to prevent duplicate submissions on retry.
  7. No financial advice. Your agent executes your instructions. It does not recommend trades.
CLI-specific rules
  1. Never pass -p/--profile to any command. alpaca doctor ignores it, so the paper check and the order can resolve to different profiles. Use ALPACA_PROFILE for the session instead.
  2. Parse the default JSON output. Every command returns structured JSON already. Use --jq '<expr>' to filter it and --csv only for human-facing tables. --quiet suppresses warnings, hints, and color; it does not change the data format.
  3. Never pipe to external jq. The built-in --jq flag does the same job with one less dependency.
  4. Always discover flags with --help, --help-all, and --schema before assuming syntax. The CLI is in Alpha Preview and may change between versions.
  5. Save all raw CLI output to the run folder. Every command's stdout and stderr goes to raw/.
  6. If alpaca doctor fails, do not proceed. Report the failure and stop.
  7. Redact profile details and tokens in summaries. Never expose API keys or secrets in output files.
  8. Handle CLI exit codes. 0 success, 1 error, 2 auth failure. Capture stderr and surface it.
  9. Do not add your own retry loop for rate limits. The CLI already retries 429 and 5xx responses up to three times and respects Retry-After. A second backoff layer on top of it turns one rate-limited call into a much longer stall. If a command still fails after the CLI's retries, surface the error and stop.
  10. Preview with --dry-run before submitting. It prints the exact request body without sending an order.
  11. Gate unscoped destructive commands. order cancel-all and position close-all affect the whole account. Require explicit confirmation regardless of confirmation_mode.

6 - Output contract

Every paper-trading session produces a run folder:

runs/<YYYYMMDD-HHMMSS>-paper-trading-cli/
  notes.md                        # Session narrative: strategy, decisions, outcomes
  raw/                            # Saved raw CLI outputs
    account.json                  # Account state at session start
    order_submit_response.json    # Raw submission response
    order_status.json             # Order status checks
    positions.json                # Position state after fills
    clock.json                    # Market clock at submission time
    error.json                    # Error output (if any)
  orders.json                     # Structured order records
  order_log.csv                   # Tabular log: timestamp, action, order_id, status, details
  positions_snapshot.json         # Position state post-trade
  portfolio_summary.md            # Human-readable portfolio impact
  review.md                       # Session review: what worked, issues, next steps
notes.md structure
markdown
# Paper Trading Session — <timestamp>

## Signal Source
<origin of trade idea>

## Strategy
<strategy logic as confirmed>

## Orders Submitted
| # | Symbol | Side | Qty | Type | Status | Fill Price |
|---|--------|------|-----|------|--------|-----------|

## Portfolio Impact
<post-trade portfolio state>

## Issues / Notes
<any errors, warnings, or observations>
order_log.csv columns
timestamp,action,order_id,symbol,side,qty,type,limit_price,stop_price,tif,status,fill_price,fill_qty,error

7 - Validation and tests

Your agent runs these checks during execution.

Pre-submission validation
CheckCommandPass condition
CLI installedalpaca versionExit code 0
Connectivityalpaca doctorAll checks pass
Paper endpointalpaca doctorTrading: line reads https://paper-api.alpaca.markets
Account activealpaca account getstatus=ACTIVE, not blocked
Buying poweralpaca account get --jq '.buying_power'Sufficient for order
Market openalpaca clockis_open=true (unless extended hours or GTC)
Symbol valid and tradablealpaca asset get --symbol-or-asset-id Xstatus=active, tradable=true
Post-submission validation
CheckCommandPass condition
Order acceptedalpaca order get --order-id XStatus != rejected
Fill receivedSamefilled_qty > 0
Position updatedalpaca position get --symbol-or-asset-id XReflects new position

8 - Disclosures, safety, and data handling

Disclosures
  • Paper trading only. This skill operates exclusively in the Alpaca paper-trading environment. No real money is at risk.
  • Not financial advice. Your agent executes your instructions. It does not provide investment recommendations, market predictions, or trading advice.
  • Paper ≠ live. Paper fills may differ from live execution due to simplified fill simulation. Do not assume paper results predict live performance.
  • Your responsibility. You are responsible for the strategies you choose to paper-trade. Your agent is a tool, not an advisor.
  • Full disclosures. Review Alpaca's disclosures and agreements at alpaca.markets/disclosures.

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.

Safety controls
ControlImplementation
Live-trade preventionResolved-endpoint check before every submission
Confirmation gateDefault ON — explicit yes required
Buying-power checkPre-submission validation
Connectivity verificationalpaca doctor at session start
Error isolationFailures logged, do not cascade
Idempotency--client-order-id prevents duplicates
Data handling
  • Local only. All run data stays in your local workspace under runs/.
  • No telemetry. Your agent does not send trading data to external services beyond the Alpaca API.
  • Credential safety. API keys are never logged, displayed, or written to files. Profile names are redacted in shared outputs.
  • Audit trail. Every CLI command and response is saved in raw/ for your review.

9 - Anti-patterns

Your agent must NEVER:

Anti-patternWhyCorrect approach
Submit against the live endpointReal money at riskAlways confirm alpaca doctor reports the paper endpoint first
Skip confirmation when mode is ONYou lose controlAlways honor confirmation preference
Modify order params silentlyViolates your intentRe-confirm any parameter changes
Give trading adviceLiability, not agent's roleExecute instructions, don't recommend
Hard-code CLI flagsAlpha Preview — flags may change between versionsDiscover with --help, --help-all, and --schema
Pipe output to external jqAdds a dependency the CLI already providesUse the built-in --jq flag
Treat --quiet as the JSON switchJSON is the default; --quiet only drops warnings, hints, and colorParse the default output directly
Read pattern_day_trader or daytrade_countNeither field exists on the Trading API account objectInfer PDT from multiplier = 4
Add a retry loop for 429sThe CLI already retries 3x and honors Retry-AfterSurface the error after its retries fail
Run cancel-all or close-all unpromptedUnscoped — hits orders and positions this session never createdList what will be affected, require explicit confirmation
Bypass Alpaca CLI with direct HTTP callsThis is the CLI versionUse alpaca commands exclusively
Ignore CLI exit codesMissed errorsCheck exit code, capture stderr
Proceed after alpaca doctor failsConnectivity not verifiedStop and report the failure
Store API keys in run foldersSecurity riskRedact all credentials
Assume market hoursMay be extended/crypto 24/7Check alpaca clock
Submit without buying-power checkOrder will be rejectedValidate buying power first
Use --csv output for programmatic parsingLess structured than JSONParse the default JSON, filtered with --jq

FilePurpose
reference.mdDetailed reference: order types, TIF, lifecycle, asset classes, errors
Companion skills
SkillDescription
alpaca-trading-backtestHistorical backtesting via Alpaca CLI — produces signals this skill can execute
alpaca-trading-paper-tradingGeneric implementation-agnostic paper-trading skill
alpaca-trading-paper-trading-mcpMCP-server version of this skill

© alpacahq, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in skills/trading-api/paper-trading-cli of alpacahq/alpaca-skills.

  • SKILL.md
  • reference.md

Open the folder on GitHubat commit 39111ab

Compare with similar skills

Alpaca Trading Paper Trading CLI next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Alpaca Trading Paper Trading CLI compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Alpaca Trading Paper Trading CLI this skillalpacahq/alpaca-skills154—~9kAutomated safety check: PassApache-2.0
Alpaca Tradinggauss314/skills248—~2.4kAutomated safety check: PassMIT
Tushare Datazillionare/zillionare3222 repos~2.3kAutomated safety check: PassNone
Tradingview MCPatilaahmettaner/tradingview-mcp5k—~1.3kAutomated safety check: PassMIT
Digital Oraclekomako-workshop/digital-oracle878—~5.9kAutomated safety check: PassMIT
Polyclawchainstacklabs/polyclaw3591 repos~2kAutomated safety check: PassApache-2.0

Similar skills

  • Alpaca Trading

    gauss314/skills

    Trading API de Alpaca: órdenes, posiciones, cuenta. An agent skill from gauss314/skills.

    248 GitHub stars~2.4k tokensUpdated 3 mo ago
    Business, Finance & HRAuto-check passed
  • Tushare Data

    zillionare/zillionare

    面向中文自然语言的 Tushare 数据研究技能。用于把“看看这只股票最近怎么样”“帮我查财报趋势”“最近哪个板块最强”“北向资金在买什么”“给我导出一份行情数据”这类请求,转成可执行的数据获取、清洗、对比、筛选、导出与简要分析流程。适用于 A 股、指数、ETF/基金、财务、估值、资金流、公告新闻、板块概念与宏观数据等研究场景。

    322 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed
  • Tradingview MCP

    atilaahmettaner/tradingview-mcp

    AI Trading Intelligence — live prices, 30+ technical indicators, backtesting (6 strategies), walk-forward overfitting detection, trade logs, equity curves, licensed news sentiment (Marketaux), and…

    5k GitHub stars~1.3k tokensUpdated yesterday
    Business, Finance & HRAuto-check passed
  • Digital Oracle

    komako-workshop/digital-oracle

    Answer prediction questions using market trading data, not opinions.

    878 GitHub stars~5.9k tokensUpdated 2 mo ago
    Business, Finance & HRAuto-check passed
  • Polyclaw

    chainstacklabs/polyclaw

    Trade on Polymarket via split + CLOB execution. An agent skill from chainstacklabs/polyclaw.

    359 GitHub starsUsed in 1 repo~2k tokens
    Business, Finance & HRAuto-check passed
  • Markdown

    facioquo/stock-indicators-dotnet

    Format and lint Markdown in this repository against GitHub Flavored Markdown and its markdownlint-cli2 configuration — headers, lists, code fences, callouts (VitePress containers on docs-site pages…

    1.2k GitHub stars~812 tokensUpdated yesterday
    Business, Finance & HRAuto-check passed

More from alpacahq/alpaca-skills

All 14 skills in this repo
  • Alpaca Broker Account Onboarding

    alpacahq/alpaca-skills

    Open and manage brokerage accounts via the Alpaca Broker API — account creation, KYC/CIP, identity & disclosures, agreements, document upload (incl.

    154 GitHub stars~2.3k tokensUpdated 1 mo ago
    Auto-check passed
  • Alpaca Broker Funding Transfers

    alpacahq/alpaca-skills

    Move money between an Alpaca brokerage account and the EXTERNAL banking world via the Broker API — ACH relationships, wire recipient banks, classic transfers (deposits/withdrawals), the v1beta…

    154 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Alpaca Broker Integration

    alpacahq/alpaca-skills

    Entry point for integrating with the Alpaca Broker API (plus Market Data and Trading APIs) in any programming language.

    154 GitHub stars~3k tokensUpdated 1 mo ago
    Auto-check passed
  • Alpaca Broker Journals

    alpacahq/alpaca-skills

    Move cash (JNLC) and securities (JNLS) BETWEEN accounts inside your own Alpaca omnibus via the Broker API — single, batch, and reverse-batch journals, the Idempotency-Key header, journal status…

    154 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Alpaca Broker Money Precision

    alpacahq/alpaca-skills

    Handle money and numeric precision correctly with the Alpaca API — numbers-as-strings on the wire, decimals vs floats, rounding/truncation before sending amounts, fractional-share precision, and…

    154 GitHub stars~1.2k tokensUpdated 1 mo ago
    Auto-check passed
  • Make Alpaca API clients resilient — rate-limit header handling, HTTP 429 backoff, exponential retry, bounded concurrency/worker pools, pagination loops, batch sizing, and timeouts.

    154 GitHub stars~1.4k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Alpaca Trading Paper Trading CLI

What does Alpaca Trading Paper Trading CLI do?

Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI. Alpaca Trading Paper Trading CLI is an agent skill from alpacahq/alpaca-skills. Preview, submit, inspect, and manage Alpaca paper-trading orders using the Alpaca CLI.

When should I use Alpaca Trading Paper Trading CLI?

Alpaca Trading Paper Trading CLI fits situations like: you want your AI agent to take a strategy signal and execute it as a paper trade through the Alpaca command-line interface; tasks that involve Trading and backtesting.

How do I install Alpaca Trading Paper Trading CLI in Claude Code?

Run `npx skills add alpacahq/alpaca-skills --skill alpaca-trading-paper-trading-cli -a claude-code`. Or copy the skill folder (skills/trading-api/paper-trading-cli in alpacahq/alpaca-skills) into .claude/skills/alpaca-trading-paper-trading-cli in your project. Claude Code loads it when a task matches its description.

How do I install Alpaca Trading Paper Trading CLI in Codex?

Run `npx skills add alpacahq/alpaca-skills --skill alpaca-trading-paper-trading-cli -a codex`. Or copy the skill folder (skills/trading-api/paper-trading-cli in alpacahq/alpaca-skills) into .agents/skills/alpaca-trading-paper-trading-cli in your project. Codex loads it when a task matches its description.

Can I use Alpaca Trading Paper Trading CLI in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add alpacahq/alpaca-skills --skill alpaca-trading-paper-trading-cli -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/alpaca-trading-paper-trading-cli, .gemini/skills/alpaca-trading-paper-trading-cli, .github/skills/alpaca-trading-paper-trading-cli and .opencode/skills/alpaca-trading-paper-trading-cli in your project.

What does Alpaca Trading Paper Trading CLI need to run?

Going by SKILL.md and its folder, Alpaca Trading Paper Trading CLI needs the command-line tools its instructions call (go, brew and bash) and credentials named ALPACA_API_KEY, ALPACA_PAPER_API_KEY, ALPACA_SECRET_KEY and ALPACA_PAPER_SECRET_KEY.

Does Alpaca Trading Paper Trading CLI access the network?

SKILL.md names 4 domains. In commands or code: paper-api.alpaca.markets and api.alpaca.markets; the agent is likely to contact these when it follows the instructions. As links in the text: docs.alpaca.markets and alpaca.markets. This is read from the text; nothing was executed.

Is Alpaca Trading Paper Trading CLI safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Alpaca Trading Paper Trading CLI use?

Alpaca Trading Paper Trading CLI is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Alpaca Trading Paper Trading CLI use?

About 9k tokens (SKILL.md is roughly 36k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Alpaca Trading Paper Trading CLI?

Skills that share tags, products or a category with Alpaca Trading Paper Trading CLI: Alpaca Trading (gauss314/skills, 248 stars), Tushare Data (zillionare/zillionare, 322 stars), Tradingview MCP (atilaahmettaner/tradingview-mcp, 5k stars) and Digital Oracle (komako-workshop/digital-oracle, 878 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Alpaca Trading Paper Trading CLI?

alpacahq (a GitHub organization) maintains it in alpacahq/alpaca-skills, which has 154 GitHub stars. The repository holds 14 skills in this directory. The repository was last updated on September 8, 2026.

Source: alpacahq/alpaca-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.