---
title: "Exchange State Management | Siebly AI Agent Guide"
description: "Canonical build path for exchange order, account, and position state systems with private streams, scoped REST hydration, custom order IDs, recovery, and behavior-contract fixtures."
canonical: "https://siebly.io/ai/exchange-state"
---

# Exchange State Management

Build one local exchange-state workflow for in-flight mutations, active orders, account state, [order intent](https://siebly.io/reference/glossary#order-intent), and managed slots such as DCA/TP/SL. After startup, healthy private events are the normal state path; REST hydration is reserved for trust boundaries such as reconnects, gaps, missing prerequisites, unknown outcomes, or conflicting evidence.

## Default Scope

- Runtime: Node.js LTS
- Recommended language: TypeScript
- Implement execution for when [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE is enabled and all gates pass, but keep that path disabled by default.
- [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE is the default local mode for building and logging final place/amend/cancel request candidates.

## Primary Resources

- [Position Management with Binance APIs & WebSockets](/ai/exchange-state/binance)
- [Position Management with Bybit APIs & WebSockets](/ai/exchange-state/bybit)
- [Exchange State Management Agent Manifest](/.well-known/agent-manifests/exchange-state-management/latest.json)
- [Exchange State Management recipe](/.well-known/recipes/exchange-state-management.json)
- [Exchange State Management Runtime Kit](/.well-known/runtime-kits/exchange-state-management/v1/index.json)
- [Exchange State Management Runtime Types](/.well-known/runtime-kits/exchange-state-management/v1/types.ts)
- [Exchange State Management Integration Kit](/.well-known/integration-kits/exchange-state-management/latest.json)
- [Exchange State Management Conformance Pack](/.well-known/conformance/exchange-state-management/latest.json)
- [Exchange State Management Conformance Schema](/.well-known/conformance/exchange-state-management/v1/schema.json)
- [Exchange State Management Conformance Fixtures](/.well-known/conformance/exchange-state-management/v1/fixtures.json)
- [Exchange State Management Conformance Runner](/.well-known/conformance/exchange-state-management/v1/runner.ts)
- [Exchange State Management Prompt Artifact](/.well-known/prompts/exchange-state-management/latest.md)

### Guides

Read the core spec first, then use the exchange implementation guides for SDK clients, fields, topics, product terms, and rejection codes.

- [Position Management with Binance APIs & WebSockets](/ai/exchange-state/binance)
- [Position Management with Bybit APIs & WebSockets](/ai/exchange-state/bybit)

### Machine resources

Use these after the guide path is selected: manifest, recipe, runtime contracts, [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture), and prompt artifact.

- [Exchange State Management Agent Manifest](/.well-known/agent-manifests/exchange-state-management/latest.json)
- [Exchange State Management recipe](/.well-known/recipes/exchange-state-management.json)
- [Exchange State Management Runtime Kit](/.well-known/runtime-kits/exchange-state-management/v1/index.json)
- [Exchange State Management Runtime Types](/.well-known/runtime-kits/exchange-state-management/v1/types.ts)
- [Exchange State Management Integration Kit](/.well-known/integration-kits/exchange-state-management/latest.json)
- [Exchange State Management Conformance Pack](/.well-known/conformance/exchange-state-management/latest.json)
- [Exchange State Management Conformance Schema](/.well-known/conformance/exchange-state-management/v1/schema.json)
- [Exchange State Management Conformance Fixtures](/.well-known/conformance/exchange-state-management/v1/fixtures.json)
- [Exchange State Management Conformance Runner](/.well-known/conformance/exchange-state-management/v1/runner.ts)
- [Exchange State Management Prompt Artifact](/.well-known/prompts/exchange-state-management/latest.md)

## Implementation Phases

### 1. Implementation sequence

Keep the initial scope narrow and prove runtime behavior before optional strategy knobs.

- 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.

### 2. Architecture

Build an order/account/position state machine. Keep one WebSocket-driven product/account [workflow owner](https://siebly.io/reference/glossary#workflow-owner) that drains product/symbol/side work items.

- Private events update [Account State](https://siebly.io/reference/glossary#accountstate) immediately.
- Affected scopes are precise where possible and bounded where not.
- The scheduler uses a short [event-burst wait](https://siebly.io/reference/glossary#event-burst-wait) (150ms, configurable) for related events in the same burst, then runs one workflow pass from settled account state.
- One [workflow owner](https://siebly.io/reference/glossary#workflow-owner) drains one symbol-side scope at a time.
- Keep one planner/recovery loop for each product/account; do not add a second lifecycle path for the same scope.
- A REST submit response creates [Pending Confirmation](https://siebly.io/reference/glossary#pending-confirmation) state; it is not [Trusted State](https://siebly.io/reference/glossary#trusted-state).

### 3. Non-confirmation evidence

These inputs can update local state, clear latches, or schedule work, but they do not prove that a protective slot is safely active.

- REST place/amend/cancel acceptance: record or match [Pending Confirmation](https://siebly.io/reference/glossary#pending-confirmation). Transport or request success does not prove active open-order state.
- Terminal order row: clear or terminalize the matching latch. Cancelled, rejected, filled, deactivated, triggered, or equivalent rows are not active slot evidence.
- Execution or fill row: update fills and record the affected scope. Fill evidence can change position/order state but does not confirm active open-order existence or [Position Trust](https://siebly.io/reference/glossary#position-trust).
- Private order update: update [Order Trust](https://siebly.io/reference/glossary#order-trust), match pending confirmations, and record the affected scope. [Order Trust](https://siebly.io/reference/glossary#order-trust) is not [Position Trust](https://siebly.io/reference/glossary#position-trust). When the exchange provides position rows, replacement planning waits for a matching position or account-state update or [Scoped Recovery](https://siebly.io/reference/glossary#scoped-recovery).
- Private stream open or subscription event: update transport readiness only. Account State readiness still needs hydration, replay, and private account-state evidence.
- Active DCA order for the current step: hold dependent DCA work. An active DCA order is not permission to place the next DCA step.

### 4. Required checks

Required checks use this compact behavior set. After implementation, run the complete [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) set from the [conformance pack](https://siebly.io/reference/glossary#conformance-pack) before enabling [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE order paths. [conformance packs](https://siebly.io/reference/glossary#conformance-pack) are the machine-readable fixture sources for these checks.

- startup_hydrated_position_queues_work_before_service_ready: REST-hydrated open positions queue work before service readiness.
- private_event_records_scope_and_schedules_reconcile: Private event ingestion leads to scoped workflow scheduling.
- private_event_burst_waits_for_related_events: Account State ingestion is immediate while workflow execution briefly waits for related events in the same burst.
- custom_order_id_registry_routes_exchange_echoes: Exchange-visible custom IDs are lookup keys into one order-context store.
- pending_confirmation_does_not_unlock_dependent_action_family: Accepted mutation responses are provisional and cannot unlock dependent action families.
- context_write_failure_blocks_submission: A failed durable order-context write must block exchange submission.
- private_confirmation_before_rest_accept_is_consumed: A private confirmation can arrive before the REST submit promise resolves.
- side_flip_cleans_old_side_before_new_side_work: A one-way side flip cleans old-side app-owned orders before new-side protection or DCA.
- pending_place_blocks_duplicate_place: A pending place confirmation blocks another place for the same slot.
- pending_cancel_blocks_duplicate_cancel: A pending cancel confirmation blocks another cancel for the same target.
- decimal_and_default_equivalent_active_order_does_not_replace: Equivalent active orders do not churn because of display precision or hydrated defaults.
- terminal_event_during_cancel_or_amend_is_benign_race: Terminal private evidence can make later missing-target cancel/amend errors benign.
- reconnect_queues_known_scopes_for_recovery_even_when_quiet: Reconnect schedules recovery even without a later private event.
- slot_filter_failures_are_blocked_not_silent_or_retried: Exchange filters and local sizing gates produce explicit blocks.
- flat_position_cleans_app_owned_orders: A flat position cleans remaining managed orders.

### 5. Exchange overlay

Exchange-state lifecycle behavior stays reusable. Exchange pages add venue-specific names, request shapes, topics, and rejection handling.

- Binance overlay covers newClientOrderId, clientAlgoId, SDK ID utilities, regular TP order shape, Algo SL order shape, and Binance rejection codes.
- Bybit overlay covers orderLinkId, positionIdx, V5 private topics, retCode behavior, durable context defaults, and close-all SL request shapes.
- Shared behavior belongs in the exchange-state manifest, runtime kit, integration kit, and [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture).

### 6. Fallback sources

Use general SDK docs and examples only after task-specific artifacts establish the runtime contract.

- Use the manifest as the first executable artifact.
- Use this spec for workflow review.
- Use SDK docs, endpoint maps, repository examples, SDK catalog, and llms-full only for unresolved method or request-shape details.

## Runtime sequence

Module names can vary. These transitions should remain visible and testable.

- Startup hydration loads filters, positions or inputs for local position tracking, open orders, fills or executions, wallet or margin state, account mode, risk/readiness state, and stored contexts.
- Private stream readiness is established and buffered private events replay into [Account State](https://siebly.io/reference/glossary#accountstate).
- Service readiness opens only after hydration, replay, and configuration gates pass.
- A private event updates [Account State](https://siebly.io/reference/glossary#accountstate) immediately.
- The affected product/symbol/side is recorded as the [affected scope](https://siebly.io/reference/glossary#affected-scope).
- A short [event-burst wait](https://siebly.io/reference/glossary#event-burst-wait) gives related order, execution, position, and wallet events time to arrive.
- One [workflow owner](https://siebly.io/reference/glossary#workflow-owner) drains one affected scope.
- The planner chooses one [action family](https://siebly.io/reference/glossary#action-family).
- The submitter sends only the mutations approved by that pass after final gates pass.
- Accepted mutations become [pending confirmations](https://siebly.io/reference/glossary#pending-confirmation).
- [Private Stream Confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) updates [Account State](https://siebly.io/reference/glossary#accountstate), or [Scoped Recovery](https://siebly.io/reference/glossary#scoped-recovery) resolves unknown outcomes.
- Follow-up scopes are requeued only when trusted state changed.

## Minimal system

Build this before optional strategy controls.

- Use [Account State](https://siebly.io/reference/glossary#accountstate) or the project-local account cache as the only planning state.
- After readiness, private events update [Account State](https://siebly.io/reference/glossary#accountstate) as the normal state path.
- Use REST state fetches only at trust boundaries: startup, restart, reconnect or gap, missing prerequisites, unknown outcome, timeout, conflict, or explicit recovery.
- Order and fill updates trigger reconciliation, but dependent replacement planning waits for matching position or account-state evidence or [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery).
- When the exchange does not provide position rows, derive local [position](https://siebly.io/reference/glossary#position) state from fills, fees, and balance/account events before managed exits or exposure changes.
- DCA is a configured exposure-increasing order unless another execution style is explicitly selected. TP and SL are protective managed slots.

## Files to create first

These files preserve the prompt, plan, and runtime lifecycle before exchange calls are implemented.

- docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard)
- docs/AI_PROMPT_MANIFEST.json
- docs/PLAN.md
- docs/WORKFLOW_STATE_MACHINE.md
- docs/PRIVATE_EVENT_ROUTING_TABLE.md
- docs/CONFIRMATION_LIFECYCLE.md
- docs/DURABLE_CONTEXT_LIFECYCLE.md
- .env.example

## Runtime modules

Create these local boundaries before exchange-specific request builders. Use the runtime kit for full interfaces.

- OrderContextStore: customOrderId -> order context. Register context before submit, persist when configured, prune against trusted active orders, and never recover slot meaning by parsing custom IDs.
- AccountState: subject trust for position state, active orders, fills, balances, filters, contexts, readiness, and sync/recovery flags. Apply startup/recovery REST snapshots and private events into one account view. REST submit acceptance is coordination evidence only. Track order trust separately from position trust, filter trust, context trust, and readiness trust.
- PrivateEventRouter: event classification, accountstate ingestion, affected-scope recording, and pending-confirmation matches. Ingest private rows immediately, route known custom IDs through OrderContextStore, use bounded fallback scopes for ambiguous rows, and keep wallet-only events out of broad DCA/TP/SL planning unless configured.
- AffectedScopeQueue: deduped product/symbol/side work items. Canonicalize scope keys, dedupe repeats, preserve bounded follow-up reasons, and drain through one workflow owner.
- EventBurstReconciler: short-delay reconciliation for private event bursts. Apply events to AccountState immediately, record the exact product/symbol/side that changed, wait briefly so related events in the same burst can arrive, then run one reconciliation pass from the settled account state with a bounded max delay.
- ConfirmationTracker: pending place/amend/cancel confirmations and in-flight custom IDs. REST acceptance creates pending coordination state. Trusted private state or scoped recovery clears it. Timeout enters scoped recovery.
- RecoveryHydrator: scoped REST hydration for untrusted subjects. When recoveryRequired or sync-required state is set, hydrate positions, open orders, fills/executions, balances/readiness, replay buffered events, clear recovery on success, and requeue affected scopes.
- WorkflowOwner: single active reconciliation/planning/submission pass. Drain one affected scope at a time. If already active, record follow-up work and let the owner schedule one deferred pass.
- Planner: desired managed slots and one selected action family. Plan from trusted AccountState subjects. Products with exchange-provided position rows wait for matching position or account-state trust after order/fill events; products without exchange-provided position rows require trusted local position state. 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.
- SubmissionExecutor: preflight, context registration, exchange call dispatch, and provisional mutation records. Pre-register contexts, preflight filters, risk geometry, and duplicate IDs, dispatch fresh SL/TP concurrently by default, and never unlock dependent action families from REST acceptance alone.
- ExchangeErrorClassifier: deterministic block, benign race, retry/backoff, and scoped recovery decisions. Classify by action, role, exchange code, current trusted state, and proof. Unknown mutation status enters scoped recovery.
- StructuredLogger: redacted lifecycle, planner, submission, recovery, and shutdown logs. Emit semantic counters and reasons without raw private payloads, secrets, signatures, listen keys, or raw [order intents](https://siebly.io/reference/glossary#order-intent).

## Exchange implementations

Use exchange implementation pages for SDK clients, request fields, private topics, product terms, rejection codes, and venue-specific fixtures.

- Binance implementation guide: [Position Management with Binance APIs & WebSockets](/ai/exchange-state/binance).
- Binance recipe and fixtures: /.well-known/recipes/binance-position-manager.json, /.well-known/integration-kits/binance-position-manager/latest.json, /.well-known/conformance/binance-position-manager/latest.json.
- Bybit implementation guide: [Position Management with Bybit APIs & WebSockets](/ai/exchange-state/bybit).
- Bybit recipe and fixtures: /.well-known/recipes/bybit-position-manager.json, /.well-known/integration-kits/bybit-position-manager/latest.json, /.well-known/conformance/bybit-position-manager/latest.json.

## Invariants

- Default behavior is read-only hydration and [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE [order intents](https://siebly.io/reference/glossary#order-intent).
- A private exchange-state manager is a long-running service, not a run-once order placer.
- No exchange write path can run before [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE is explicitly selected and every configured gate allows it.
- 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.
- Symbol scope, subject trust, position trust, and TP/DCA/SL geometry follow the shared exchange-state rules before any exchange write.
- No unowned manual order is cancelled or amended by default.
- Generated managers use [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) plus an order-context registry and deterministic internal SlotKey/context by default.
- Use REST state fetches only at trust boundaries: startup, restart, reconnect or gap, missing prerequisites, unknown outcome, timeout, conflict, or explicit recovery.
- 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.
- The order workflow is ws_symbol_side_action_gated; affected work items are symbol-side scoped. 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.
- Desired-vs-active comparison normalizes exchange-hydrated defaults by order kind before suppressing replacement; raw field-by-field object equality is forbidden. When an accountstate or exchange-overlay comparison helper is available, compare NormalizedOrder-to-NormalizedOrder: convert desired slot/request objects into the accountstate NormalizedOrder shape first, mapping local managedSide/managedStrategySide to strategySide, then compare them with active normalized orders. Do not pass strategy-local DesiredManagedOrder/request objects directly or hand-roll raw exchange-object equality.
- Same-slot amendable changes are amended first instead of cancel/placed by default.
- Workflow-active events record bounded follow-up reasons and cannot start recursive replans.
- Protective exits are pre-registered, dispatched concurrently by default, and confirmed before exposure-increasing DCA for a new managed position.
- DCA risk-limit failures do not pause or churn protective TP/SL management.
- Reconnect, restart, rejection, and unknown submission paths enter recoveryRequired or syncRequired and reconcile before new exposure resumes.
- Advanced lifecycle/generation recovery is opt-in persistent strategy behavior, not the simple prompt-generated default.

## Prompt

```markdown
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.
- Do not store state in the custom order ID field. Keep strategy/system state locally instead. Use [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as a randomised lookup key for that local state.
- 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.
```
