# Exchange State Management Prompt

Goal: Build the smallest exchange state-management runtime that passes the required behavior checks before adding exchange-specific features.

Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.

Start with:
- Exchange State Management Agent Manifest: https://siebly.io/.well-known/agent-manifests/exchange-state-management/latest.json
- Exchange State Management Runtime Kit: https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/index.json
- Exchange State Management Runtime Types: https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/types.ts
- Exchange State Management Integration Kit: https://siebly.io/.well-known/integration-kits/exchange-state-management/latest.json
- Exchange State Management Conformance Pack: https://siebly.io/.well-known/conformance/exchange-state-management/latest.json

Then apply the selected exchange overlay for SDK methods, request fields, topics, and rejection codes.

Primary spec:
- Use Exchange State Management as the primary spec. Use the selected exchange recipe as the default machine build path, integration kits for exact exchange fields and errors, manifests and runtime kits for advanced reusable-runtime scaffolding, and [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) for post-implementation validation.
- Save this exact prompt or spec in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard), plus the prompt manifest, workflow state machine, private-event routing table, confirmation lifecycle, durable-context lifecycle, plan, and environment example before exchange calls.
- Verify installed SDK/API clients, request builders, custom ID fields, private topics, filters, error shapes, reconnect hooks, and shutdown methods from installed declarations/source before coding exchange adapters.
- Create the exchange-state runtime modules before exchange-specific adapters. Use the runtime kit when reusable scaffolding or typed module contracts are needed.
- After implementation, generate or run local tests from the applicable [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) in the exchange-state and selected exchange [conformance packs](https://siebly.io/reference/glossary#conformance-pack) before enabling write-capable execution modes.
- Implement the event-driven private-state loop (ws_symbol_side_action_gated). Private events update [Account State](https://siebly.io/reference/glossary#accountstate), record the [affected scope](https://siebly.io/reference/glossary#affected-scope), give related events a short bounded window to arrive, and one [workflow owner](https://siebly.io/reference/glossary#workflow-owner) chooses one [action family](https://siebly.io/reference/glossary#action-family). Accepted mutations stay [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation) until [private confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) or [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery), and REST state fetches happen only at trust boundaries.
- Each reconciliation pass chooses one [action family](https://siebly.io/reference/glossary#action-family) only: recover uncertain state, clean up stale app-owned orders, repair/place protection, place/repair DCA, do nothing, or wait because required evidence or configuration is missing.
- Do not enter REST recovery just because private order, execution, fill, or position events arrived. If the private stream is healthy and [Account State](https://siebly.io/reference/glossary#accountstate) has ingested the matching order evidence plus the matching position or account evidence, continue from private-stream account state without REST hydration. For products without exchange-provided position rows, locally derived position evidence fills the same role.
- Plan protective SL/TP before exposure-increasing DCA for a fresh managed position. DCA runs only after protection is trusted or scoped recovery proves the account state.

Execution mode:
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- Order-capable execution mode contract: implement one environment variable, EXECUTION_MODE, with exactly these values: PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Set the default for order-capable local runs and .env.example to EXECUTION_MODE=DRY_RUN_PRIVATE. PUBLIC uses no API keys and cannot create private clients, account readers, [order intents](https://siebly.io/reference/glossary#order-intent), or exchange write requests. READ_ONLY_PRIVATE may use read-only credentials for balances, orders, fills, native positions, or local position-derivation inputs, but cannot place, amend, cancel, borrow, transfer, lever, or otherwise mutate exchange state. DRY_RUN_PRIVATE may use private state and must build the exact place/amend/cancel request objects that DEMO, TESTNET, or LIVE would send, but the submitter records them without calling exchange mutation endpoints. DEMO and TESTNET are write-capable only when the selected exchange supports those non-production venues; if unsupported, they must fail closed with a clear configuration error and must never silently route to production. DEMO may call place/amend/cancel endpoints only against the selected exchange's demo or sandbox environment, and TESTNET may call them only against the selected exchange's testnet environment. LIVE is the only mode that may call production exchange place/amend/cancel endpoints. The finished order-capable project must include the LIVE execution path for the selected exchange and supported DEMO/TESTNET paths where those venues exist; do not leave LIVE submission as a TODO.

Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.

Acceptance criteria:
- Runtime modules exist for order context, accountstate, affected-scope work items, confirmations, recovery, planning, submission, and error classification.
- RecoveryRequired/syncRequired hydrate before normal cleanup, protection, DCA, or submission resumes.
- [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) are lookup keys into durable local order context, not state containers.
- Split trust by subject: order trust, position trust, filter trust, context trust, and readiness trust.
- A TP/SL/DCA order update proves only order trust; it does not prove position trust, position size, entry/cost basis, exposure, or replacement eligibility.
- For products with exchange-provided position rows, order/fill events are triggers; replacement planning waits for matching position trust from private position or account updates or scoped recovery.
- For products without exchange-provided position rows, derive local position state from fills/executions, fees, account events, balance updates, and documented matching rules before managed exits, exposure changes, or re-hedging.
- If configuredSymbols is blank, absent, or empty, auto-detect eligible open positions. When symbols are configured, treat them as an allowlist: manage matching detected positions only and ignore or log out-of-scope private events without mutation. Sample symbols from docs, tests, prompts, or quickstarts are examples only; never use them as runtime defaults.
- For broad TP/SL/DCA position managers, use percentage-based strategy inputs by default: derive TP, DCA, and SL prices plus DCA size from trusted entry and position size before order planning.
- Absolute TP/DCA/SL prices or DCA quantities are advanced per-symbol operator overrides, not the primary config model. If allowed, they must be explicit, scoped, compatible with percentage defaults, and validated through the same filters and risk geometry.
- Startup validation rejects missing, invalid, contradictory, or non-finite strategy inputs before private clients, WebSocket subscriptions, hydration, or exchange mutation.
- Validate risk geometry before exchange mutation: for long positions, TP is above entry, DCA is below entry, and SL is below DCA; for short positions, TP is below entry, DCA is above entry, and SL is above DCA.
- Reject missing or invalid TP/DCA/SL strategy outputs before order placement. After derivation or override, quantize prices and quantities with hydrated exchange filters before final validation.
- After quantization, revalidate risk geometry, min/max, and notional rules; reject only if the quantized TP/DCA/SL values are equal, crossed, or otherwise violate geometry or filters before [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE order placement.
- Risk geometry validation uses the trusted entry price or explicit operator override, hydrated tick/lot filters, and the managed side before any place/amend/cancel request.
- EXECUTION_MODE is documented as the only execution-mode switch, with allowed values PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Tests or fixtures prove PUBLIC and READ_ONLY_PRIVATE cannot build or submit exchange writes, DRY_RUN_PRIVATE builds the final request objects without calling exchange mutation endpoints, DEMO and TESTNET refuse unsupported exchange venues and can write only to the selected non-production venue, and LIVE is the only mode that can call production exchange mutation endpoints.
- Required [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) pass before EXECUTION_MODE=DEMO, TESTNET, or LIVE submission.
- Do not mark the implementation complete until three consecutive full identity-chain review passes produce no code, tests, fixtures, or documentation changes.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
