{
  "format": "siebly-conformance-pack/v1",
  "id": "binance-position-manager",
  "title": "Binance Position Management Conformance Pack",
  "lastReviewed": "2026-05-12",
  "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; do not pin implementation guidance to a version observed in one prior test run."
  },
  "canonicalArtifacts": {
    "manifest": "https://siebly.io/.well-known/agent-manifests/binance-position-manager/latest.json",
    "integrationKit": "https://siebly.io/.well-known/integration-kits/binance-position-manager/latest.json",
    "recipe": "https://siebly.io/.well-known/recipes/binance-position-manager.json",
    "guide": "https://siebly.io/ai/exchange-state/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"
    ]
  },
  "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."
  },
  "schema": {
    "fixture": {
      "name": "string",
      "product": "spot | usdm | multi",
      "given": "hydration snapshots, buffered events, in-memory state, intents, or errors",
      "expect": "planner outputs, submit calls, state transitions, log markers, active counts, and blocked actions"
    },
    "trace": {
      "event": "log event name",
      "requiredFields": "fields or matchers that must be present"
    }
  },
  "criticalWriteConformance": {
    "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"
    ],
    "architecture": "ws_symbol_side_action_gated",
    "requiredWorkflowText": "private WS account events feed accountstate, semantic logs record affected symbol-side scopes, one action family runs per pass, and accepted submissions remain pending confirmations until private stream evidence or scoped recovery hydration confirms them",
    "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."
    ]
  },
  "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."
    ]
  },
  "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."
  },
  "requiredCoreSafetyFixtures": [
    "blank_symbols_auto_detects_open_positions",
    "absent_symbols_auto_detects_open_positions",
    "blank_symbols_no_positions_noops_without_mutation",
    "symbol_allowlist_manages_matching_detected_positions_only",
    "sample_symbol_not_used_as_runtime_default",
    "order_confirmation_does_not_imply_position_trust",
    "native_position_dca_fill_waits_for_position_update",
    "native_position_tp_sl_fill_waits_for_position_update",
    "spot_local_position_state_substitutes_for_native_position_rows",
    "long_dca_equal_sl_rejected",
    "short_dca_equal_sl_rejected"
  ],
  "fixtures": [
    {
      "name": "position_open_reacts_without_timer",
      "product": "usdm",
      "given": {
        "initialHydration": {
          "positions": [],
          "regularOpenOrders": [],
          "openAlgoOrders": [],
          "filters": [
            {
              "symbol": "BTCUSDT",
              "tickSize": "0.1",
              "stepSize": "0.001"
            }
          ]
        },
        "events": [
          {
            "eventType": "TRADE_LITE",
            "symbol": "BTCUSDT",
            "clientOrderId": "manual-open"
          },
          {
            "eventType": "ORDER_TRADE_UPDATE",
            "order": {
              "symbol": "BTCUSDT",
              "clientOrderId": "manual-open",
              "positionSide": "BOTH"
            }
          },
          {
            "eventType": "ACCOUNT_UPDATE",
            "updateData": {
              "updatedPositions": [
                {
                  "symbol": "BTCUSDT",
                  "positionSide": "BOTH",
                  "positionAmount": 0.01,
                  "entryPrice": 100000
                }
              ]
            }
          }
        ],
        "postEventHydration": {
          "positions": [
            {
              "symbol": "BTCUSDT",
              "positionSide": "BOTH",
              "positionAmt": "0.01",
              "entryPrice": "100000.0"
            }
          ],
          "regularOpenOrders": [],
          "openAlgoOrders": []
        }
      },
      "expect": {
        "scheduledDelayMs": 0,
        "semanticLogs": [
          "private_ws_event_received",
          "accountstate_event_applied",
          "affected_scope_recorded"
        ],
        "firstPhase": "protective",
        "firstIntentRoles": [
          "SL",
          "TP"
        ],
        "noTimerWait": true
      }
    },
    {
      "name": "position_open_places_protective_then_dca_after_ws_confirmation",
      "product": "usdm",
      "given": {
        "position": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "managedStrategySide": "LONG"
        },
        "activeOrders": [],
        "privateConfirmations": [
          "SL_NEW",
          "TP_NEW"
        ]
      },
      "expect": {
        "firstPhase": "protective",
        "firstPhaseRoles": [
          "SL",
          "TP"
        ],
        "dcaInFirstPhase": false,
        "dcaPhaseRequiresPrivateConfirmation": true,
        "finalIntentCount": 0
      }
    },
    {
      "name": "accepted_submissions_settle_to_zero_intents",
      "product": "usdm",
      "given": {
        "hydration": {
          "positions": [
            {
              "symbol": "BTCUSDT",
              "positionSide": "BOTH",
              "positionAmt": "0.01"
            }
          ],
          "regularOpenOrders": [
            {
              "role": "DCA",
              "clientId": "x-9f2c8a1b6d3e",
              "type": "LIMIT"
            },
            {
              "role": "TP",
              "clientId": "x-a7d4e1c9b2f6",
              "type": "LIMIT"
            }
          ],
          "openAlgoOrders": [
            {
              "role": "SL",
              "clientAlgoId": "x-c3e8b5a1d7f0",
              "type": "STOP_MARKET"
            }
          ]
        }
      },
      "expect": {
        "activeOrders": 3,
        "intentCount": 0,
        "cancelIntents": 0,
        "placeIntents": 0
      }
    },
    {
      "name": "startup_wipe_rebuild_cancels_app_orders_before_rebuild",
      "product": "usdm",
      "given": {
        "startupHydration": {
          "positions": [
            {
              "symbol": "BTCUSDT",
              "positionSide": "BOTH",
              "positionAmt": "0.01"
            }
          ],
          "regularOpenOrders": [
            {
              "role": "DCA",
              "clientId": "x-2d9a6f1c8b4e",
              "owned": true
            },
            {
              "role": "TP",
              "clientId": "x-4e1b8c7f0a2d",
              "owned": true
            },
            {
              "role": "TP",
              "clientId": "external-1729",
              "owned": false
            }
          ],
          "openAlgoOrders": [
            {
              "role": "SL",
              "clientAlgoId": "x-8b3f0d6a1c9e",
              "owned": true
            }
          ]
        }
      },
      "expect": {
        "cleanupBeforeRebuild": true,
        "cancelledOwnedOnly": [
          "x-2d9a6f1c8b4e",
          "x-4e1b8c7f0a2d",
          "x-8b3f0d6a1c9e"
        ],
        "unownedStillOpen": [
          "external-1729"
        ],
        "rebuiltPhases": [
          "cleanup",
          "protective",
          "dca"
        ],
        "lifecycleRecoveredFromClientIds": false
      }
    },
    {
      "name": "fixed_tp_uses_regular_limit",
      "product": "usdm",
      "given": {
        "position": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "managedStrategySide": "LONG"
        },
        "desiredRole": "TP"
      },
      "expect": {
        "method": "submitNewOrder",
        "type": "LIMIT",
        "timeInForce": "GTC",
        "clientIdField": "newClientOrderId",
        "appearsIn": "regularOpenOrders",
        "notIn": "openAlgoOrders"
      }
    },
    {
      "name": "sl_is_algo_stop_market_close_position",
      "product": "usdm",
      "given": {
        "position": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "managedStrategySide": "LONG"
        },
        "desiredRole": "SL"
      },
      "expect": {
        "method": "submitNewAlgoOrder",
        "type": "STOP_MARKET",
        "closePosition": true,
        "forbiddenFields": [
          "quantity",
          "reduceOnly"
        ],
        "clientIdField": "clientAlgoId"
      }
    },
    {
      "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
      }
    },
    {
      "name": "custom_oid_guard_preflights_before_submit",
      "product": "usdm",
      "given": {
        "pendingConfirmations": [
          "BTCUSDT:BOTH:LONG:SL"
        ],
        "intents": [
          {
            "action": "place",
            "role": "SL",
            "slotKey": "BTCUSDT:BOTH:LONG:SL",
            "clientId": "x-b3f91d7c4a0e"
          }
        ]
      },
      "expect": {
        "preflightFailsBeforeExchangeCall": true,
        "exchangeSubmitCalls": 0,
        "pauseReason": "pending_confirmation_guard"
      }
    },
    {
      "name": "cancel_before_place_replacement_converges_before_place",
      "product": "usdm",
      "given": {
        "plan": [
          {
            "action": "cancel",
            "kind": "algo",
            "role": "SL",
            "clientAlgoId": "x-0af3d9b7c2e1"
          },
          {
            "action": "place",
            "kind": "algo",
            "role": "SL",
            "clientAlgoId": "x-7ec12a9f0d4b"
          },
          {
            "action": "place",
            "kind": "regular",
            "role": "TP",
            "clientId": "x-d64f0b2e8a19"
          }
        ],
        "openAlgoOrdersBeforeCancel": [
          "x-0af3d9b7c2e1"
        ],
        "openAlgoOrdersAfterSettle": []
      },
      "expect": {
        "actionSequence": [
          "cancel",
          "settle_or_private_confirm",
          "replan",
          "place"
        ],
        "restHydrateRequiredInHealthyMode": false,
        "cancelOutcomesAppliedBeforeReplan": true
      }
    },
    {
      "name": "account_sync_required_triggers_scoped_rest_hydration",
      "product": "usdm",
      "given": {
        "readiness": "sync_required",
        "syncRequests": [
          "positions",
          "openOrders",
          "openAlgoOrders"
        ],
        "liveCapableIntentPending": true
      },
      "expect": {
        "plannerRunsBeforeSync": false,
        "submitCallsBeforeSync": 0,
        "hydratedSubjects": [
          "positions",
          "openOrders",
          "openAlgoOrders"
        ],
        "logs": [
          "account_sync_recovery_requested",
          "account_sync_recovery_complete"
        ],
        "nextAction": "schedule_symbol_side_reconcile"
      }
    },
    {
      "name": "recoverable_immediate_trigger_does_not_crash_service",
      "product": "usdm",
      "given": {
        "placement": {
          "kind": "algo",
          "role": "SL",
          "clientAlgoId": "x-85c29f1d0ab3"
        },
        "exchangeError": {
          "code": "-2021",
          "message": "Order would immediately trigger."
        }
      },
      "expect": {
        "recoverable": true,
        "serviceCrashed": false,
        "laterIntentsSubmitted": false,
        "structuredErrorLogged": true,
        "recovery": "enter_recovery_required_or_replan_product"
      }
    },
    {
      "name": "close_position_conflict_replans_after_cancel_settle",
      "product": "usdm",
      "given": {
        "placement": {
          "kind": "algo",
          "role": "SL",
          "closePosition": true,
          "clientAlgoId": "x-85c29f1d0ab3"
        },
        "exchangeError": {
          "code": "-4130",
          "message": "Close-position order already exists."
        }
      },
      "expect": {
        "recoverable": true,
        "placementPhaseStopped": true,
        "recoveryPhases": [
          "cancel",
          "private_confirm_or_scoped_hydrate",
          "replan"
        ],
        "serviceCrashed": false
      }
    },
    {
      "name": "dca_2027_blocks_dca_only",
      "product": "usdm",
      "given": {
        "placement": {
          "kind": "regular",
          "role": "DCA",
          "clientId": "x-f1e0b8c3d6a4",
          "type": "LIMIT"
        },
        "exchangeError": {
          "code": "-2027",
          "message": "Exceeded the maximum allowable position at current leverage."
        },
        "protectiveSlots": [
          "SL",
          "TP"
        ]
      },
      "expect": {
        "dcaBlockedOrCooledDown": true,
        "protectiveManagementStillActive": true,
        "operatorPaused": false,
        "productWidePause": false
      }
    },
    {
      "name": "amend_no_need_to_change_treated_converged_when_current_slot_equivalent",
      "product": "usdm",
      "given": {
        "amend": {
          "kind": "regular",
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "exchangeError": {
          "code": "-5027",
          "message": "No need to change."
        },
        "slotConvergenceFieldsMatch": true
      },
      "expect": {
        "slotConverged": true,
        "cancelPlaceFallback": false,
        "finalIntentCount": 0
      }
    },
    {
      "name": "max_leverage_4509_blocks_dca_only",
      "product": "usdm",
      "given": {
        "placement": {
          "kind": "regular",
          "role": "DCA",
          "clientId": "x-f1e0b8c3d6a4",
          "type": "LIMIT"
        },
        "exchangeError": {
          "code": "-4509",
          "message": "Maximum leverage limit exceeded."
        },
        "protectiveSlots": [
          "SL",
          "TP"
        ]
      },
      "expect": {
        "dcaBlockedOrCooledDown": true,
        "protectiveManagementStillActive": true,
        "operatorPaused": false
      }
    },
    {
      "name": "live_marker_required_before_live_start",
      "product": "multi",
      "given": {
        "runtimeConfig": {
          "liveTradingEnabled": true,
          "liveAckMatched": true
        },
        "optionalMarkerGateEnabled": true,
        "runtimeVerifiedMarker": null
      },
      "expect": {
        "liveStartupAllowed": false,
        "requiredMarkerFile": ".runtime/verified.json",
        "missingBooleans": [
          "sdkSurfaceCheckPassed",
          "buildPassed",
          "testsPassed",
          "criticalConformancePassed"
        ]
      }
    },
    {
      "name": "live_submission_exception_clears_inflight",
      "product": "usdm",
      "given": {
        "inFlightBefore": [],
        "phaseIntents": [
          {
            "action": "cancel",
            "role": "SL",
            "clientId": "x-1d0a7c4f9e2b"
          }
        ],
        "exchangeError": {
          "code": "-2011",
          "message": "Unknown order sent."
        }
      },
      "expect": {
        "inFlightAfter": [],
        "recoveryState": {
          "recoveryRequired": true,
          "operatorPaused": false,
          "blocksNewExposure": true,
          "blocksNormalPhasesUntilHydrated": true,
          "requiresScopedHydration": true,
          "clearsBy": [
            "scoped_rest_hydration",
            "buffered_user_data_replay",
            "coherent_accountstate_read"
          ]
        },
        "structuredErrorLogged": true
      }
    },
    {
      "name": "unknown_order_cancel_absent_from_hydration_marks_terminal",
      "product": "usdm",
      "given": {
        "openAlgoOrders": [],
        "cancelTarget": {
          "role": "SL",
          "clientAlgoId": "x-5c8a1f0d3e7b"
        },
        "cancelError": {
          "code": "-2011",
          "message": "Unknown order sent."
        }
      },
      "expect": {
        "orderState": "terminal_or_stale",
        "retryCancelForever": false,
        "inFlightAfter": [],
        "logLevel": "info"
      }
    },
    {
      "name": "private_stream_exception_fails_startup",
      "product": "usdm",
      "given": {
        "events": [
          {
            "sdkEvent": "exception",
            "product": "usdm",
            "error": {
              "message": "listen key failed"
            }
          }
        ],
        "requiredPrivateProducts": [
          "usdm"
        ]
      },
      "expect": {
        "readiness": "recoveryRequired",
        "serviceReadyLogged": false,
        "startupFailsBeforeLive": true,
        "nestedSdkErrorPreserved": true
      }
    },
    {
      "name": "deferred_replan_reentrant_calls_are_grouped",
      "product": "usdm",
      "given": {
        "activeWorkflow": true,
        "reentrantEvents": [
          {
            "eventType": "ORDER_TRADE_UPDATE"
          },
          {
            "eventType": "ALGO_UPDATE"
          },
          {
            "eventType": "ORDER_TRADE_UPDATE"
          }
        ]
      },
      "expect": {
        "followUpOwners": 1,
        "deferredReasonsGrouped": true,
        "logStorm": false,
        "finalIntentCount": 0
      }
    },
    {
      "name": "same_side_position_add_classifies_slots_once",
      "product": "usdm",
      "given": {
        "existingScope": {
          "side": "LONG",
          "symbol": "BTCUSDT",
          "positionSide": "BOTH"
        },
        "hydratedPosition": {
          "quantity": "0.02",
          "averageEntry": "100500.0"
        },
        "oppositeHedgeSideOpen": true
      },
      "expect": {
        "slotClassifierActions": [
          "keep",
          "amend",
          "cancel_place",
          "cancel",
          "place"
        ],
        "cancelPlaceOnlyFor": "non-amendable or identity-changing Binance slots",
        "protectiveExitsBeforeDca": true,
        "trustedStateReadBeforeDca": true,
        "oppositeSideTouched": false,
        "convergenceIntentCount": 0
      }
    },
    {
      "name": "hedge_same_symbol_opposite_side_coexists",
      "product": "usdm",
      "given": {
        "hedgeMode": true,
        "positions": [
          {
            "symbol": "BTCUSDT",
            "positionSide": "LONG",
            "quantity": "0.01"
          },
          {
            "symbol": "BTCUSDT",
            "positionSide": "SHORT",
            "quantity": "0.01"
          }
        ],
        "existingLongOrders": 3
      },
      "expect": {
        "shortOrdersCreated": 3,
        "longOrdersCancelled": 0,
        "finalPositions": 2,
        "finalActiveOrders": 6,
        "finalIntentCount": 0
      }
    },
    {
      "name": "full_close_cleanup_clears_slot_state_after_cleanup_settles",
      "product": "usdm",
      "given": {
        "managedScope": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "side": "LONG"
        },
        "hydrationAfterCleanup": {
          "positions": [],
          "regularOpenOrders": [],
          "openAlgoOrders": []
        }
      },
      "expect": {
        "slotStateCleared": true,
        "nextSameSymbolSameSideStartsFresh": true
      }
    },
    {
      "name": "binary_float_precision_tails_are_formatted",
      "product": "usdm",
      "given": {
        "price": "74992.800000000003",
        "tickSize": "0.1",
        "quantity": "0.0020000000000000005",
        "stepSize": "0.001"
      },
      "expect": {
        "price": "74992.8",
        "quantity": "0.002",
        "submitRawFloatTail": false
      }
    },
    {
      "name": "fallback_filters_block_live_planning",
      "product": "usdm",
      "given": {
        "hydratedFiltersMissing": true,
        "liveCapableIntent": {
          "role": "DCA"
        }
      },
      "expect": {
        "blocked": true,
        "submitted": false,
        "reason": "missing_hydrated_filters"
      }
    },
    {
      "name": "one_way_tp_sends_reduce_only_regular_limit",
      "product": "usdm",
      "given": {
        "positionMode": "one_way",
        "position": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "positionAmt": "0.01"
        },
        "desiredRole": "TP"
      },
      "expect": {
        "method": "submitNewOrder",
        "type": "LIMIT",
        "positionSide": "BOTH",
        "reduceOnlyWhenConfiguredAndAllowed": true,
        "clientIdField": "newClientOrderId"
      }
    },
    {
      "name": "hedge_regular_tp_omits_reduce_only_but_ignores_hydrated_echo",
      "product": "usdm",
      "given": {
        "positionMode": "hedge",
        "desiredTp": {
          "positionSide": "LONG",
          "price": "105000.0",
          "quantity": "0.010"
        },
        "hydratedTp": {
          "positionSide": "LONG",
          "reduceOnly": false,
          "price": "105000",
          "quantity": "0.01"
        }
      },
      "expect": {
        "equivalent": true,
        "amendIntents": 0,
        "cancelPlaceIntents": 0,
        "reduceOnlyEchoIsNotActionable": true
      }
    },
    {
      "name": "client_id_change_alone_does_not_replace_order",
      "product": "usdm",
      "given": {
        "desiredSlot": {
          "role": "TP",
          "side": "SELL",
          "quantity": "0.01",
          "price": "105000.0",
          "clientId": "x-new"
        },
        "activeSlot": {
          "role": "TP",
          "side": "SELL",
          "quantity": "0.010",
          "price": "105000",
          "clientId": "x-old"
        }
      },
      "expect": {
        "ordersEquivalent": true,
        "replacementPlanned": false,
        "clientIdDriftActionable": false
      }
    },
    {
      "name": "only_changed_slot_replaced",
      "product": "usdm",
      "given": {
        "activeSlots": [
          {
            "role": "TP",
            "price": "105000.0",
            "quantity": "0.01"
          },
          {
            "role": "SL",
            "triggerPrice": "95000.0"
          },
          {
            "role": "DCA",
            "price": "97000.0",
            "quantity": "0.005"
          }
        ],
        "desiredSlots": [
          {
            "role": "TP",
            "price": "105000.0",
            "quantity": "0.01"
          },
          {
            "role": "SL",
            "triggerPrice": "94900.0"
          },
          {
            "role": "DCA",
            "price": "97000.0",
            "quantity": "0.005"
          }
        ]
      },
      "expect": {
        "changedRoles": [
          "SL"
        ],
        "untouchedRoles": [
          "TP",
          "DCA"
        ],
        "replaceAllSlots": false
      }
    },
    {
      "name": "healthy_user_data_reconcile_skips_rest_backfill",
      "product": "usdm",
      "given": {
        "accountstateTrusted": true,
        "event": {
          "eventType": "ACCOUNT_UPDATE",
          "subjects": [
            "positions"
          ]
        },
        "syncRequired": false,
        "recoveryRequired": false
      },
      "expect": {
        "accountstateIngestedImmediately": true,
        "restHydrationCalls": 0,
        "plannerRunsAfterEventBurstWait": true
      }
    },
    {
      "name": "semantic_ws_logs_emitted_after_ingest",
      "product": "usdm",
      "given": {
        "userDataEvents": [
          "ORDER_TRADE_UPDATE",
          "ALGO_UPDATE",
          "ACCOUNT_UPDATE"
        ]
      },
      "expect": {
        "logs": [
          "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"
        ],
        "rawPrivatePayloadLogged": false
      }
    },
    {
      "name": "symbol_side_queue_groups_private_event_burst",
      "product": "usdm",
      "given": {
        "burstEvents": [
          {
            "eventType": "TRADE_LITE",
            "symbol": "BTCUSDT",
            "clientOrderId": "x-9f2c8a1b6d3e"
          },
          {
            "eventType": "ORDER_TRADE_UPDATE",
            "order": {
              "symbol": "BTCUSDT",
              "clientOrderId": "x-9f2c8a1b6d3e",
              "positionSide": "BOTH"
            }
          },
          {
            "eventType": "ACCOUNT_UPDATE",
            "updateData": {
              "updatedPositions": [
                {
                  "symbol": "BTCUSDT",
                  "positionSide": "BOTH",
                  "positionAmount": 0.01
                }
              ]
            }
          }
        ],
        "waitForRelatedEventsMs": 50,
        "maxDelayMs": 250
      },
      "expect": {
        "affectedWorkItems": 1,
        "workflowPasses": 1,
        "dedupeKeyShape": "product:symbol:managedSide"
      }
    },
    {
      "name": "private_stream_event_during_active_workflow_defers_followup",
      "product": "usdm",
      "given": {
        "workflowOwnerActive": true,
        "privateEvents": [
          {
            "eventType": "ORDER_TRADE_UPDATE"
          },
          {
            "eventType": "ACCOUNT_UPDATE"
          }
        ]
      },
      "expect": {
        "reentrantWorkflowStarts": 0,
        "deferredFollowUpRecorded": true,
        "followUpRunsAfterOwner": 1
      }
    },
    {
      "name": "pending_confirmation_does_not_unlock_dependent_action_family",
      "product": "usdm",
      "given": {
        "acceptedProtectiveResponses": [
          "SL",
          "TP"
        ],
        "privateConfirmations": [],
        "nextDesiredActionFamily": "dca"
      },
      "expect": {
        "dependentPhaseBlocked": true,
        "dcaSubmitCalls": 0,
        "clearsOnlyBy": [
          "private_confirmation",
          "scoped_recovery_hydration"
        ]
      }
    },
    {
      "name": "pending_confirmations_do_not_trigger_replacement",
      "product": "usdm",
      "given": {
        "pendingPlace": {
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "desiredSlotStillEquivalent": true
      },
      "expect": {
        "replacementIntents": 0,
        "duplicatePlaceCalls": 0,
        "waitForTrustedState": true
      }
    },
    {
      "name": "pending_place_guard_does_not_block_cancel",
      "product": "usdm",
      "given": {
        "pendingPlace": {
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "cleanupIntent": {
          "action": "cancel",
          "role": "SL",
          "clientAlgoId": "x-c3e8b5a1d7f0"
        }
      },
      "expect": {
        "cleanupCancelAllowed": true,
        "newPlaceBlocked": true,
        "guardScopedByActionAndTarget": true
      }
    },
    {
      "name": "custom_order_id_registry_lookup_routes_private_event",
      "product": "usdm",
      "given": {
        "registry": {
          "x-9f2c8a1b6d3e": {
            "slotKey": "BTCUSDT:BOTH:LONG:DCA:1",
            "role": "DCA"
          }
        },
        "privateEvent": {
          "eventType": "ORDER_TRADE_UPDATE",
          "order": {
            "symbol": "BTCUSDT",
            "clientOrderId": "x-9f2c8a1b6d3e",
            "positionSide": "BOTH"
          }
        }
      },
      "expect": {
        "slotResolvedByRegistry": true,
        "strategyStateParsedFromClientId": false,
        "affectedScope": "BTCUSDT:BOTH:LONG"
      }
    },
    {
      "name": "binance_formatted_order_trade_update_uses_order_client_order_id",
      "product": "usdm",
      "given": {
        "formattedEvent": {
          "eventType": "ORDER_TRADE_UPDATE",
          "order": {
            "symbol": "BTCUSDT",
            "clientOrderId": "x-a7d4e1c9b2f6",
            "positionSide": "BOTH",
            "executionType": "NEW",
            "orderStatus": "NEW"
          }
        },
        "rootFieldsAbsent": [
          "newClientOrderId",
          "clientAlgoId"
        ],
        "pendingConfirmation": {
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "registry": {
          "x-a7d4e1c9b2f6": {
            "slotKey": "BTCUSDT:BOTH:LONG:TP",
            "role": "TP"
          }
        }
      },
      "expect": {
        "readsClientIdFrom": "order.clientOrderId",
        "pendingOrderConfirmationCleared": true,
        "affectedScope": "BTCUSDT:BOTH:LONG",
        "positionTrustUnlocked": false,
        "waitsForPositionTrustFrom": "ACCOUNT_UPDATE updateData.updatedPositions[]"
      }
    },
    {
      "name": "binance_formatted_algo_update_uses_algo_order_client_algo_id",
      "product": "usdm",
      "given": {
        "formattedEvent": {
          "eventType": "ALGO_UPDATE",
          "algoOrder": {
            "symbol": "BTCUSDT",
            "clientAlgoId": "x-c3e8b5a1d7f0",
            "positionSide": "BOTH",
            "orderType": "STOP_MARKET",
            "algoStatus": "NEW",
            "closePosition": true
          }
        },
        "rootFieldsAbsent": [
          "clientAlgoId",
          "newClientOrderId"
        ],
        "pendingConfirmation": {
          "role": "SL",
          "clientAlgoId": "x-c3e8b5a1d7f0"
        },
        "registry": {
          "x-c3e8b5a1d7f0": {
            "slotKey": "BTCUSDT:BOTH:LONG:SL",
            "role": "SL"
          }
        }
      },
      "expect": {
        "readsClientIdFrom": "algoOrder.clientAlgoId",
        "pendingOrderConfirmationCleared": true,
        "affectedScope": "BTCUSDT:BOTH:LONG",
        "positionTrustUnlocked": false,
        "waitsForPositionTrustFrom": "ACCOUNT_UPDATE updateData.updatedPositions[]"
      }
    },
    {
      "name": "binance_formatted_trade_lite_routes_by_registry_or_broad_scope",
      "product": "usdm",
      "given": {
        "formattedEvent": {
          "eventType": "TRADE_LITE",
          "symbol": "BTCUSDT",
          "clientOrderId": "x-9f2c8a1b6d3e",
          "side": "BUY",
          "lastFilledPrice": 97000,
          "lastFilledQuantity": 0.005
        },
        "noPositionSidePath": true,
        "registry": {
          "x-9f2c8a1b6d3e": {
            "slotKey": "BTCUSDT:BOTH:LONG:DCA:1",
            "role": "DCA"
          }
        },
        "missingContextVariant": {
          "registry": {},
          "positionMode": "one_way"
        }
      },
      "expect": {
        "withRegistryAffectedScope": "BTCUSDT:BOTH:LONG",
        "withoutRegistryAffectedScopes": [
          "BTCUSDT:BOTH:LONG_candidate",
          "BTCUSDT:BOTH:SHORT_candidate"
        ],
        "unknownSideMutation": false,
        "positionTrustUnlocked": false,
        "waitsForPositionTrustFrom": "ACCOUNT_UPDATE updateData.updatedPositions[]"
      }
    },
    {
      "name": "binance_formatted_account_update_position_rows_create_position_trust",
      "product": "usdm",
      "given": {
        "previousPosition": {
          "symbol": "BTCUSDT",
          "positionSide": "BOTH",
          "positionAmount": 0.01,
          "entryPrice": 100000
        },
        "formattedEvent": {
          "eventType": "ACCOUNT_UPDATE",
          "transactionTime": 1760000000000,
          "updateData": {
            "updateEventType": "ORDER",
            "updatedPositions": [
              {
                "symbol": "BTCUSDT",
                "positionSide": "BOTH",
                "positionAmount": 0.015,
                "entryPrice": 99000
              }
            ],
            "updatedBalances": []
          }
        },
        "priorOrderEvidence": {
          "eventType": "TRADE_LITE",
          "clientOrderId": "x-9f2c8a1b6d3e"
        }
      },
      "expect": {
        "readsPositionRowsFrom": "updateData.updatedPositions[]",
        "positionTrustSubject": "BTCUSDT:BOTH:LONG",
        "replacementPlanningAllowedAfterThisEvent": true,
        "dcaReprotectUsesUpdatedSizeAndEntry": true
      }
    },
    {
      "name": "binance_formatted_event_missing_required_path_enters_recovery",
      "product": "usdm",
      "given": {
        "formattedEvent": {
          "eventType": "ORDER_TRADE_UPDATE",
          "order": {
            "symbol": "BTCUSDT",
            "positionSide": "BOTH",
            "executionType": "NEW",
            "orderStatus": "NEW"
          }
        },
        "pendingConfirmation": {
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "missingRequiredPath": "order.clientOrderId"
      },
      "expect": {
        "pendingConfirmationCleared": false,
        "unknownScopeMutation": false,
        "recoveryState": {
          "recoveryRequired": true,
          "operatorPaused": false,
          "blocksNewExposure": true,
          "blocksNormalPhasesUntilHydrated": true,
          "requiresScopedHydration": true,
          "clearsBy": [
            "scoped_rest_hydration",
            "buffered_user_data_replay",
            "coherent_accountstate_read"
          ]
        },
        "diagnostic": "formatted_private_event_missing_required_path",
        "scopedHydrationScheduled": true
      }
    },
    {
      "name": "binance_terminal_private_proof_makes_2011_cancel_benign",
      "product": "usdm",
      "given": {
        "cancelTarget": {
          "role": "SL",
          "clientAlgoId": "x-c3e8b5a1d7f0"
        },
        "privateTerminalProof": {
          "eventType": "ALGO_UPDATE",
          "algoOrder": {
            "clientAlgoId": "x-c3e8b5a1d7f0",
            "symbol": "BTCUSDT",
            "positionSide": "BOTH",
            "algoStatus": "CANCELED"
          }
        },
        "cancelError": {
          "code": "-2011",
          "message": "Unknown order sent."
        }
      },
      "expect": {
        "treatedAsBenignRace": true,
        "logLevel": "info",
        "structuredErrorLoggedAsAlarm": false,
        "orderState": "terminal_or_stale",
        "inFlightAfter": [],
        "recoveryRequired": false
      }
    },
    {
      "name": "protective_sl_tp_pre_registered_and_dispatched_concurrently_by_default",
      "product": "usdm",
      "given": {
        "actionFamily": "protective",
        "intents": [
          {
            "role": "SL"
          },
          {
            "role": "TP"
          }
        ]
      },
      "expect": {
        "contextsRegisteredBeforeSubmit": [
          "SL",
          "TP"
        ],
        "dispatchMode": "concurrent",
        "dcaInSamePass": false
      }
    },
    {
      "name": "unknown_submit_outcome_enters_recovery_after_configured_timeout",
      "product": "usdm",
      "given": {
        "mutation": {
          "action": "place",
          "role": "SL",
          "clientAlgoId": "x-c3e8b5a1d7f0"
        },
        "restOutcome": "timeout_after_send_possible",
        "confirmationTimeoutMs": 5000,
        "privateConfirmation": null
      },
      "expect": {
        "recoveryState": {
          "recoveryRequired": true,
          "operatorPaused": false,
          "blocksNewExposure": true,
          "blocksNormalPhasesUntilHydrated": true,
          "requiresScopedHydration": true,
          "clearsBy": [
            "scoped_rest_hydration",
            "buffered_user_data_replay",
            "coherent_accountstate_read"
          ]
        },
        "duplicateSubmitBeforeRecovery": false,
        "scopedHydrationScheduled": true
      }
    },
    {
      "name": "recovery_required_blocks_normal_actions_until_hydration_succeeds",
      "product": "usdm",
      "given": {
        "recoveryRequired": true,
        "affectedScope": "BTCUSDT:BOTH:LONG",
        "desiredPhase": "protective"
      },
      "expect": {
        "plannerRunsBeforeHydration": false,
        "normalPhasesBlocked": [
          "cleanup",
          "protective",
          "dca"
        ],
        "nextAction": "scoped_rest_hydration_then_requeue"
      }
    },
    {
      "name": "duplicate_client_id_4116_enters_recovery_without_pause",
      "product": "usdm",
      "given": {
        "placement": {
          "role": "TP",
          "clientId": "x-a7d4e1c9b2f6"
        },
        "exchangeError": {
          "code": "-4116",
          "message": "ClientOrderId is duplicated"
        }
      },
      "expect": {
        "recoveryRequired": true,
        "operatorPaused": false,
        "orderContextNotCorrupted": true
      }
    },
    {
      "name": "dca_2019_blocks_dca_only",
      "product": "usdm",
      "given": {
        "placement": {
          "kind": "regular",
          "role": "DCA",
          "clientId": "x-f1e0b8c3d6a4",
          "type": "LIMIT"
        },
        "exchangeError": {
          "code": "-2019",
          "message": "Margin is insufficient."
        },
        "protectiveSlots": [
          "SL",
          "TP"
        ]
      },
      "expect": {
        "dcaBlockedOrCooledDown": true,
        "preparedContextDeleted": true,
        "protectiveManagementStillActive": true,
        "recoveryRequired": false
      }
    },
    {
      "name": "regular_tp_dca_5029_filter_block_is_role_specific",
      "product": "usdm",
      "given": {
        "exchangeError": {
          "code": "-5029",
          "message": "notional must be no smaller than minimum notional"
        },
        "affectedOrders": [
          {
            "role": "TP",
            "kind": "regular_LIMIT"
          },
          {
            "role": "DCA",
            "kind": "regular_LIMIT"
          }
        ]
      },
      "expect": {
        "classification": "deterministic_filter_block",
        "regularTpBehavior": "omit_or_block_and_cancel_stale_infeasible_tp",
        "regularDcaBehavior": "block_dca_with_min_notional_reason",
        "blindlyAppliedToAlgoSl": false
      }
    },
    {
      "name": "position_full_close_cleans_app_orders",
      "product": "usdm",
      "given": {
        "position": null,
        "activeOrders": [
          {
            "owner": "app",
            "role": "DCA",
            "clientId": "x-9f2c8a1b6d3e"
          },
          {
            "owner": "app",
            "role": "TP",
            "clientId": "x-a7d4e1c9b2f6"
          },
          {
            "owner": "app",
            "role": "SL",
            "clientAlgoId": "x-c3e8b5a1d7f0"
          },
          {
            "owner": "manual",
            "role": "MANUAL",
            "clientId": "external-1729"
          }
        ]
      },
      "expect": {
        "cancelledOwnedRoles": [
          "DCA",
          "TP",
          "SL"
        ],
        "unownedOrdersTouched": false,
        "finalPhase": "noop"
      }
    },
    {
      "name": "binary_float_tails_are_formatted_from_filters",
      "product": "usdm",
      "given": {
        "rawPrice": "74992.800000000003",
        "rawQuantity": "0.0020000000000000005",
        "filters": {
          "tickSize": "0.1",
          "stepSize": "0.001"
        }
      },
      "expect": {
        "requestPrice": "74992.8",
        "requestQuantity": "0.002",
        "submitRawFloatTail": false
      }
    },
    {
      "name": "websocket_beautify_required_for_formatted_user_data",
      "product": "multi",
      "given": {
        "websocketClientOptions": {
          "beautify": false
        },
        "handlerUses": "formattedUserDataMessage"
      },
      "expect": {
        "sdkSurfaceCheckFails": true,
        "fix": "enable websocket beautify or handle raw user-data payloads explicitly"
      }
    },
    {
      "name": "rest_beautify_disabled_for_accountstate_inputs",
      "product": "multi",
      "given": {
        "restClientOptions": {
          "beautifyResponses": true
        },
        "accountstateInputPath": "hydration"
      },
      "expect": {
        "rawExchangeFieldsPreserved": true,
        "beautifiedResponsesUsedForTrustedState": false,
        "sdkSurfaceNotesOption": true
      }
    }
  ],
  "goldenLogTraces": {
    "manualOpen": [
      {
        "event": "private_ws_event_received",
        "eventType": "ORDER_TRADE_UPDATE",
        "symbolSide": "BTCUSDT:LONG"
      },
      {
        "event": "accountstate_event_applied",
        "positions": 1,
        "activeOrders": 0
      },
      {
        "event": "affected_scope_recorded",
        "symbolSide": "BTCUSDT:LONG"
      },
      {
        "event": "action_family_selected",
        "actionFamily": "protective",
        "intentCount": 2
      },
      {
        "event": "protective_dispatch_started",
        "actionFamily": "protective",
        "intentCount": 2,
        "dispatch": "concurrent_separate_orders"
      },
      {
        "event": "submission_accepted_pending_confirmation",
        "role": "SL",
        "kind": "algo_STOP_MARKET",
        "action": "place"
      },
      {
        "event": "submission_accepted_pending_confirmation",
        "role": "TP",
        "kind": "regular_LIMIT",
        "action": "place"
      },
      {
        "event": "private_ws_confirmation_applied",
        "regularOpenOrders": 1,
        "openAlgoOrders": 1
      },
      {
        "event": "action_family_selected",
        "actionFamily": "dca",
        "intentCount": 1
      },
      {
        "event": "submission_accepted_pending_confirmation",
        "role": "DCA",
        "kind": "regular_LIMIT",
        "action": "place"
      },
      {
        "event": "private_ws_confirmation_applied",
        "regularOpenOrders": 2,
        "openAlgoOrders": 1
      },
      {
        "event": "planner_finished",
        "positions": 1,
        "activeOrders": 3,
        "intentCount": 0
      }
    ],
    "sameSideAdd": [
      {
        "event": "planner_finished",
        "positions": 1,
        "activeOrders": 3,
        "classifier": "keep|amend|cancel_place|cancel|place"
      },
      {
        "event": "slot_classified",
        "role": "SL",
        "action": "amend_or_cancel_place",
        "cancelPlaceOnlyWhen": "current Binance package/docs prove the conditional exit slot cannot be amended or its identity changed"
      },
      {
        "event": "slot_classified",
        "role": "TP",
        "action": "amend_or_cancel_place",
        "cancelPlaceOnlyWhen": "current Binance package/docs prove the regular TP slot cannot be amended or its identity changed"
      },
      {
        "event": "slot_classified",
        "role": "DCA",
        "action": "amend_or_cancel_place",
        "cancelPlaceOnlyWhen": "current Binance package/docs prove the regular order slot cannot be amended or its identity changed"
      },
      {
        "event": "trusted_accountstate_read",
        "after": "protective_action_family",
        "reason": "same_side_add"
      },
      {
        "event": "submission_action_started",
        "actionFamily": "dca",
        "requiresPositionStillOpen": true
      },
      {
        "event": "planner_finished",
        "positions": 1,
        "activeOrders": 3,
        "intentCount": 0
      }
    ],
    "hedgeCoexistence": [
      {
        "event": "action_family_selected",
        "actionFamily": "protective",
        "positions": 1,
        "activeOrders": 0,
        "intentCount": 2,
        "side": "LONG"
      },
      {
        "event": "action_family_selected",
        "actionFamily": "protective",
        "positions": 2,
        "activeOrders": 3,
        "intentCount": 2,
        "side": "SHORT"
      },
      {
        "event": "planner_finished",
        "positions": 2,
        "activeOrders": 6,
        "intentCount": 0
      }
    ]
  },
  "snippets": {
    "privateStartup": "ws.on('exception', (event) => supervisor.onException(event));\nws.on('open', (event) => supervisor.onOpen(event));\nws.on('reconnecting', (event) => supervisor.onReconnecting(event));\nws.on('reconnected', (event) => supervisor.onReconnected(event));\n\nawait adapter.connectPrivateStreams();\n\nconst failed = products.filter((product) => store.getTradingState(product).recoveryRequired);\nif (failed.length > 0) {\n  throw new Error(`Private stream startup failed for products: ${failed.join(',')}`);\n}\n\nawait hydrateAllEnabledProducts();\nawait replayBufferedEvents();\nlogger.info('service_ready', { products });",
    "liveIntentPreflight": "async function submitActionFamilyInsideWorkflow(intents) {\n  const submitIntents = intents.filter((intent) => !intent.blocked);\n  if (submitIntents.length === 0) {\n    logger.info('submission_action_skipped_empty', { intentCount: 0 });\n    return;\n  }\n\n  for (const intent of submitIntents) {\n    orderContextStore.set(intent.clientId, {\n      slotKey: intent.slotKey,\n      role: intent.role,\n      actionFamily: intent.actionFamily,\n      request: summarizeRequest(intent),\n      submittedAt: Date.now(),\n    });\n    if (intent.action === 'place' && pendingConfirmations.has(intent.slotKey)) {\n      throw enterRecoveryRequired('pending_confirmation_guard', { slotKey: intent.slotKey });\n    }\n    if (inFlight.has(intent.clientId)) {\n      throw enterRecoveryRequired('duplicate_or_inflight_client_id', { clientId: intent.clientId });\n    }\n  }\n\n  const canDispatchConcurrently =\n    submitIntents.every((intent) => intent.actionFamily === 'protective' && ['SL', 'TP'].includes(intent.role));\n  const selectedIntents = canDispatchConcurrently ? submitIntents : submitIntents.slice(0, 1);\n\n  if (canDispatchConcurrently) {\n    logger.info('protective_dispatch_started', { intentCount: selectedIntents.length });\n  }\n\n  await Promise.all(selectedIntents.map(async (intent) => {\n    inFlight.add(intent.clientId);\n    try {\n      const response = await exchange.submit(intent);\n      pendingConfirmations.add(intent.slotKey, { intent, response });\n      logger.info('submission_accepted_pending_confirmation', {\n        slotKey: intent.slotKey,\n        role: intent.role,\n        actionFamily: intent.actionFamily,\n        requestDiff: summarizeActionableDiff(intent),\n      });\n    } catch (error) {\n      classifySubmissionFailureOrEnterRecovery(intent, error);\n      throw error;\n    } finally {\n      inFlight.delete(intent.clientId);\n    }\n  }));\n}",
    "orderComparison": "import type { AccountScope, NormalizedOrder } from 'accountstate';\nimport { areBinanceManagedOrdersEquivalent } from 'accountstate/binance';\n\ntype DesiredManagedOrder = {\n  slot: {\n    symbol: string;\n    exchangePositionSide: string;\n    managedSide: 'LONG' | 'SHORT';\n    role: 'TP' | 'SL' | 'DCA';\n    step: number;\n    orderKind: 'regular_LIMIT' | 'algo_STOP_MARKET';\n  };\n  side: 'BUY' | 'SELL';\n  positionSide?: string;\n  quantity?: string;\n  price?: string;\n  triggerPrice?: string;\n  reduceOnly?: boolean;\n  closePosition?: boolean;\n  workingType?: string;\n};\n\nfunction desiredManagedOrderToNormalizedOrder(\n  scope: AccountScope,\n  desired: DesiredManagedOrder,\n  updatedAtMs = 0,\n): NormalizedOrder {\n  const isAlgoStop = desired.slot.orderKind === 'algo_STOP_MARKET';\n\n  return {\n    ...scope,\n    symbol: desired.slot.symbol,\n    kind: isAlgoStop ? 'algo' : 'regular',\n    side: desired.side,\n    type: isAlgoStop ? 'STOP_MARKET' : 'LIMIT',\n    status: 'new',\n    exchangePositionSide: desired.positionSide ?? desired.slot.exchangePositionSide,\n    strategySide: desired.slot.managedSide,\n    quantity: desired.quantity,\n    price: desired.price,\n    triggerPrice: desired.triggerPrice,\n    reduceOnly: desired.reduceOnly,\n    closePosition: desired.closePosition,\n    workingType: desired.workingType,\n    timeInForce: isAlgoStop ? undefined : 'GTC',\n    owner: 'app',\n    metadata: {\n      role: desired.slot.role,\n      step: desired.slot.step,\n      exchangePositionSide: desired.slot.exchangePositionSide,\n      strategySide: desired.slot.managedSide,\n    },\n    updatedAtMs,\n    source: 'local',\n  };\n}\n\nfunction managedOrdersEquivalent(\n  scope: AccountScope,\n  desired: DesiredManagedOrder,\n  active: NormalizedOrder,\n  positionMode: 'one-way' | 'hedge',\n) {\n  return areBinanceManagedOrdersEquivalent({\n    desired: desiredManagedOrderToNormalizedOrder(scope, desired),\n    active,\n    product: 'usdm',\n    positionMode,\n  });\n}",
    "structuredLogger": "function emit(level, eventName, context = {}) {\n  const { event: contextEvent, level: _level, ts: _ts, ...safeContext } = redact(context);\n  const line = {\n    ts: new Date().toISOString(),\n    level,\n    event: eventName,\n    ...safeContext,\n    ...(contextEvent === undefined ? {} : { contextEvent }),\n  };\n  console[level === 'error' ? 'error' : 'log'](JSON.stringify(line));\n}\n\nfunction serializeSdkError(error) {\n  const out = { errorType: typeof error };\n  if (error instanceof Error) {\n    out.name = error.name;\n    out.message = error.message;\n    out.stack = error.stack;\n  }\n  if (error && typeof error === 'object') {\n    out.exchangeCode = error.code;\n    out.exchangeMessage = error.msg;\n    out.message = error.message ?? out.message;\n    if (error.response) {\n      out.httpStatus = error.response.status;\n      out.responseHeaders = error.response.headers;\n      out.responseBody = error.response.data;\n    }\n    if (error.error || error.exception) {\n      out.nested = serializeSdkError(error.error ?? error.exception);\n    }\n  }\n  return redact(out);\n}"
  }
}
