AI Guide Map
Position Management with Binance APIs & WebSockets
Track positions. Hydrate account state at startup/recovery boundaries, listen to private user-data streams, and produce risk-gated DCA, take-profit, and stop-loss intents.
Default Scope
- Runtime: Node.js LTS
- Recommended language: TypeScript
- Package: binance
- Products: selected Binance product groups
- Implement execution for when EXECUTION_MODE=DEMO, TESTNET, or LIVE is enabled and all gates pass, but keep that path disabled by default.
- EXECUTION_MODE=DRY_RUN_PRIVATE is the default local mode for bounded Binance order mutation candidates.
- Credentials: scoped API keys from environment variables only
Resources
Start with the task-specific resources below, then use SDK and exchange docs to verify exact method names, request fields, topics, and product rules.
Start here
Use this short route for the default Binance TP/SL/DCA build path. It keeps the first read focused before opening heavier machine artifacts.
Exchange State Management
Primary spec for accountstate, private events, recovery, confirmations, and workflow ownership.
Binance prompt artifact
Task prompt for the Binance TP/SL/DCA position-manager implementation.
Preferred recipe JSON
Machine-readable build order, invariants, and acceptance gates for this task.
Exact Binance details
Open these when implementation needs exact Binance request fields, event shapes, rejection handling, or SDK method names.
Validation after implementation
A Conformance Pack is a versioned, machine-readable set of behavior-contract fixtures, expected outcomes, and runner requirements for a generated integration. Use conformance packs after the implementation exists as validation sources, not the first design input.
Advanced reusable-runtime material
Use these when generating shared runtime modules, manifests, reusable contracts, or deeper agent scaffolding. They are not the default first-read path.
Implementation Steps
Follow these in order; use the linked artifacts only where they clarify the current step.
1. Follow the simple route
Start from the primary spec, prompt artifact, and recipe. Use integration kits for exact Binance details and behavior-contract fixtures after implementation.
- Read /ai/exchange-state, then /.well-known/prompts/binance-position-manager/latest.md, then /.well-known/recipes/binance-position-manager.json.
- Open the Binance integration kit only when exact fields, event shapes, SDK surfaces, or rejection handling are needed.
- Use these when generating shared runtime modules, manifests, reusable contracts, or deeper agent scaffolding. They are not the default first-read path.
- Use installed binance declarations and current Binance docs for exact method names, request fields, and product limits.
2. Hydrate and listen
REST Hydration seeds Account State. Private user-data streams keep it current after startup.
- Startup hydration loads filters, positions or inputs for local position tracking, open orders, fills or executions, wallet or margin state, account mode, risk/readiness state, and stored contexts.
- Follow the Event-Driven Workflow: During normal private event bursts, apply every event to Account State immediately, then use a short event-burst wait before planning. Do not enter REST recovery just because private order, execution, fill, or position events arrived. If the private stream is healthy and Account State 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.
- Private event routing uses verified product-specific paths from the installed package and Binance docs. Do not assume every product group shares the same private event names or fields.
- 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.
3. Track owned slots
Use Binance Custom Order IDs as lookup keys into Durable Context records.
- Use the Binance SDK order ID utilities for every Custom Order ID field, including newClientOrderId and clientAlgoId. Prefer generateNewOrderId(...) or client.generateNewOrderId(). Use getOrderIdPrefix(...) or client.getOrderIdPrefix() only when building a custom random suffix. Keep the final value inside Binance limits and store all strategy context in the order-context registry.
- Use the selected product surface custom ID field, such as newClientOrderId for regular orders or clientAlgoId where the conditional/Algo surface requires it.
- Store product, symbol, exchange position identity when available, managed side, order side, role, step, order kind, request summary, and pending action in Durable Context before submit; never parse strategy state from the client ID.
4. Choose one action family
One workflow owner follows the Runtime Workflows model: drain one symbol-side scope and choose one action family per pass.
- Each reconciliation pass chooses one 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.
- A fresh managed position places protective SL/TP before exposure-increasing DCA. SL and TP are separate orders and may dispatch concurrently after contexts are registered.
- Accepted place/amend/cancel responses create pending confirmations and duplicate-submit protection, but they do not unlock dependent action families until private confirmation or scoped recovery proves account state.
- RecoveryRequired or syncRequired blocks normal cleanup, protective, DCA, and EXECUTION_MODE=DEMO, TESTNET, or LIVE submission until scoped REST hydration plus buffered replay restores trusted account state. Deterministic stale-target no-ops avoid entering recovery when account state already proves convergence.
5. Apply Binance specifics
Shared runtime modules handle lifecycle behavior. Binance-specific code handles request surfaces, field rules, and rejection handling.
- 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 conditional/Algo orders only for stop-loss, trailing stop, or explicitly requested conditional TP behavior when the selected product supports that surface.
- Hydrate and cancel regular open orders and conditional/Algo open orders through their matching product surfaces.
- In one-way derivatives products, preserve the exchange one-way position identity and infer managed LONG or SHORT from signed position size.
- Treat -5027 as amend-only and equivalent-slot-gated; -2011/-2013 require private terminal proof or scoped REST absence; -2027/-2019 block DCA without marking accountstate untrusted; -5029 is deterministic filter evidence with role-specific planner handling.
- Converge app-owned orders by actionable slot fields, not raw exchange echo equality or client ID drift.
Runtime sequence
Keep these transitions visible in logs and tests.
- Load config, credentials, product scope, and EXECUTION_MODE; use EXECUTION_MODE=DRY_RUN_PRIVATE for order-capable local runs.
- Startup hydration loads filters, positions or inputs for local position tracking, open orders, fills or executions, wallet or margin state, account mode, risk/readiness state, and stored contexts.
- Load Durable Context and classify app-owned orders from stored context plus Trusted State.
- Subscribe to private user-data streams and replay buffered events before management readiness.
- Drain affected symbol-side scopes through one workflow owner and one action family per pass.
- Submit cleanup, protective, or DCA in separate action-family passes; never unlock DCA from REST acceptance alone.
- On timeout, network uncertainty, reconnect, conflict, or sync-required state, run Scoped Recovery, replay buffered events, then replan.
Product-specific private eventsReference
Current futures-formatted fixtures include these paths.
- Build product-specific routing tables from installed declarations before handling private events. Do not assume all Binance product groups share the same event names or field paths.
- For futures-formatted ORDER_TRADE_UPDATE, classify regular order updates from order.clientOrderId, order.symbol, order.positionSide, order.executionType, and order.orderStatus.
- For futures-formatted ALGO_UPDATE, classify conditional order updates from algoOrder.clientAlgoId, algoOrder.symbol, algoOrder.positionSide, algoOrder.orderType, and algoOrder.algoStatus.
- For futures-formatted TRADE_LITE, classify fills from top-level clientOrderId, symbol, side, lastFilledPrice, and lastFilledQuantity. Because this event has no positionSide field, use registry context or mark the symbol broadly until position evidence resolves the side.
- For futures-formatted ACCOUNT_UPDATE, treat updateData.updatedPositions[] rows as position evidence, using symbol, positionSide, positionAmount, and entryPrice.
- If a formatted event lacks the required path needed to clear a pending confirmation or identify a slot, enter scoped recovery instead of changing an unidentified slot.
Local test setReference
After implementation, run the applicable behavior-contract fixtures locally before enabling EXECUTION_MODE=DEMO, TESTNET, or LIVE submission. conformance packs are the machine-readable fixture sources for these checks.
- Use /.well-known/conformance/exchange-state-management/latest.json for reusable workflow fixtures.
- Use /.well-known/conformance/binance-position-manager/latest.json for Binance request, stream, and rejection fixtures.
- Required Binance behavior-contract fixtures cover startup wipe/rebuild, fixed TP regular LIMIT, formatted private event paths, benign terminal cancel races, DCA risk blocks, amend no-op convergence, and leverage limits. Use the fixture list for exact names.
- Keep EXECUTION_MODE=DEMO, TESTNET, or LIVE submission disabled until startup hydration, private confirmation races, pending-confirmation gating, recovery hydration, protective SL/TP, stale-target races, and Binance rejection handling pass locally.
Manager invariants
- Use EXECUTION_MODE=DRY_RUN_PRIVATE for order-capable local runs.
- The manager never cancels or amends orders that are not app-owned orders unless manual-order takeover is explicitly configured.
- Managed Binance IDs follow the Custom Order ID rule.
- Formatted Binance private events route by verified product-specific field paths, not assumed root fields.
- REST acceptance does not unlock dependent action families until Private Stream Confirmation or Scoped Recovery confirms Account State.
- RecoveryRequired or syncRequired blocks normal cleanup, protective, DCA, and EXECUTION_MODE=DEMO, TESTNET, or LIVE submission until scoped REST hydration plus buffered replay restores trusted account state. Deterministic stale-target no-ops avoid entering recovery when account state already proves convergence.
- A fresh managed position places protective SL/TP before exposure-increasing DCA. SL and TP are separate orders and may dispatch concurrently after contexts are registered.
- 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.
- Convergence compares actionable slot fields, not raw exchange echoes or client ID drift.