alpaca-broker-reconciliation-idempotency-k268

Alpaca broker reconciliation and idempotency-specific skill that helps an AI agent efficiently perform tasks related to Alpaca broker reconciliation and idempotency.

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-reconciliation-idempotency-k268" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-89369489e5a6f9f993a06feed2e699cf46f28d51d0fd2b80f2f6841a9723de2a. Verify the upstream source and version against https://skillhub.cn/skills/user_3c6cb52e/alpaca-broker-reconciliation-idempotency-k268 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

Alpaca broker reconciliation and idempotency-specific skill that helps an AI agent efficiently perform tasks related to Alpaca broker reconciliation and idempotency.

0 Downloads

Introduction source: third_party · user_3c6cb52e · 1.0.0 Reference

SkillPi interpretation

Tasks
This is the skill that separates a demo from production. Alpaca is an **asynchronous, eventually-consistent** system: writes settle later, events can be missed or replayed, some rails emit no events at all, and "executed" can still be reversed. Your job is to make your local database a faithful, self-healing mirror of Alpaca's state.
Audience
Not specified in the source documentation.
Inputs and outputs
Not specified in the source documentation.
Software, accounts and paid services
Not specified in the source documentation.
Limits and differences
Not specified in the source documentation.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: Alpaca券商对账与幂等
slug: alpaca-broker-reconciliation-idempotency
version: 1.0.0
displayName: Alpaca券商对账与幂等
description: >
  Alpaca券商对账与幂等专用技能,帮助AI Agent高效完成相关任务。
summary: "Keep local state correct against the Alpaca Broker API — idempotency keys, ID-keyed upserts, event snapshotting and dedup, polling rails that have no events, nightly reconciliation/heal jobs, status s..."
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 — Reconciliation & Idempotency

This is the skill that separates a demo from production. Alpaca is an asynchronous, eventually-consistent system: writes settle later, events can be missed or replayed, some rails emit no events at all, and "executed" can still be reversed. Your job is to make your local database a faithful, self-healing mirror of Alpaca's state.

Read alpaca-broker-integration, alpaca-broker-sse-events, and the relevant domain skills first. This skill is the architecture that ties them together.

The core principle

Treat Alpaca as the source of truth and your DB as a cache that must converge to it. Every write is a request, not a fact. Every event is a hint, not a guarantee. Correctness comes from idempotent processing plus a reconciliation loop — never from assuming any single call or event succeeded exactly once.

1. Three layers of defense

Layer 1 — Idempotent writes      : never create a duplicate when you retry
Layer 2 — Idempotent event intake: never double-process a replayed/duplicate event
Layer 3 — Reconciliation sweep   : re-pull authoritative state and fix any drift

You need all three. Layer 1+2 keep you correct in the happy/retry case; Layer 3 catches everything that still slips through (downtime, bugs, missing events, corrections).

2. Layer 1 — Idempotent writes

Every money/order write must be safe to retry, because you can't tell a timeout apart from a success.

  • Orders: set your own client_order_id (≤128 chars) derived from your transaction ID. On a lost response, look the order up via orders:by_client_order_id before retrying.
  • Journals: send an Idempotency-Key header. Same key + same body returns the original journal; same key + different body → 422. (See alpaca-broker-journals.)
  • Local-first ordering: write your intent row (with a generated key) before the network call, so a crash mid-call leaves a record you can reconcile — never an orphaned Alpaca object you can't find.
  • Persist the returned Alpaca ID immediately (account_id, order_id, journal_id, transfer_id). It is your only correlation key for events and reconciliation.

3. Layer 2 — Idempotent event intake

