alpaca-broker-rate-limits-resilience-uqtv

Skill for Alpaca broker rate limits and resilience, helping an AI Agent efficiently handle tasks related to broker rate limits and system resilience for Alpaca.

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "alpaca-broker-rate-limits-resilience-uqtv" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-c5a40dae07db06b1422bec688e7f219f83b83a76617be98f0ff4b4811ec86190. Verify the upstream source and version against https://skillhub.cn/skills/user_3c6cb52e/alpaca-broker-rate-limits-resilience-uqtv before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

skillhub.cn

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Skill for Alpaca broker rate limits and resilience, helping an AI Agent efficiently handle tasks related to broker rate limits and system resilience for Alpaca.

0 Downloads

Introduction source: third_party · user_3c6cb52e · 1.0.0 Reference

SkillPi interpretation

Tasks
Alpaca's APIs are rate-limited and occasionally flaky under load. Any client that does more than a handful of calls — especially bulk jobs, backfills, and reconciliation sweeps — needs disciplined retry, backoff, and concurrency control. These patterns are transport-level and apply in any language.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: Alpaca券商限频与韧性
slug: alpaca-broker-rate-limits-resilience
version: 1.0.0
displayName: Alpaca券商限频与韧性
description: >
  Alpaca券商限频与韧性专用技能,帮助AI Agent高效完成相关任务。
summary: "Make Alpaca API clients resilient — rate-limit header handling, HTTP 429 backoff, exponential retry, bounded concurrency/worker pools, pagination loops, batch sizing, and timeouts. Use when building r..."
license: MIT
category: 量化交易
framework:
  - Claude Code
  - Codex
  - Hermes Agent
  - OpenClaw
  - QClaw
  - WorkBuddy
platform: multi-platform
homepage: https://github.com/1991513ccie-png
repository: https://github.com/1991513ccie-png

Alpaca — Rate Limits & Resilience

Alpaca's APIs are rate-limited and occasionally flaky under load. Any client that does more than a handful of calls — especially bulk jobs, backfills, and reconciliation sweeps — needs disciplined retry, backoff, and concurrency control. These patterns are transport-level and apply in any language.

Read alpaca-broker-integration first.

1. Rate-limit headers — read them on every response

Alpaca returns standard headers:

Header Meaning
X-RateLimit-Limit requests allowed in the window
X-RateLimit-Remaining requests left in the current window
X-RateLimit-Reset unix timestamp (seconds) when the window resets

Parse them on every response, not just on errors. Two uses:

  • Proactive: when Remaining drops below a threshold (e.g. ≤ 50), log a warning and/or slow down — you're about to get throttled.
  • Reactive: on 429, use Reset to wait exactly until the window opens.

Limits vary by endpoint and plan; market-data limits differ from broker limits. Don't hardcode a number — react to the headers.

2. The retry loop (pseudocode)

MAX_ATTEMPTS = 10
INITIAL_DELAY_MS = 1000

for attempt in 1..MAX_ATTEMPTS:
    res = http(request)                      # with a sane timeout (see §5)
    remaining, reset_at = parse_rate_headers(res.headers)
    if remaining <= 50: log_warn("approaching rate limit", reset_at)

    if res.status == 429:
        # wait until the window resets, plus a small buffer
        wait = (reset_at - now()) if reset_at else INITIAL_DELAY_MS * 2^(attempt-1)
        sleep(max(0, wait) + 1000)           # +1s buffer past reset
        continue

    if res.status in (500, 502, 503, 504) or network_error:
        sleep(INITIAL_DELAY_MS * 2^(attempt-1))   # exponential backoff
        continue

    return res                                # success or non-retryable 4xx
raise last_error

Key points:

  • On 429, wait until X-RateLimit-Reset + a ~1s buffer — don't blindly exponential-backoff when the API told you exactly when to retry.
  • Exponential backoff (base * 2^(attempt-1)) for network errors and 5xx. With base 1s and 10 attempts the tail is minutes — fine for background jobs, too slow for user-facing calls (use fewer attempts there).
  • Don't retry non-retryable 4xx (400/403/422) — those won't fix themselves; surface them.
  • Optionally add jitter to backoff to avoid thundering-herd when many workers retry together.

