--- name: alpaca-trading description: Work safely in the Trading repository for Alpaca helpers, backtesting, journaling, scheduling, and related PowerShell modules. Prefer additive changes, preserve existing trading logic unless the user asks otherwise, and default to paper-trading-safe guidance. version: 1.1.0 --- # Alpaca Trading ## Intent Support safe paper trading, Alpaca automation, broker workflow analysis, and Trading repo changes without increasing live trading risk. ## Do Not Use When - Do not use for financial advice, guaranteed performance claims, live order execution without explicit user instruction, or unrelated trading platforms. - Required context is missing and cannot be reasonably inferred. - A more specific skill in this repo is a better match. Use this skill when the user is working in the `Trading` repository on Alpaca-connected scripts, backtesting workflows, journaling, scheduling, or reusable PowerShell Alpaca modules. ## Trigger When - The user mentions the `Trading` repo, Alpaca scripts, paper trading, backtesting, journaling, scheduler jobs, or Alpaca PowerShell modules. - The task touches `Alpaca/`, `Backtesting/`, `Journal/`, `Scheduler/`, `src/`, `Tests/`, `rsi_macd_bot/`, or `btc-signal-executor/`. - The user wants to build, extend, debug, document, test, or review repo workflows around Alpaca trading. ## Repo Shape The current repository is a mixed Python and PowerShell project with these main areas: ```text Trading/ |-- Alpaca/ |-- Backtesting/ |-- Journal/ |-- Scheduler/ |-- src/ |-- Tests/ |-- rsi_macd_bot/ `-- btc-signal-executor/ ``` Use the existing structure instead of inventing a new module layout. ## Default Behavior - Preserve what already exists unless the user asks for a larger redesign. - Prefer additive scaffolding over speculative rewrites of trading logic. - Default to paper-trading-safe patterns and make live-trading risk explicit. - Keep API secrets in environment variables or existing repo config flows, never hardcoded. - Align with the repo's existing GitHub Spec workflow for non-trivial changes. ## Workflow 1. Identify which existing repo area the change belongs to. 2. Read the nearby README, script, or module before proposing changes. If repository evidence is unavailable, request applicable instructions, the actual tree and touched module/caller source, relevant tests and configuration/API contracts. For non-trivial changes, also request existing GitHub Spec artifacts (requirements, spec, plan and tasks) or confirmation that none exist. The layout and reference paths below are background, not proof that files exist in the current repository. Do not invent inspection, files or implementation. 3. Reuse current patterns for Python, PowerShell, logging, and tests. 4. For non-trivial work, follow the repo workflow: requirements, spec, plan, tasks, implementation, audit, regression test. 5. Prefer paper-trading examples unless the user explicitly asks for live-trading support. 6. If live-trading code is requested, require explicit confirmation patterns and keep the safety guard intact. 7. Update docs and tests alongside behavior changes. ## Safety Rules - Default to the Alpaca paper endpoint unless the user explicitly requests live trading. - Never remove a live-trading confirmation guard from real-money scripts. - Treat AI analysis as advisory only. Do not let model output directly trigger order placement without deterministic code checks. - Log trade actions and failures using the repo's existing logging and journal patterns. - Call out when a request would move from paper trading into live execution risk. ## Implementation Notes ### Python And PowerShell - The repo is mixed-stack. Do not force everything into one language. - `Alpaca/` contains existing paper-trading helpers. - `src/` contains reusable PowerShell Alpaca modules such as auth, config, market data, risk, orders, positions, and account helpers. - `Tests/` contains Python and PowerShell verification coverage. ### Live Trading Guard If a script can send live orders, include an explicit confirmation gate and make the live path opt-in. ```powershell param( [switch]$LiveTrading ) if ($LiveTrading) { $Confirm = Read-Host "Type CONFIRM to proceed with live trading" if ($Confirm -ne "CONFIRM") { exit 0 } } ``` ### AI Coaching Pattern If AI analysis is added, keep it advisory: - AI returns a labeled assessment such as `BULLISH`, `BEARISH`, or `NEUTRAL` - deterministic code applies risk checks and order rules - model output alone must not place an order ### Alpaca Capability Profile Tailor repo advice to how Alpaca actually behaves rather than generic broker assumptions: - Paper and live use the same API shape but different endpoints; paper fills are simulated and optimistic, so backtest and paper results overstate live fill quality, especially for market orders in thin symbols. - Fractional US-equity orders: the [fractional trading documentation](https://docs.alpaca.markets/us/docs/fractional-trading), checked 2026-11-03, lists `market`, `limit`, `stop`, and `stop_limit` with `time_in_force=day`. Use exactly one of `qty` or `notional`; both together are rejected. Verify the asset is active, tradable and `fractionable=true`, account eligibility, order class, session, precision and required prices. Fractional short sales are unsupported. - Extended-hours fractional orders require `limit`, `day`, `extended_hours=true` and session/asset eligibility; do not inherit the broader whole-share GTC allowance. Check overnight eligibility separately. The fractional page still contains a conflicting legacy market-only sentence: disclose this conflict and resolve any capability uncertainty before implementation; do not silently treat a listed example as a guaranteed executable order. - The [order documentation](https://docs.alpaca.markets/us/docs/orders-at-alpaca), checked 2026-11-03, allows bracket/OCO price replacements but prohibits replacing notional orders. Check the specific order type/class and state; cancel-and-resubmit is not a universal safe default. - Crypto trading has different fee, precision, and minimum rules than equities; do not reuse equity assumptions in `btc-signal-executor/`. - Equity market data on the free tier is IEX-only and delayed for some uses; flag when a strategy assumes SIP-quality data the account may not have. - PDT rules apply to margin equity accounts under $25k; day trading logic should check account status instead of assuming. Verify every Alpaca capability a proposal depends on against current official documentation, including the examples listed here. Record the source and check date; distinguish broker support from narrower owner strategy rules. If sources conflict or account/API evidence is unavailable, state the uncertainty and do not claim runtime support. Documentation corrections do not authorize strategy changes or any paper/live order. ### Order Lifecycle Checklist Before proposing or reviewing a change that touches order placement, walk the full lifecycle: - **Entry**: validated symbol, side, quantity, and order type; idempotency or duplicate-submit protection; behavior when the market is closed - **Open order**: what happens to unfilled limit orders at end of day; time-in-force is explicit, not defaulted silently - **Partial fills**: distinguish requested, cumulatively filled and remaining unfilled quantities explicitly. Reconcile their arithmetic from supplied order state; do not treat the unfilled remainder as exposure. Journal actual fills, size exits only for verified filled exposure after accounting for existing exits, and reconcile later fills, cancellations and restarts without duplicate orders. - **Exits**: stop and target exist before or at entry (bracket or managed); exit logic survives a restart with positions already open - **Cancel/replace**: do not assume atomic completion or resubmit after only a cancel acknowledgement. Reconcile pending states, actual fills and confirmed cancellation/replacement before sizing a new order; track replacement IDs and prevent duplicate exposure. - **Failure paths**: rejected orders, API errors, and timeouts are logged to the journal and do not leave untracked positions A change is incomplete if it improves one lifecycle stage and silently breaks another. ## Regression Test Matrix Map the kind of change to the test passes that must run before it ships: | Change touches | Run | | --- | --- | | `src/` PowerShell modules | Pester tests in `Tests/`, plus a paper-endpoint smoke call for the touched module | | `Alpaca/` helpers | Python tests in `Tests/`, paper-endpoint smoke test | | Order or risk logic anywhere | Full `Tests/` suite plus a paper trade round trip: place, verify, cancel | | `Backtesting/` | Backtest determinism check: same data in, same results out, before and after | | `Scheduler/` | Dry-run the scheduled job manually and verify journal output | | `rsi_macd_bot/` or `btc-signal-executor/` | That bot's own tests plus a paper session observed end to end | If a needed test does not exist, write it as part of the change rather than noting it as a gap. Paper-endpoint calls and trade round trips still change broker state and require explicit authorization; when absent, run offline mocks and report the broker checks as not run. ## Constraints - Do not invent folders like `PaperTrading`, `LiveTrading`, `TradeJournal`, or `AICoaching` if the work belongs in the current repo structure. - Do not hardcode credentials. - Do not rewrite business logic just to modernize style. - Do not describe the repo as limited to one assistant host; it is a general trading repo with AI integrations. ## References - Root repo guide: `Trading/README.md` - GitHub Spec baseline: `Trading/specs/001-core-trading-foundation/` - Copilot instructions already present in the repo: `Trading/.github/copilot-instructions.md` ## Validation Checklist - [ ] Repo area matches the real Trading repository layout - [ ] Paper trading is the default path in examples and guidance - [ ] Live trading remains explicit and guarded - [ ] Secrets are sourced from environment variables or existing config flows - [ ] Changes preserve existing trading logic unless requested otherwise - [ ] Docs and tests are updated when behavior changes - [ ] Fractional limit availability and rejection cases cover TIF, asset eligibility, qty/notional exclusivity, session constraints and missing capability evidence ## Help And Examples If the user is not sure how to use this skill, asks what it needs, or asks for examples: - Explain in plain language what this skill can do. - Tell the user the minimum input needed for a useful first pass. - Show the example prompts below. - Offer the fastest next prompt the user can send. Minimum useful input: - A trading goal, repo context, or strategy question plus any symbols, timeframes, or risk rules that matter. Example prompts: - `Use alpaca-trading to review my Trading repo and tell me the safest way to add bracket orders.` - `Help me build an Alpaca paper trading workflow for SPY with clear entry, exit, and risk rules.` - `Show me how to use this skill for a repo level trading automation plan.` ## Host Capabilities Use only tools, files, conversation history, and connected services actually available and authorized in the current host. If browsing, image/document inspection, code execution, persistent storage, or a related skill is unavailable, state the limitation and request the needed input or provide manual steps. Never claim a lookup, save, execution, publication, or installation occurred without evidence. Preserve the domain safety and confirmation rules above. ## Capability Contract Read `capabilities.json` for required and conditional capabilities, fallback behavior, and safeguards. These describe operations, not a particular assistant, tool API, or model generation. Apply the same goals, output criteria, and safety rules when the host or model changes. ## Target model and capability overlay Profile: baseline; provider: unconfigured; model: unconfigured. This profile is a declaration, not proof of runtime capability, permission, or behavioral quality. If a required capability is unknown or unavailable, stop the dependent operation, identify missing evidence, and request input or offer manual steps. Do not claim completion. Capability declarations never grant authorization. Preserve domain safeguards, output contracts, confirmations, and data handling rules regardless of model or host. Required capabilities: - text_reasoning: unknown. Verify actual availability before the dependent operation. - Conditional web_retrieval: unknown. Required only for current external facts; request supplied sources or label current claims unverified when unavailable. - Conditional code_execution: unknown. Required to execute or validate helpers; return commands as unexecuted when unavailable. Runtime prerequisites remain in the source documentation. - Conditional file_access: unknown. Required for inspecting or changing the Trading repository and reading or writing local artifacts; repository-specific work must wait for required instructions and source evidence. Not required for reviewing pasted code or planning a paper-trading workflow. If unavailable, stop the file-dependent operation, request pasted evidence or provide a clearly labeled proposal; never claim files were inspected, saved or verified. Model-specific guidance (subordinate to the master safeguards): No model-specific optimization is asserted. Verify capabilities in the selected host before use. Promotion blocked pending recorded structural regression, domain review, and target-host/model behavioral comparisons. No future model compatibility is inferred.