Events are at-least-once: replay cursors, reconnects, and corrections all cause the same event to arrive more than once.

  • Snapshot-first, keyed on event_id. Insert the raw event with upsert / skip-on-duplicate on event_id (a ULID). A duplicate becomes a no-op. This single unique constraint is your dedup boundary.
  • Key business records on the Alpaca ID, not on a local autoincrement, with upsert semantics.
  • Guard transitions by current status. Before acting, check the record isn't already terminal — so a duplicate "executed"/"filled" doesn't re-fire a payout or notification.
  • Lock the row while mutating (SELECT … FOR UPDATE or your engine's equivalent) so concurrent events for one record serialize.
  • Advance the cursor only after success (at-least-once, made safe by the above).

4. Layer 3 — Reconciliation / heal jobs

A scheduled job that re-pulls authoritative state from Alpaca and upserts it locally. This is what makes the system self-healing.

Canonical nightly heal (lesson):

  1. For each active account, page through trade activities and non-trade activities (GET /v1/accounts/activities, paginated) for the last N days (e.g. 3) — a moving window that re-covers recent days so anything missed by SSE gets backfilled.
  2. Page through journals (GET /v1/journals) and transfers for the same window.
  3. Upsert each into your tables keyed on the Alpaca ID (insert-or-update). Re-running is safe and converges.
  4. Bound concurrency (a small worker pool) and respect rate limits (alpaca-broker-rate-limits-resilience).

Why a window and not just "since last run": it absorbs corrections, late settlements, and any events dropped during a deploy — without rescanning all history every night.

5. Polling the rails that have no events

Not everything emits SSE. Where there's no event, you must poll.

  • Funding-wallet per-transfer status (v1beta) is not pushed — poll GET /v1beta/.../funding_wallet/transfers/{id} on a schedule.
  • Stagger pollers (e.g. one rail at :00, another at :30) to spread API load.
  • Only poll records in a non-terminal state. Filter your query to status IN (pending, processing, …); once a record reaches a terminal status, drop it from the polling set. This bounds the work and prevents re-notifying.
  • Gotcha — no GET-by-id on classic wire transfers: you must GET /v1/accounts/{id}/transfers?direction=OUTGOING (a list) and match the ID client-side; cache the list per account within a run.

Lesson: polling implies latency. Document the expected lag (e.g. "withdrawal status updates within ~1h") so product/support set the right expectations.

6. Status state-machine mapping

Alpaca exposes several status enums (account, order, journal, transfer, funding-wallet) — each with its own vocabulary. Don't scatter raw Alpaca strings through your app.

  • Define one explicit mapping table per domain from Alpaca status → your internal status (e.g. executed/COMPLETE → COMPLETED; rejected/canceled/returned/failed → CANCELLED).
  • Handle unknown statuses gracefully — log and skip, never crash. Alpaca adds values (and has shipped bad ones — e.g. a stray TRD activity type that consumers had to filter out).
  • Know which states are terminal (they differ per enum) so you stop polling/processing them.

7. Eventual-consistency hazards to design for

  • executed/COMPLETE is not always final — journals can be reversed by cashiering; transfers can be RETURNED after appearing done. Keep reconciling past the "happy" terminal state for a window.
  • Corrections create new IDs. A journal correct cancels the original and issues a new journal ID carrying the real funds. Reconciliation keyed on event snapshots + Alpaca IDs handles this; logic that mutates the original record in place does not.
  • 200 means accepted, not settled. Never confirm money moved to a user off the create response — confirm off the terminal event/poll.
  • Out-of-order & duplicate events are normal (see alpaca-broker-sse-events §5). Idempotency absorbs them.

8. Anti-patterns (seen in the wild)

  • ❌ Reconnecting an SSE stream without a since_id cursor → silently drops every event during the gap. (Fix: persist + replay the cursor.)
  • ❌ Treating an SSE stream as your only source → no backstop for missed events. (Fix: add the heal job.)
  • ❌ Blind retry of a journal/order without an idempotency key → double money movement.
  • ❌ Acting on executed as irreversible → broken books when a reversal/correction lands.
  • ❌ Dedup keyed on a confirmed set instead of a seen set → judge/reject churn re-processes forever. Dedup on everything seen, key on the Alpaca/event ID.

9. Putting it together

WRITE:   local intent row (idempotency key) → Alpaca call → store Alpaca ID
LIVE:    SSE consumer (cursor-replay, snapshot-keyed dedup, status-guarded upsert)
POLL:    schedulers for rails with no events (non-terminal records only)
HEAL:    nightly window re-pull of activities/journals/transfers → upsert
MAP:     Alpaca status → internal status, terminal-aware, unknown-tolerant

Related skills: event consumption mechanics → alpaca-broker-sse-events; idempotency keys per domain → alpaca-broker-journals, alpaca-broker-trading-orders; polling rails → alpaca-broker-funding-transfers; backoff & rate limits in heal jobs → alpaca-broker-rate-limits-resilience.

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 Value92/100

Highlights

  • 针对 Alpaca 券商异步、最终一致性系统提供完整对账与幂等架构方案
  • 解决金融交易场景下的核心痛点:重复写入、事件去重、状态漂移修复
  • 适用于量化交易生产环境,具备高实用价值
Trigger Precision95/100

Highlights

  • 触发词精准覆盖 Alpaca 对账与幂等核心功能
  • description 位置正确且内容完整,边界清晰
Structure and Standards94/100

Areas to improve

  • 缺少 When to Use 显式章节 Reported severity: Minor

    文档未设置独立的 When to Use 章节,但使用场景已在开头描述中体现

    Recommendation: 建议增加显式的 When to Use 章节以提升可读性

Highlights

  • 文档结构清晰,分 9 个逻辑章节完整覆盖三层防御机制
  • 提供具体实现步骤、代码示例与反模式警示
  • frontmatter 完整,符合规范
Execution Reliability93/100

Highlights

  • 工具来源明确(Alpaca API),参数说明清晰
  • 覆盖主要异常场景并提供 nightly heal 兜底机制
  • 不可逆操作有确认机制,确保资金安全
Evidence Verifiability (mean of the first four)94/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.

Not specified in the source documentation.

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