3. Bounded concurrency

Parallelism speeds bulk jobs but is the fastest way to hit limits. Use a fixed worker pool, not unbounded fan-out.

  • Start small (e.g. 5–8 concurrent requests) and tune against the rate-limit headers. A real lesson from production: a pool was reduced from 10 → 5 to ease both Alpaca and downstream-DB load.
  • Cache per-entity reads within a run (e.g. an account's buying power, or a per-account transfer list) so you don't refetch the same thing across items in a batch.
  • For per-item throttling, a small fixed sleep between calls (e.g. 100ms) is a crude-but-effective floor when you can't easily coordinate a pool.

4. Pagination loops

List endpoints page forward with a token — never assume one response is complete.

  • Activities (/v1/accounts/activities): page via the X-Next-Page-Token response header; loop until it's empty. Use page_size (≤100) and a direction.
  • Market-data bars (/v2/stocks/bars): page via next_page_token in the body → pass back as page_token. Remember limit counts across all symbols and results sort by symbol-then-time, so a single page may contain only the first symbol(s) — keep paging.
  • Wrap each page fetch in the retry loop from §2.
token = null
loop:
    page = fetch(url + (token ? "&page_token="+token : ""))   # via retry loop
    accumulate(page.items)
    token = page.next_token            # header or body, per endpoint
    if not token: break

5. Timeouts & batch sizing

  • Always set an HTTP timeout (e.g. 15–30s). A hung connection without a timeout stalls a whole worker pool. (SSE streams are the exception — they're meant to stay open; see alpaca-broker-sse-events.)
  • Use a shared HTTP client / connection pool rather than constructing one per request, so keep-alive and connection reuse work.
  • When writing reconciliation results to your own store, chunk bulk inserts (e.g. 500 rows per statement) to stay under DB statement-size limits and keep transactions reasonable.

6. Resilience checklist for a bulk/cron job

  • [ ] Rate-limit headers parsed every response; proactive warn near the limit.
  • [ ] 429 → wait until X-RateLimit-Reset + buffer.
  • [ ] Exponential backoff (+ jitter) for 5xx/network; capped attempts.
  • [ ] Non-retryable 4xx surfaced, not retried.
  • [ ] Bounded worker pool; per-run caching of repeated reads.
  • [ ] Pagination loop until the token is empty.
  • [ ] HTTP timeout on every call; shared client.
  • [ ] Bulk DB writes chunked and idempotent (upsert) — see alpaca-broker-reconciliation-idempotency.
  • [ ] Structured logging with a trace/correlation ID per item for debugging partial failures.

Related skills: safe re-runs of jobs → alpaca-broker-reconciliation-idempotency; the heal/poll jobs that use these patterns → alpaca-broker-reconciliation-idempotency; market-data pagination specifics → alpaca-broker-market-data.

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value75/100

Highlights

  • 提供 Alpaca 券商 API 限频与韧性处理的完整解决方案
  • 涵盖限频头解析、重试机制、并发控制等关键实践
  • 适用于量化交易场景,解决实际 API 调用痛点
Trigger Precision70/100

Areas to improve

  • 触发词描述不够具体 Reported severity: Minor

    description 描述了 Skill 用途,但未具体说明适用场景的边界条件和具体触发条件

    Recommendation: 建议补充更具体的触发场景描述,如'当需要处理 Alpaca API 限频错误时'或'当进行批量数据获取时'

Highlights

  • description 明确指出了 Skill 的核心功能
Structure and Standards90/100

Highlights

  • 文档结构清晰,分章节详细说明各个处理环节
  • 包含伪代码示例和实际检查清单,便于理解和实施
  • frontmatter 完整,包含必要的元数据信息
Execution Reliability85/100

Areas to improve

  • description 内容截断 Reported severity: Minor

    summary 字段内容在末尾被截断,影响信息完整性

    Recommendation: 建议补全 summary 字段内容,确保信息完整传达

Highlights

  • 提供了详细的限频处理逻辑和重试机制
  • 覆盖主要异常场景,包括 429、5xx 错误处理
  • 给出了具体的参数建议和最佳实践
Evidence Verifiability (mean of the first four)80/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • github.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.