{
  "format": "siebly-agent-implementation-manifest/v1",
  "id": "binance-position-manager",
  "title": "Binance Position Management Agent Manifest",
  "task": "binance-position-manager",
  "version": 1,
  "lastReviewed": "2026-05-12",
  "purpose": "Implementation manifest for coding agents building a Binance Spot plus USD-M position manager.",
  "canonicalArtifacts": {
    "manifest": "https://siebly.io/.well-known/agent-manifests/binance-position-manager/latest.json",
    "coreManifest": "https://siebly.io/.well-known/agent-manifests/exchange-state-management/latest.json",
    "coreRuntimeKit": "https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/index.json",
    "coreRuntimeTypes": "https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/types.ts",
    "coreIntegrationKit": "https://siebly.io/.well-known/integration-kits/exchange-state-management/latest.json",
    "coreConformancePack": "https://siebly.io/.well-known/conformance/exchange-state-management/latest.json",
    "coreConformanceSchema": "https://siebly.io/.well-known/conformance/exchange-state-management/v1/schema.json",
    "coreConformanceFixtures": "https://siebly.io/.well-known/conformance/exchange-state-management/v1/fixtures.json",
    "coreConformanceRunner": "https://siebly.io/.well-known/conformance/exchange-state-management/v1/runner.ts",
    "specGuide": "https://siebly.io/ai/exchange-state",
    "integrationKit": "https://siebly.io/.well-known/integration-kits/binance-position-manager/latest.json",
    "conformancePack": "https://siebly.io/.well-known/conformance/binance-position-manager/latest.json",
    "guide": "https://siebly.io/ai/exchange-state/binance",
    "recipe": "https://siebly.io/.well-known/recipes/binance-position-manager.json",
    "usdmAlgoGuide": "https://siebly.io/ai/algo-orders/binance",
    "usdmAlgoRecipe": "https://siebly.io/.well-known/recipes/binance-usdm-algo-orders.json",
    "artifactOrder": [
      "https://siebly.io/ai/exchange-state",
      "https://siebly.io/.well-known/prompts/binance-position-manager/latest.md",
      "https://siebly.io/.well-known/recipes/binance-position-manager.json",
      "https://siebly.io/ai/exchange-state/binance",
      "https://siebly.io/.well-known/integration-kits/binance-position-manager/latest.json",
      "https://siebly.io/ai/algo-orders/binance",
      "https://siebly.io/.well-known/recipes/binance-usdm-algo-orders.json",
      "https://siebly.io/.well-known/agent-manifests/binance-position-manager/latest.json",
      "https://siebly.io/.well-known/agent-manifests/exchange-state-management/latest.json",
      "https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/index.json",
      "https://siebly.io/.well-known/runtime-kits/exchange-state-management/v1/types.ts",
      "https://siebly.io/.well-known/integration-kits/exchange-state-management/latest.json",
      "https://siebly.io/.well-known/conformance/exchange-state-management/latest.json",
      "https://siebly.io/.well-known/conformance/exchange-state-management/v1/schema.json",
      "https://siebly.io/.well-known/conformance/exchange-state-management/v1/fixtures.json",
      "https://siebly.io/.well-known/conformance/exchange-state-management/v1/runner.ts",
      "https://siebly.io/.well-known/conformance/binance-position-manager/latest.json"
    ],
    "fallbackSources": [
      "https://siebly.io/sdk/binance/javascript",
      "https://siebly.io/llms-tasks.txt",
      "https://siebly.io/.well-known/siebly-sdk-catalog.json",
      "https://github.com/tiagosiebler/binance",
      "https://github.com/sieblyio/crypto-api-examples/tree/master/examples/Binance"
    ]
  },
  "primarySpec": {
    "id": "exchange-state-management-spec",
    "title": "Exchange State Management",
    "href": "https://siebly.io/ai/exchange-state",
    "purpose": "Exchange-neutral runtime spec for private account, order, and position state workflows, including DCA/TP/SL managers.",
    "architecture": {
      "reusable": "order_account_position_state_machine",
      "lane": "ws_symbol_side_action_gated"
    },
    "role": "Primary implementation spec. Other artifacts support, specialize, or test this workflow; they do not replace it."
  },
  "authorityOrder": [
    "When this manifest is explicitly selected, use it as an advanced reusable-runtime checklist; the default build path remains the primary spec and selected exchange recipe.",
    "Use the exchange-state runtime kit for reusable module contracts when needed; it is not a required first read for simple implementations.",
    "Use Exchange State Management Integration Kit and Binance Position Management Integration Kit for runtime rules, field matrices, event policy, redaction, and logs.",
    "Use Exchange State Management Conformance Pack and Binance Position Management Conformance Pack as post-implementation validation sources. After implementation, generate or run local [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) from Exchange State Management Conformance Pack and Binance Position Management Conformance Pack before enabling EXECUTION_MODE=DEMO, TESTNET, or LIVE submission.",
    "Use the recipe and guide for the default build path and explanatory context.",
    "Use installed binance package declarations and current Binance API docs as the final authority for exact request shapes."
  ],
  "package": {
    "ecosystem": "npm",
    "name": "binance",
    "install": "npm install binance",
    "versionPolicy": "Use the latest available binance package in the generated project. Record the installed version in the README dependency notes; installed declarations and current docs are the authority for exact request shapes.",
    "docs": "https://siebly.io/sdk/binance/javascript",
    "repository": "https://github.com/tiagosiebler/binance"
  },
  "requiredFirstSteps": [
    "Save docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and docs/AI_PROMPT_MANIFEST.json before implementation.",
    "Install the latest available dependencies and record the installed binance package version as SDK surface metadata.",
    "Run or create the local SDK surface script below.",
    "Write README SDK surface notes with exact methods, types, files, and package version checked.",
    "If using this manifest, generate a short implementation checklist from it and the integration kit before editing exchange code.",
    "Implement EXECUTION_MODE=DRY_RUN_PRIVATE planning first. After implementation, run applicable [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) before enabling EXECUTION_MODE=DEMO, TESTNET, or LIVE submission. [conformance packs](https://siebly.io/reference/glossary#conformance-pack) are the machine-readable fixture sources for these checks."
  ],
  "spec": [
    "Install the latest available SDK and verify exact method/type names from installed declarations.",
    "Build a formatted private-event field-path matrix for ORDER_TRADE_UPDATE, ALGO_UPDATE, TRADE_LITE, and ACCOUNT_UPDATE from installed declarations before private event routing.",
    "Store the exact generated prompt and a machine-readable prompt manifest before implementation so future audits can compare implementation behavior with the original instructions.",
    "Use the simple managed-slot lane unless the user explicitly asks for a persistent advanced strategy.",
    "Implement Binance [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as order-context lookup keys only.",
    "Hydrate filters, positions, regular open orders, open Algo orders, recent orders/fills, account mode, position mode, and leverage/notional constraints.",
    "Store hydrated filters; never plan EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE orders from fallback filters.",
    "On startup, reconnect, or recovery, cancel open app-owned managed orders before rebuilding slots from current positions.",
    "Fixed TP and DCA use regular LIMIT orders. A DCA LIMIT may fill immediately at limit-or-better or rest at the submitted limit price; both are normal LIMIT behavior. Do not add maker-only, post-only, mark-price, quote-freshness, marketability, or forced-maker gates unless explicitly configured.",
    "Use Algo STOP_MARKET close-position orders for SL where supported by the selected product.",
    "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.",
    "Implement slot convergence normalizers, including regular TP/DCA LIMIT field matching and USD-M Algo close-position SL default echo handling.",
    "Implement one workflow owner with symbol-side affected work items. 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.",
    "Implement private user-data supervision: typed classification, buffering, short event-burst waiting, and immediate recovery precedence for reconnect/exception/rejection events.",
    "Pre-register order context and preflight each DEMO, TESTNET, or LIVE intent before its exchange request; do not let duplicate-place guards block cleanup cancels. Fresh protective SL/TP may dispatch as concurrent separate orders by default.",
    "Treat Binance -2027 as DCA risk-limited/cooldown while protective TP/SL management continues.",
    "After implementation, run the applicable [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) from the [Conformance Pack](https://siebly.io/reference/glossary#conformance-pack) before enabling EXECUTION_MODE=DEMO, TESTNET, or LIVE order submission. [conformance packs](https://siebly.io/reference/glossary#conformance-pack) are the machine-readable fixture sources for these checks."
  ],
  "criticalWriteConformance": {
    "conformancePack": "https://siebly.io/.well-known/conformance/binance-position-manager/latest.json",
    "mustPassBeforeLive": [
      "startup_wipe_rebuild_cancels_app_orders_before_rebuild",
      "position_open_reacts_without_timer",
      "position_open_places_protective_then_dca_after_ws_confirmation",
      "accepted_submissions_settle_to_zero_intents",
      "fixed_tp_uses_regular_limit",
      "sl_is_algo_stop_market_close_position",
      "one_way_tp_sends_reduce_only_regular_limit",
      "hedge_regular_tp_omits_reduce_only_but_ignores_hydrated_echo",
      "usdm_algo_close_position_hydration_defaults",
      "client_id_change_alone_does_not_replace_order",
      "only_changed_slot_replaced",
      "same_side_position_add_classifies_slots_once",
      "healthy_user_data_reconcile_skips_rest_backfill",
      "semantic_ws_logs_emitted_after_ingest",
      "symbol_side_queue_groups_private_event_burst",
      "private_stream_event_during_active_workflow_defers_followup",
      "pending_confirmation_does_not_unlock_dependent_action_family",
      "pending_confirmations_do_not_trigger_replacement",
      "pending_place_guard_does_not_block_cancel",
      "custom_order_id_registry_lookup_routes_private_event",
      "binance_formatted_order_trade_update_uses_order_client_order_id",
      "binance_formatted_algo_update_uses_algo_order_client_algo_id",
      "binance_formatted_trade_lite_routes_by_registry_or_broad_scope",
      "binance_formatted_account_update_position_rows_create_position_trust",
      "binance_formatted_event_missing_required_path_enters_recovery",
      "binance_terminal_private_proof_makes_2011_cancel_benign",
      "protective_sl_tp_pre_registered_and_dispatched_concurrently_by_default",
      "unknown_submit_outcome_enters_recovery_after_configured_timeout",
      "recovery_required_blocks_normal_actions_until_hydration_succeeds",
      "duplicate_client_id_4116_enters_recovery_without_pause",
      "amend_no_need_to_change_treated_converged_when_current_slot_equivalent",
      "max_leverage_4509_blocks_dca_only",
      "account_sync_required_triggers_scoped_rest_hydration",
      "recoverable_immediate_trigger_does_not_crash_service",
      "close_position_conflict_replans_after_cancel_settle",
      "dca_2027_blocks_dca_only",
      "dca_2019_blocks_dca_only",
      "regular_tp_dca_5029_filter_block_is_role_specific",
      "live_submission_exception_clears_inflight",
      "unknown_order_cancel_absent_from_hydration_marks_terminal",
      "private_stream_exception_fails_startup",
      "live_marker_required_before_live_start",
      "hedge_same_symbol_opposite_side_coexists",
      "position_full_close_cleans_app_orders",
      "binary_float_tails_are_formatted_from_filters",
      "websocket_beautify_required_for_formatted_user_data",
      "rest_beautify_disabled_for_accountstate_inputs",
      "custom_oid_guard_preflights_before_submit",
      "cancel_before_place_replacement_converges_before_place",
      "deferred_replan_reentrant_calls_are_grouped",
      "full_close_cleanup_clears_slot_state_after_cleanup_settles",
      "binary_float_precision_tails_are_formatted",
      "fallback_filters_block_live_planning"
    ],
    "recoveryState": {
      "recoveryRequired": true,
      "operatorPaused": false,
      "blocksNewExposure": true,
      "blocksNormalPhasesUntilHydrated": true,
      "requiresScopedHydration": true,
      "clearsBy": [
        "scoped_rest_hydration",
        "buffered_user_data_replay",
        "coherent_accountstate_read"
      ]
    },
    "activeRiskNotes": [
      "Use the simple managed-slot lane for Binance: SDK-prefixed [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) plus runtime order-context registry, recovery hydrate/rebuild, stream-first live state, regular fixed TP, and Algo SL.",
      "Use the fixed ws_symbol_side_action_gated architecture. Do not broaden it into a product-wide field-by-field reconciler.",
      "Keep Binance cancel-before-place guidance scoped to Binance close-position or conditional conflicts. Do not copy it into exchange-neutral or Bybit same-slot update rules.",
      "Do not use \"replace\" as shorthand for cancel/place. Classify each app-owned slot as keep, amend, cancel_place, cancel, or place, then apply Binance-specific cancel-before-place only where required.",
      "Do not recover lifecycle epoch, replacement generation, role, step, side, or order kind from Binance client IDs for the default manager; use IDs only as context lookup keys.",
      "Fixed TP and DCA use regular LIMIT orders. A DCA LIMIT may fill immediately at limit-or-better or rest at the submitted limit price; both are normal LIMIT behavior. Do not add maker-only, post-only, mark-price, quote-freshness, marketability, or forced-maker gates unless explicitly configured. Use the Algo path only for SL, trailing stop, or explicitly configured conditional TP behavior.",
      "Do not turn sync_required, rejected submission, or unknown state into a permanent operator pause. Use recoveryRequired or syncRequired, block normal action families until scoped hydration restores trusted state, then requeue and replan.",
      "Use scoped REST hydration for startup, restart, reconnect, stream exception or gap, missing prerequisites such as filters, unknown submit/cancel/amend outcomes, timeouts, sync-required or not-ready state, conflicting evidence, and explicit recovery. It is not the ordinary response to every healthy private event or ordinary pending confirmation."
    ],
    "mustLogFields": [
      "event",
      "product",
      "intentCount",
      "blockedCount",
      "activeOrders",
      "positions",
      "bufferedEventCount",
      "readiness"
    ],
    "mustNeverLogRawFields": [
      "apiKey",
      "apiSecret",
      "signature",
      "listenKey",
      "wsKey",
      "signedUrl",
      "rawOrderIntent"
    ]
  },
  "subjectTrust": {
    "subjects": [
      "order trust",
      "position trust",
      "filter trust",
      "context trust",
      "readiness trust"
    ],
    "rules": [
      "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."
    ]
  },
  "symbolScope": [
    "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."
  ],
  "riskGeometry": [
    "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."
  ],
  "identityChainReview": {
    "cleanPassesRequired": 3,
    "chain": [
      "config scope",
      "product/environment/account",
      "symbol",
      "position mode",
      "managed side",
      "exchange position identity",
      "accountstate position state (native or locally derived)",
      "planner scope",
      "slot scope",
      "custom order ID",
      "durable context",
      "exchange request",
      "REST acceptance",
      "private order/execution/position event",
      "trusted active order",
      "subject trust state",
      "confirmation tracker",
      "recovery scope",
      "cleanup/protective/DCA replanning"
    ],
    "requiredRule": "Do not mark the implementation complete until three consecutive full identity-chain review passes produce no code, tests, fixtures, or documentation changes.",
    "passMustTrace": "Trace mismatched, stale, missing, contradictory, duplicated, late, recovered, and flat identities across every runtime boundary."
  },
  "promptProvenance": {
    "files": [
      "docs/AI_PROMPT.md",
      "docs/AI_PROMPT_MANIFEST.json"
    ],
    "manifestRequiredFields": [
      "createdFrom",
      "generatedAt",
      "exchange",
      "products",
      "selectedFeatures",
      "permissionBoundary",
      "linkedArtifacts",
      "installedPackages",
      "liveGateNames",
      "criticalFixtureNames"
    ],
    "rule": "Commit the exact prompt text and selected prompt options before implementation so prompt coverage can be compared with implementation behavior."
  },
  "sdkSurfaceCheckScript": {
    "filename": "scripts/verify-binance-position-manager-surfaces.mjs",
    "command": "node scripts/verify-binance-position-manager-surfaces.mjs",
    "scriptLines": [
      "import fs from 'node:fs';",
      "import path from 'node:path';",
      "import { createRequire } from 'node:module';",
      "",
      "const require = createRequire(import.meta.url);",
      "const packageJsonPath = require.resolve('binance/package.json');",
      "const packageRoot = path.dirname(packageJsonPath);",
      "const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));",
      "const sdk = await import('binance');",
      "",
      "const requiredExports = [",
      "  'MainClient',",
      "  'USDMClient',",
      "  'WebsocketClient',",
      "  'generateNewOrderId',",
      "  'getOrderIdPrefix',",
      "];",
      "",
      "const missingExports = requiredExports.filter((name) => !(name in sdk));",
      "const declarationTargets = [",
      "  'RestClientOptions',",
      "  'WSClientConfigurableOptions.beautify',",
      "  'RestClientOptions.beautifyResponses',",
      "  'FuturesNewOrderParams',",
      "  'FuturesNewAlgoOrderParams',",
      "  'FuturesAlgoConditionalOrderTypes',",
      "  'FuturesAlgoOrderResponse',",
      "  'formattedUserDataMessage',",
      "  'WsMessageFuturesUserDataAccountUpdateFormatted.updateData.updatedPositions',",
      "  'WsMessageFuturesUserDataTradeUpdateEventFormatted.order.clientOrderId',",
      "  'WsMessageFuturesUserDataTradeLiteEventFormatted.clientOrderId',",
      "  'WsMessageFuturesUserDataAlgoUpdateFormatted.algoOrder.clientAlgoId',",
      "  'isWsFormattedFuturesUserDataAccountUpdate',",
      "  'isWsFormattedFuturesUserDataTradeUpdateEvent',",
      "  'isWsFormattedFuturesAlgoUpdateEvent',",
      "  'BEAUTIFIER_EVENT_MAP ACCOUNT_UPDATEEvent ORDER_TRADE_UPDATEEvent TRADE_LITEEvent ALGO_UPDATEEvent',",
      "  'subscribeSpotUserDataStream',",
      "  'subscribeUsdFuturesUserDataStream',",
      "  'closeAll',",
      "];",
      "",
      "const report = {",
      "  package: 'binance',",
      "  installedVersion: packageJson.version,",
      "  packageRoot,",
      "  ok: missingExports.length === 0,",
      "  exports: Object.fromEntries(requiredExports.map((name) => [name, name in sdk])),",
      "  missingExports,",
      "  declarationTargetsToInspect: declarationTargets,",
      "  formattedPrivateEventFieldMatrix: {",
      "    ORDER_TRADE_UPDATE: ['order.clientOrderId', 'order.symbol', 'order.positionSide', 'order.executionType', 'order.orderStatus'],",
      "    ALGO_UPDATE: ['algoOrder.clientAlgoId', 'algoOrder.symbol', 'algoOrder.positionSide', 'algoOrder.orderType', 'algoOrder.algoStatus'],",
      "    TRADE_LITE: ['clientOrderId', 'symbol', 'side', 'lastFilledPrice', 'lastFilledQuantity'],",
      "    ACCOUNT_UPDATE: ['updateData.updatedPositions[].symbol', 'updateData.updatedPositions[].positionSide', 'updateData.updatedPositions[].positionAmount', 'updateData.updatedPositions[].entryPrice'],",
      "  },",
      "  nextStep:",
      "    'Open installed package declarations and confirm REST raw/beautify options, WebSocket beautify=true for formatted private events, USD-M regular and Algo literals, formatted private event field paths, WebSocket event names, closeAll signature, and optional-field behavior before coding.',",
      "};",
      "",
      "console.log(JSON.stringify(report, null, 2));",
      "if (!report.ok) process.exit(1);"
    ],
    "expectedReportShape": {
      "package": "binance",
      "installedVersion": "string",
      "ok": "boolean",
      "exports": "MainClient, USDMClient, WebsocketClient, generateNewOrderId, and getOrderIdPrefix booleans",
      "declarationTargetsToInspect": "RestClientOptions, FuturesNewOrderParams, FuturesNewAlgoOrderParams, FuturesAlgoConditionalOrderTypes, FuturesAlgoOrderResponse, formatted user-data field paths, user-data helpers and events, closeAll"
    },
    "requiredFollowUp": "After the script runs, manually inspect installed declarations for method signatures, valid USD-M Algo type literals, closeAll(force?) shape, optional-field handling, and formatted user-data event field paths."
  },
  "mustVerifyInstalledSdk": {
    "clients": [
      "MainClient",
      "USDMClient",
      "WebsocketClient"
    ],
    "restOptions": [
      "strictParamValidation",
      "filterUndefinedParams",
      "beautifyResponses"
    ],
    "idUtilities": [
      "getOrderIdPrefix",
      "generateNewOrderId"
    ],
    "privateStreamHelpers": [
      "subscribeSpotUserDataStream",
      "subscribeUsdFuturesUserDataStream"
    ],
    "privateEvents": [
      "formattedUserDataMessage",
      "formattedMessage",
      "ORDER_TRADE_UPDATE order.clientOrderId",
      "ALGO_UPDATE algoOrder.clientAlgoId",
      "TRADE_LITE clientOrderId",
      "ACCOUNT_UPDATE updateData.updatedPositions",
      "reconnecting",
      "reconnected",
      "exception",
      "closeAll"
    ],
    "spotMethods": [
      "getExchangeInfo",
      "getAccountInformation",
      "getOpenOrders",
      "getAllOrders",
      "getAccountTradeList",
      "submitNewOrder",
      "cancelOrder",
      "testNewOrder"
    ],
    "usdmMethods": [
      "getExchangeInfo",
      "getPositionsV3",
      "getAllOpenOrders",
      "getOpenAlgoOrders",
      "getAccountTrades",
      "getAllOrders",
      "getAccountInformationV3",
      "getCurrentPositionMode",
      "getMultiAssetsMode",
      "getFuturesSymbolConfig",
      "getNotionalAndLeverageBrackets",
      "submitNewOrder",
      "cancelOrder",
      "testOrder",
      "submitNewAlgoOrder",
      "cancelAlgoOrder"
    ],
    "declarationTargets": [
      "RestClientOptions",
      "NewSpotOrderParams",
      "FuturesNewOrderParams",
      "FuturesNewAlgoOrderParams",
      "FuturesAlgoConditionalOrderTypes",
      "FuturesAlgoOrderResponse",
      "WsMessageFuturesUserDataAlgoUpdateFormatted",
      "WsMessageFuturesUserDataAccountUpdateFormatted",
      "WsMessageFuturesUserDataTradeUpdateEventFormatted",
      "WsMessageFuturesUserDataTradeLiteEventFormatted",
      "WsUserDataEvents"
    ]
  },
  "requestBuilders": {
    "spotRegularManagedOrder": {
      "clientIdField": "newClientOrderId",
      "requiredFields": [
        "symbol",
        "side",
        "type",
        "quantity"
      ],
      "optionalOmitWhenUndefined": [
        "price",
        "timeInForce"
      ],
      "notes": [
        "Use Spot filters from hydrated exchangeInfo before formatting quantities/prices."
      ]
    },
    "usdmRegularDca": {
      "clientIdField": "newClientOrderId",
      "requiredFields": [
        "symbol",
        "side",
        "type",
        "quantity",
        "price",
        "timeInForce"
      ],
      "optionalOmitWhenUndefined": [
        "positionSide",
        "reduceOnly"
      ],
      "notes": [
        "Use regular submitNewOrder for exposure-increasing DCA.",
        "For one-way shorts, outbound positionSide remains BOTH while side is SELL above entry."
      ]
    },
    "usdmFixedTakeProfit": {
      "clientIdField": "newClientOrderId",
      "validType": "LIMIT",
      "method": "submitNewOrder",
      "requiredFields": [
        "symbol",
        "side",
        "positionSide",
        "type",
        "quantity",
        "price",
        "timeInForce"
      ],
      "forbiddenFields": [
        "clientAlgoId",
        "triggerPrice",
        "closePosition",
        "workingType",
        "priceProtect"
      ],
      "optionalOmitWhenUndefined": [
        "reduceOnly"
      ],
      "notes": [
        "This is the default fixed TP slot because fixed TP uses regular LIMIT order semantics.",
        "Use reduceOnly only where current Binance docs/package types allow it for the account mode."
      ]
    },
    "usdmExplicitConditionalTakeProfit": {
      "clientIdField": "clientAlgoId",
      "validType": "TAKE_PROFIT",
      "method": "submitNewAlgoOrder",
      "useOnlyWhen": "The user explicitly requests conditional TP behavior instead of regular LIMIT fixed TP.",
      "requiredFields": [
        "symbol",
        "side",
        "positionSide",
        "type",
        "quantity",
        "price",
        "triggerPrice",
        "timeInForce",
        "clientAlgoId"
      ],
      "forbiddenFields": [
        "type=TAKE_PROFIT_LIMIT"
      ],
      "optionalOmitWhenUndefined": [
        "reduceOnly",
        "workingType",
        "priceProtect"
      ]
    },
    "usdmAlgoClosePositionStop": {
      "clientIdField": "clientAlgoId",
      "validType": "STOP_MARKET",
      "requiredFields": [
        "symbol",
        "side",
        "positionSide",
        "type",
        "triggerPrice",
        "closePosition",
        "clientAlgoId"
      ],
      "forbiddenFields": [
        "quantity",
        "reduceOnly"
      ],
      "notes": [
        "closePosition=true stop-market exits omit quantity and reduceOnly unless current docs and package types explicitly change.",
        "In hedge mode with positionSide LONG or SHORT, omit reduceOnly for Algo SL or explicit conditional TP."
      ]
    }
  },
  "regularVersusAlgoDecisionTree": [
    "DCA limit add -> regular submitNewOrder with newClientOrderId.",
    "USD-M fixed take-profit -> regular submitNewOrder LIMIT with newClientOrderId.",
    "USD-M explicit conditional take-profit -> Algo submitNewAlgoOrder with type=TAKE_PROFIT and clientAlgoId only when the user requested conditional TP.",
    "USD-M close-all stop-loss -> Algo submitNewAlgoOrder with type=STOP_MARKET, closePosition=true, clientAlgoId, no quantity, no reduceOnly.",
    "Hedge-mode Algo SL or explicit conditional TP -> omit reduceOnly for positionSide LONG or SHORT.",
    "Current open Algo state -> hydrate with getOpenAlgoOrders separately from regular open orders.",
    "Algo cancel -> cancelAlgoOrder, and stale -2011 stops retrying when open-Algo hydration proves absence."
  ],
  "replacementPhasing": [
    "If a plan contains app-owned cancels and placements for the same symbol-side workflow, submit the cleanup action first.",
    "Record accepted cancels as pending coordination state, not trusted open-order state. Treat -2011 Unknown order as terminal and benign only when private terminal proof exists or current REST open-order/open-Algo hydration proves the app-owned order is absent.",
    "In healthy private-stream mode, wait for private user-data confirmation and replan from stream-fed accountstate before placing replacement slots.",
    "Use REST hydration between cancel and place only for startup, reconnect, sync-required, exception, rejected/unknown, or conflicting-state recovery.",
    "Only submit placement intents after the old app-owned orders are gone, stale, or otherwise terminal in trusted local state.",
    "Do not place a new close-position SL in the same reconciliation pass as a cancel for the old close-position SL; Binance can reject it while the old conditional is still visible."
  ],
  "syncRecovery": [
    "If the project-local state layer reports readyToTrade=false, sync_required, or outstanding syncRequests for positions, openOrders, openAlgoOrders, balances, or fills, block planning and EXECUTION_MODE=DEMO, TESTNET, or LIVE submission.",
    "Satisfy the requested subjects with scoped REST hydration for the affected product and symbol instead of waiting for a reconnect-only path.",
    "Apply positions, regular open orders, open Algo orders, balances, and fills through the same adapter path used at startup so replacement-view semantics remain consistent.",
    "After sync recovery completes, schedule a normal product reconciliation pass rather than submitting from inside the recovery helper.",
    "Log account_sync_recovery_requested and account_sync_recovery_complete with requested subjects, hydrated counts, remaining requests, and readiness."
  ],
  "recoveryState": {
    "recoveryRequired": true,
    "operatorPaused": false,
    "blocksNewExposure": true,
    "blocksNormalPhasesUntilHydrated": true,
    "requiresScopedHydration": true,
    "clearsBy": [
      "scoped_rest_hydration",
      "buffered_user_data_replay",
      "coherent_accountstate_read"
    ]
  },
  "activeRiskNotes": [
    "Use the simple managed-slot lane for Binance: SDK-prefixed [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) plus runtime order-context registry, recovery hydrate/rebuild, stream-first live state, regular fixed TP, and Algo SL.",
    "Use the fixed ws_symbol_side_action_gated architecture. Do not broaden it into a product-wide field-by-field reconciler.",
    "Keep Binance cancel-before-place guidance scoped to Binance close-position or conditional conflicts. Do not copy it into exchange-neutral or Bybit same-slot update rules.",
    "Do not use \"replace\" as shorthand for cancel/place. Classify each app-owned slot as keep, amend, cancel_place, cancel, or place, then apply Binance-specific cancel-before-place only where required.",
    "Do not recover lifecycle epoch, replacement generation, role, step, side, or order kind from Binance client IDs for the default manager; use IDs only as context lookup keys.",
    "Fixed TP and DCA use regular LIMIT orders. A DCA LIMIT may fill immediately at limit-or-better or rest at the submitted limit price; both are normal LIMIT behavior. Do not add maker-only, post-only, mark-price, quote-freshness, marketability, or forced-maker gates unless explicitly configured. Use the Algo path only for SL, trailing stop, or explicitly configured conditional TP behavior.",
    "Do not turn sync_required, rejected submission, or unknown state into a permanent operator pause. Use recoveryRequired or syncRequired, block normal action families until scoped hydration restores trusted state, then requeue and replan.",
    "Use scoped REST hydration for startup, restart, reconnect, stream exception or gap, missing prerequisites such as filters, unknown submit/cancel/amend outcomes, timeouts, sync-required or not-ready state, conflicting evidence, and explicit recovery. It is not the ordinary response to every healthy private event or ordinary pending confirmation."
  ],
  "recoverableErrors": [
    {
      "code": "-2011",
      "name": "unknown_order_on_cancel",
      "action": "If private terminal proof already exists, or fresh REST open-order/open-Algo hydration does not contain the app-owned cancel target, treat the cancel as a benign stale-target race, mark it terminal/stale, clear in-flight state, log at info level, and do not retry forever."
    },
    {
      "code": "-2021",
      "name": "order_would_immediately_trigger",
      "action": "Treat as a recoverable placement skip for that intent, log trigger context, enter recoveryRequired or replan the affected product, and do not crash the long-running service."
    },
    {
      "code": "-4130",
      "name": "close_position_order_already_exists",
      "action": "Treat as a recoverable close-position conflict: stop the active placement action, cancel conflicting app-owned conditionals, then wait for private-stream convergence or scoped recovery hydration before replanning."
    },
    {
      "code": "-2027",
      "name": "max_position_or_leverage_limit",
      "action": "Treat as a DCA risk-limit outcome. Block or cool down the DCA slot only; keep protective TP/SL management active."
    },
    {
      "code": "-4116",
      "name": "duplicate_client_order_id",
      "action": "Treat as a pending-confirmation or conflicting-state signal, not proof of open order state. Stop the affected action family, keep duplicate-place protection active, and reconcile without product-wide pause."
    },
    {
      "code": "-5027",
      "name": "no_need_to_change",
      "action": "Apply to amend only. If current trusted accountstate still has the target slot and it is equivalent to desired, treat as converged/no-op. If accountstate does not show equivalence, run scoped recovery. Do not apply this to place or cancel."
    },
    {
      "code": "-4509",
      "name": "max_leverage_or_risk_limit",
      "action": "Treat as a DCA/risk-limit outcome when tied to exposure increase. Block or cool down DCA only and keep protective TP/SL management active."
    }
  ],
  "liveIntentPreflightRules": [
    "Filter blocked intents before EXECUTION_MODE=DEMO, TESTNET, or LIVE submission.",
    "Pre-register order context and preflight every remaining cancel, amend, and place intent before its exchange call.",
    "Block duplicate place requests while a pending confirmation exists for the same slot; do not block cleanup cancels for that same app-owned ID.",
    "Block duplicate custom IDs and in-flight custom IDs before submission.",
    "Normal exposure-increasing, replacement, and DCA work is confirmation-gated; fresh protective SL/TP may dispatch concurrently as separate orders by default after both contexts are registered.",
    "Every accepted place, amend, or cancel response creates a pending confirmation and sanitized accepted-submission log.",
    "Pending confirmations suppress duplicate submissions but do not unlock DCA or later replacement actions until private stream evidence or scoped recovery hydration confirms the outcome.",
    "Every accept, reject, and throw path clears the in-flight client ID in a finally-equivalent path.",
    "A -2011 cancel for an app-owned order with private terminal proof or absent from fresh open-order hydration is a benign stale-target race: log at info, mark the order terminal or stale, and do not leave its client ID stuck in flight."
  ],
  "privateStreamStartupReadinessRules": [
    "Attach exception, open, reconnecting, and reconnected handlers before subscribing.",
    "Do not treat subscribe helper completion as application readiness.",
    "For private streams, SDK exception is authoritative stream-health failure.",
    "After subscribing, inspect product readiness or a supervisor failure flag.",
    "Required live startup gate: stream requested, transport open, REST hydration complete, no required product has recoveryRequired from exception, buffered replay complete.",
    "Do not emit service_ready while any required private-stream product has recoveryRequired or syncRequired from SDK exception."
  ],
  "usdmAlgoClosePositionHydrationDefaults": {
    "name": "usdm_algo_close_position_hydration_defaults",
    "description": "An app-owned USD-M Algo close-position STOP_MARKET SL can hydrate with exchange defaults that should not churn replacement.",
    "desired": {
      "product": "usdm",
      "kind": "algo",
      "role": "SL",
      "type": "STOP_MARKET",
      "closePosition": true,
      "quantity": null,
      "price": null,
      "reduceOnly": null,
      "triggerPrice": "99000.0",
      "positionSide": "BOTH"
    },
    "hydratedVariants": [
      {
        "quantity": "0.0",
        "price": "0.0",
        "closePosition": "true",
        "reduceOnly": "false",
        "priceProtect": "true"
      },
      {
        "quantity": "0.01",
        "price": "0.0",
        "closePosition": false,
        "reduceOnly": true,
        "priceProtect": true
      },
      {
        "quantity": null,
        "price": null,
        "closePosition": null,
        "reduceOnly": null,
        "priceProtect": null
      }
    ],
    "equivalenceRule": "After matching product, symbol, exchangePositionSide, managedStrategySide, role, step, side, triggerPrice, workingType, closePosition semantics, and Algo stop kind through registry slot context plus trusted accountstate, treat quantity, price, reduceOnly, priceProtect, clientAlgoId drift, and other echo/default fields as diagnostic unless current docs make them actionable.",
    "expect": {
      "equivalent": true,
      "intentCount": 0,
      "doNotCancel": true
    }
  },
  "formattedPrivateEventFieldMatrix": {
    "sdkSurfaceCheck": {
      "reviewedAgainst": "binance npm package 3.5.8 on 2026-05-11",
      "declarationFiles": [
        "lib/types/websockets/ws-events-formatted.d.ts",
        "lib/util/beautifier-maps.js",
        "lib/util/typeGuards.js"
      ],
      "rule": "Implementations must re-verify these formatted paths against the installed binance package before exchange calls. If declarations differ, update the adapter and fixtures before enabling EXECUTION_MODE=DEMO, TESTNET, or LIVE submission."
    },
    "events": [
      {
        "eventType": "ORDER_TRADE_UPDATE",
        "formattedType": "WsMessageFuturesUserDataTradeUpdateEventFormatted",
        "typeGuard": "isWsFormattedFuturesUserDataTradeUpdateEvent",
        "paths": {
          "eventType": "event.eventType",
          "symbol": "event.order.symbol",
          "customClientId": "event.order.clientOrderId",
          "exchangePositionSide": "event.order.positionSide",
          "orderSide": "event.order.orderSide",
          "orderType": "event.order.orderType",
          "executionType": "event.order.executionType",
          "orderStatus": "event.order.orderStatus",
          "closeAll": "event.order.isCloseAll"
        },
        "trust": "Order or fill evidence only. It may clear matching pending order confirmation, but replacement planning waits for matching position trust or scoped recovery."
      },
      {
        "eventType": "ALGO_UPDATE",
        "formattedType": "WsMessageFuturesUserDataAlgoUpdateFormatted",
        "typeGuard": "isWsFormattedFuturesAlgoUpdateEvent",
        "paths": {
          "eventType": "event.eventType",
          "symbol": "event.algoOrder.symbol",
          "customClientId": "event.algoOrder.clientAlgoId",
          "exchangePositionSide": "event.algoOrder.positionSide",
          "orderSide": "event.algoOrder.side",
          "orderType": "event.algoOrder.orderType",
          "algoStatus": "event.algoOrder.algoStatus",
          "closePosition": "event.algoOrder.closePosition",
          "triggerPrice": "event.algoOrder.triggerPrice"
        },
        "trust": "Algo order evidence only. It must not be read from root clientAlgoId and must not unlock DCA or replacement without position trust."
      },
      {
        "eventType": "TRADE_LITE",
        "formattedType": "WsMessageFuturesUserDataTradeLiteEventFormatted",
        "typeGuard": "event.eventType === \"TRADE_LITE\"",
        "paths": {
          "eventType": "event.eventType",
          "symbol": "event.symbol",
          "customClientId": "event.clientOrderId",
          "orderSide": "event.side",
          "lastFilledPrice": "event.lastFilledPrice",
          "lastFilledQuantity": "event.lastFilledQuantity",
          "tradeId": "event.tradeId",
          "orderId": "event.orderId"
        },
        "trust": "Fill evidence only. This formatted event has no positionSide path; route by order-context registry when possible, otherwise mark the symbol broad or both one-way candidates until ACCOUNT_UPDATE resolves position trust."
      },
      {
        "eventType": "ACCOUNT_UPDATE",
        "formattedType": "WsMessageFuturesUserDataAccountUpdateFormatted",
        "typeGuard": "isWsFormattedFuturesUserDataAccountUpdate",
        "paths": {
          "eventType": "event.eventType",
          "transactionTime": "event.transactionTime",
          "updateEventType": "event.updateData.updateEventType",
          "positionRows": "event.updateData.updatedPositions[]",
          "positionSymbol": "event.updateData.updatedPositions[].symbol",
          "exchangePositionSide": "event.updateData.updatedPositions[].positionSide",
          "positionAmount": "event.updateData.updatedPositions[].positionAmount",
          "entryPrice": "event.updateData.updatedPositions[].entryPrice",
          "balanceRows": "event.updateData.updatedBalances[]"
        },
        "trust": "Position trust for the matching product/symbol/position row. DCA, TP, SL, full close, and same-side add replans should key off matching position evidence or scoped recovery."
      }
    ],
    "negativeRules": [
      "Do not look for root newClientOrderId on formatted USD-M ORDER_TRADE_UPDATE; use order.clientOrderId.",
      "Do not look for root clientAlgoId on formatted USD-M ALGO_UPDATE; use algoOrder.clientAlgoId.",
      "Do not create unresolved side scopes from TRADE_LITE. Use registry context or broad symbol/both-candidate routing until ACCOUNT_UPDATE provides positionSide.",
      "Missing required formatted paths for an event that should clear a pending confirmation enters scoped recovery; it must not mutate an unscoped slot."
    ]
  },
  "eventFieldsToClassify": [
    "wsMarket",
    "wsKey",
    "eventType",
    "Spot executionReport: symbol, newClientOrderId, executionType, orderStatus",
    "USD-M ORDER_TRADE_UPDATE: order.symbol, order.clientOrderId, order.positionSide, order.executionType, order.orderStatus",
    "USD-M ALGO_UPDATE: algoOrder.symbol, algoOrder.clientAlgoId, algoOrder.positionSide, algoOrder.orderType, algoOrder.algoStatus",
    "USD-M TRADE_LITE: symbol, clientOrderId, side, lastFilledPrice, lastFilledQuantity",
    "USD-M ACCOUNT_UPDATE: updateData.updatedPositions[].symbol, positionSide, positionAmount, entryPrice"
  ],
  "implementationSkeleton": [
    {
      "module": "ConfigLoader",
      "owns": "EXECUTION_MODE, JSON config, defaults, execution acknowledgement"
    },
    {
      "module": "RedactedLogger",
      "owns": "structured errors, redaction, compact summaries"
    },
    {
      "module": "DecimalFormatter",
      "owns": "tickSize/stepSize fixed decimal strings"
    },
    {
      "module": "ClientIdFactory",
      "owns": "SDK-prefixed Custom Order IDs and order-context registry writes"
    },
    {
      "module": "BinanceAdapter",
      "owns": "verified SDK REST and WebSocket calls"
    },
    {
      "module": "InMemoryStore",
      "owns": "replacement snapshots, app-owned state, managed-slot state"
    },
    {
      "module": "StateBoundaryAdapter",
      "owns": "project-local state-store boundary, sync_required recovery, submission outcomes, and SDK/API surface notes for any published state package the user explicitly selects"
    },
    {
      "module": "Planner",
      "owns": "cleanup, protective, DCA actions and slot-based convergence"
    },
    {
      "module": "ProductWorkflow",
      "owns": "single workflow owner, symbol-side affected-scope queue, one action family per pass"
    },
    {
      "module": "PrivateStreamSupervisor",
      "owns": "user-data buffering, event-burst waiting, reconnect handling"
    },
    {
      "module": "CliCommands",
      "owns": "EXECUTION_MODE gates for doctor/status/inspect commands"
    }
  ],
  "conformanceFixtureNames": [
    "accepted_submissions_settle_to_zero_intents",
    "binance_precision_float_tail_quantized_from_filters",
    "hydrated_close_position_algo_normalizes_to_desired",
    "startup_wipe_rebuild_cancels_app_orders_before_rebuild",
    "fixed_tp_uses_regular_limit",
    "same_side_position_add_classifies_slots_once",
    "full_close_cleanup_clears_slot_state_after_cleanup_settles",
    "dca_2027_blocks_dca_only",
    "amend_no_need_to_change_treated_converged_when_current_slot_equivalent",
    "max_leverage_4509_blocks_dca_only",
    "position_open_reacts_without_timer",
    "position_open_places_protective_then_dca_after_ws_confirmation",
    "semantic_ws_logs_emitted_after_ingest",
    "symbol_side_queue_groups_private_event_burst",
    "binance_formatted_order_trade_update_uses_order_client_order_id",
    "binance_formatted_algo_update_uses_algo_order_client_algo_id",
    "binance_formatted_trade_lite_routes_by_registry_or_broad_scope",
    "binance_formatted_account_update_position_rows_create_position_trust",
    "binance_formatted_event_missing_required_path_enters_recovery",
    "binance_terminal_private_proof_makes_2011_cancel_benign",
    "usdm_algo_close_position_hydration_defaults",
    "custom_oid_guard_preflights_before_submit",
    "protective_sl_tp_pre_registered_and_dispatched_concurrently_by_default",
    "unknown_submit_outcome_enters_recovery_after_configured_timeout",
    "cancel_before_place_replacement_converges_before_place",
    "account_sync_required_triggers_scoped_rest_hydration",
    "recoverable_immediate_trigger_does_not_crash_service",
    "close_position_conflict_replans_after_cancel_settle",
    "live_submission_exception_clears_inflight",
    "unknown_order_cancel_absent_from_hydration_marks_terminal",
    "private_stream_exception_fails_startup",
    "live_marker_required_before_live_start",
    "deferred_replan_reentrant_calls_are_grouped",
    "hedge_opposite_side_coexists",
    "full_close_cleans_app_owned_orders",
    "workflow_active_user_data_defers_replan",
    "protective_orders_before_dca",
    "log_position_counters_are_unambiguous",
    "safe_status_ignores_live_env"
  ],
  "executableFixtureSchemaExample": {
    "name": "manual-same-side-add-classifies-slots",
    "product": "usdm",
    "initialSnapshot": {
      "positions": [
        {
          "symbol": "BTCUSDT",
          "exchangePositionSide": "LONG",
          "managedStrategySide": "LONG",
          "quantity": "0.001",
          "averageEntry": "76000.0"
        }
      ],
      "openOrders": [
        {
          "role": "DCA",
          "step": 1,
          "kind": "regular_LIMIT"
        },
        {
          "role": "TP",
          "step": 1,
          "kind": "regular_LIMIT"
        }
      ],
      "openAlgoOrders": [
        {
          "role": "SL",
          "step": 1,
          "kind": "algo_STOP_MARKET"
        }
      ]
    },
    "event": {
      "type": "same_side_position_add",
      "symbol": "BTCUSDT",
      "exchangePositionSide": "LONG",
      "newQuantity": "0.002",
      "newAverageEntry": "76100.0"
    },
    "expectedPlanner": {
      "slotClassifierActions": [
        "keep",
        "amend",
        "cancel_place",
        "cancel",
        "place"
      ],
      "cancelPlaceOnlyFor": "non-amendable or identity-changing Binance slots",
      "protectiveExitsBeforeDca": true,
      "trustedStateReadBeforeDca": true,
      "untouchedOppositeSideOrders": true,
      "settlesToIntentCount": 0
    }
  },
  "knownDangerousNearMisses": [
    "Default fixed TP implemented as Algo conditional instead of regular LIMIT.",
    "TAKE_PROFIT_LIMIT invented for explicit USD-M Algo conditional TP.",
    "reduceOnly sent with closePosition=true.",
    "newClientOrderId used for Algo orders instead of clientAlgoId.",
    "client IDs invented without the SDK prefix.",
    "positionSide=BOTH treated as managed LONG instead of exchange one-way side.",
    "fallback filters used after exchangeInfo hydration did not provide real filters.",
    "binary float tails stringified into DEMO, TESTNET, or LIVE order requests.",
    "formattedMessage and formattedUserDataMessage both processed without dedupe.",
    "formatted USD-M private events classified from root newClientOrderId or root clientAlgoId instead of order.clientOrderId and algoOrder.clientAlgoId.",
    "TRADE_LITE turned into an unresolved side mutation instead of registry or broad/both-candidate routing until ACCOUNT_UPDATE arrives.",
    "user-data confirmations allowed to start overlapping symbol-side workflows.",
    "accepted REST submissions treated as trusted account state instead of pending confirmations.",
    "DCA left live after full position close.",
    "opposite hedge side cancelled or replaced by symbol-only logic.",
    "client ID drift or generated metadata treated as a replacement reason.",
    "same-process fresh position reuses stale slot state after full close cleanup settled.",
    "raw request bodies, listen keys, signed URLs, or raw [order intents](https://siebly.io/reference/glossary#order-intent) logged.",
    "private account-event idleness treated as WebSocket failure."
  ],
  "goodLogTraceCatalogue": [
    "startup flat -> stream requested -> REST hydrate openManagedPositions=0 -> planner intentCount=0",
    "position open -> private_ws_event_received -> accountstate_event_applied -> affected_scope_recorded -> protective action emits SL,TP",
    "accepted submissions -> pending confirmations recorded -> own-order confirmations deferred",
    "protective confirmations -> accountstate updated -> DCA action emits one pending DCA order",
    "follow-up confirmation -> regularOpenOrders=2 and openAlgoOrders=1 -> planner intentCount=0",
    "position close -> cleanup app-owned orders -> trusted state shows no position and no app-owned orders -> slot state cleared",
    "hedge long-plus-short -> rawPositionRows=2 and openManagedPositions=2 -> opposite side preserved",
    "same-side position add -> changed slots amended or replaced once -> next planner intentCount=0"
  ],
  "knownLiveBugPatterns": [
    "Manual fill reacts only on timer: private event handler buffered events but did not schedule reconciliation.",
    "USD-M Algo SL churn: close-position hydration defaults were compared as meaningful fields.",
    "Fixed TP implemented as Algo conditional: ordinary fixed TP should have used regular LIMIT semantics and missed eligible fills while waiting for trigger behavior.",
    "Lifecycle or replacement generation recovered from client IDs: restart churn and false replacements followed.",
    "Client ID drift listed as the only replacement difference: metadata drove order churn.",
    "DCA -2027 pauses protective management: exposure-limit rejection should block DCA only.",
    "Protective submit before context registration: custom ID guard did not run before the exchange call.",
    "-2011 Unknown order loop: cancel target absent from hydration was not marked terminal or stale.",
    "Formatted private event path mismatch: ORDER_TRADE_UPDATE, ALGO_UPDATE, TRADE_LITE, or ACCOUNT_UPDATE was parsed from the wrong field path, causing missed confirmations or wrong-side routing.",
    "TRADE_LITE unresolved side mutation: fill evidence without positionSide mutated a slot before registry context or ACCOUNT_UPDATE resolved the scope.",
    "-2011 after private terminal proof logged as an alarming error instead of a benign stale-target race.",
    "In-flight client ID stuck: submit threw before cleanup cleared in-flight state.",
    "Startup logs service_ready after SDK exception: subscribe helper completion was treated as readiness.",
    "Deferred replan log storm: reentrant pass scheduled follow-up even though it did not own the active workflow."
  ],
  "finalAcceptanceGate": [
    "docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and docs/AI_PROMPT_MANIFEST.json preserve the prompt and selected options that created the project.",
    "README records the latest installed SDK version as metadata plus exact declarations inspected.",
    "A local checklist generated from this manifest is completed before EXECUTION_MODE=DEMO, TESTNET, or LIVE execution.",
    "Critical [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) from the [Conformance Pack](https://siebly.io/reference/glossary#conformance-pack) pass before EXECUTION_MODE=DEMO, TESTNET, or LIVE is enabled.",
    "Trace the full identity chain: config scope -> product/environment/account -> symbol -> position mode -> managed side -> exchange position identity -> accountstate position state (native or locally derived) -> planner scope -> slot scope -> custom order ID -> durable context -> exchange request -> REST acceptance -> private order/execution/position event -> trusted active order -> subject trust state -> confirmation tracker -> recovery scope -> cleanup/protective/DCA replanning.",
    "Do not mark the implementation complete until three consecutive full identity-chain review passes produce no code, tests, fixtures, or documentation changes.",
    "Trace mismatched, stale, missing, contradictory, duplicated, late, recovered, and flat identities across every runtime boundary.",
    "Every accepted lifecycle claim needs an executable fixture; behaviors without fixtures must be listed as unsupported or unverified.",
    "Core [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) cover context write failure before submit, early private confirmation before REST accept, one-way side flips, pending duplicate place/cancel guards, and decimal/default-equivalent active-order convergence.",
    "The [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE submission paths are implemented for order-capable projects where supported, but they remain disabled until the required identity-chain, subject-trust, symbol-scope, and risk-geometry fixtures exist and pass.",
    ".runtime/verified.json proves build, tests, and critical conformance passed before EXECUTION_MODE=DEMO, TESTNET, or LIVE startup can continue.",
    "Public-only doctor/status commands cannot place, cancel, or amend even with EXECUTION_MODE=LIVE in .env.",
    "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."
  ],
  "liveReadinessMarkerGate": {
    "markerFile": ".runtime/verified.json",
    "requiredBooleans": [
      "sdkSurfaceCheckPassed",
      "buildPassed",
      "testsPassed",
      "criticalConformancePassed"
    ],
    "rule": "When enabled, the optional runtime verification marker proves build, tests, and critical conformance for this source tree. Current execution-mode acknowledgement stays runtime config authority."
  },
  "firstRunLogTaxonomy": {
    "startup": [
      "startup_attribution",
      "config_loaded",
      "source_verification_complete",
      "public_filters_hydrated",
      "private_stream_subscribe_requested",
      "account_backfill_complete",
      "service_ready"
    ],
    "stream": [
      "private_ws_event_received",
      "accountstate_event_applied",
      "affected_scope_recorded",
      "symbol_side_reconcile_started",
      "action_family_selected",
      "submission_accepted_pending_confirmation",
      "private_ws_confirmation_applied",
      "workflow_reconcile_complete"
    ],
    "planner": [
      "planner_finished",
      "planner_intent_blocked",
      "managed_order_replacement_summary"
    ],
    "workflow": [
      "action_family_selected",
      "cancel_action_submitted",
      "post_cancel_settle_replan_scheduled",
      "live_intent_skipped_by_guard",
      "submission_accepted_pending_confirmation",
      "private_ws_confirmation_applied",
      "workflow_reconcile_complete"
    ],
    "recovery": [
      "account_sync_recovery_requested",
      "account_sync_recovery_complete",
      "binance_submission_failed",
      "recovery_required",
      "operator_paused"
    ],
    "healthyPatterns": [
      "planner_finished intentCount=N blockedCount=0 followed by workflow_reconcile_complete submitted=N",
      "a later planner_finished intentCount=0 after pending confirmations are confirmed by private stream evidence or scoped recovery hydration"
    ],
    "attentionPatterns": [
      "readiness=sync_required",
      "planner_intent_blocked role=RISK",
      "binance_submission_failed",
      "activeOrders alternating without convergence",
      "the same custom ID repeatedly skipped or rejected"
    ]
  }
}
