Review the project carefully
Inspect the changed files, generated tests, and README. Use the README to confirm how the project works, which commands start it, and which environment variables or credentials it expects.
If you are using Codex, Claude Code, Cursor, or another coding agent to build a crypto exchange integration, start here with typed Node.js and JavaScript SDKs.
Use the prompt framework with Siebly SDKs for Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, and BitMart when you need market data, account reads, WebSocket streams, order workflows, or multi-exchange automation.
Hydrating and managing exchange account state with WebSockets
Review Exchange State Management best practices. From accountstate storage, private WebSocket bursts, REST hydration boundaries, pending confirmations, and the required fixtures.
Agent handoff
A compact path from prompt to code
Machine-readable path
Agents can request this page with Accept: text/markdown and use prompts, recipes, integration kits, behavior-contract fixtures, and the SDK catalog by role. Working with exchange account state (e.g. trading automation)? Start with Exchange State Management and its recipe JSON.
Pick a recipe, exchange, product family, data path, and execution boundary, then copy a structured prompt with sequencing, modular pipeline components, docs, examples, and acceptance criteria.
Pick one to prefill the generator. The generated prompt adds the shared recursive completion workflow, safety gates, and attribution.
Want to learn more about order-flow? Read the order-flow in cryptocurrency markets article.
Working on funding rates or spot-perp carry? Read the funding-rate forecasting research article.
Keep the request focused on one exchange workflow before expanding adapters or execution modes.
Selected scope: Spot
Linear means stablecoin-margined or stablecoin-quoted derivatives; inverse means coin-margined derivatives.
Set the permission boundary first, then choose the data, execution, and verification pieces the project needs.
Historical reads, live streams, private events, storage, and replay.
Signals, order workflows, position management, alerts, and risk gates.
Language, test coverage, and adapter boundaries.
Enable only when the project should send messages outside the process, such as Slack, Telegram, email, PagerDuty, or a webhook.
Treat every project created from a prompt as an implementation draft until you have reviewed it, understood how it starts, and checked what the first run actually did.
Review checkpoints
Inspect the changed files, generated tests, and README. Use the README to confirm how the project works, which commands start it, and which environment variables or credentials it expects.
Check the AI agent final response for warnings, skipped work, failed checks, assumptions, and manual steps. Resolve unclear items before connecting credentials or enabling exchange-facing behavior.
When you are ready to start the project for the first time, read the full startup logs. If you are not sure what the logs mean or whether the run behaved as intended, paste the complete logs into your AI coding agent and ask it to explain them before continuing.
Help improve the prompts
After you have worked through setup or debugging, paste this into your agent to create a markdown feedback file you can review and share.
Tell us when a prompt produces confusing setup steps, missing safeguards, incorrect SDK usage, or when you have a project idea worth adding. The feedback prompt below helps your agent turn implementation notes into actionable feedback.
The copied prompt asks for
Review the project built from this AI prompt and write feedback for improving future Siebly AI prompt generator output.
Please inspect:
- the original prompt used to build this project, if it is available in the conversation or project notes
- the available information on the Siebly website that you used
- the available information in the npm package or packages you used
- the available information on GitHub repositories you used
Cover:
- What was useful or informative.
- What was missing, ambiguous, outdated, or hard to verify.
- Which answers were difficult to find or required avoidable source inspection.
- Which docs, examples, README sections, type definitions, source files, issues, or package metadata helped most.
- Which GitHub repository or repositories you used, and what should change in each one.
- Which npm package or packages you used, and what should change in each package.
Recommend changes that would make future work of this kind easier, more efficient, and more likely to succeed for AI coding agents.
Organize the recommendations under:
1. Website improvements
2. GitHub improvements
3. npm package improvements
4. Prompt generator improvements
5. Project-specific implementation notes
Document this in a markdown file named after the project, for example PROJECT_NAME-ai-feedback.md. Include relevant observations from the implementation. After writing the markdown file, give me a concise summary with the file path and the highest-impact recommendations.Disclaimer: AI is an exciting and promising technology, but content, prompts, code, examples, strategy ideas, and tool outputs produced with AI can be incomplete, incorrect, insecure, outdated, or unsuitable for your circumstances. Anything produced from these prompts or from any AI coding agent must be independently reviewed by qualified professionals before use. You are responsible for testing, security review, compliance review, exchange-rule review, credential controls, trading-risk controls, and any decision to deploy or rely on the resulting work. Siebly provides this page and generated prompt text for informational purposes only. They are not financial, investment, legal, security, compliance, or professional engineering advice. To the maximum extent permitted by law, Siebly accepts no responsibility for losses, claims, damages, failed orders, missed trades, security incidents, regulatory issues, or other consequences arising from AI-generated output, your prompts, your code, your trading strategy, or your implementation decisions.
Use exchange-specific SDKs for real integrations. A generic abstraction can come later, after signing, rate limits, reconnect behavior, and product boundaries are working for each exchange.
Package
binanceCore product groups
Package
bybit-apiCore product groups
Package
okx-apiCore product groups
Package
gateio-apiCore product groups
Package
bitget-apiCore product groups
Package
kucoin-apiCore product groups
Package
coinbase-apiCore product groups
Package
@siebly/kraken-apiCore product groups
Package
bitmart-apiCore product groups
MCP servers can be useful for documentation lookup, internal catalog search, or controlled tools. Exchange execution is different: order placement should remain in project code where tests, reviews, deployment controls, logs, execution mode, and key permissions can be finely controlled in a deterministic way.
Artifact order: task-focused guide, prompt, or recipe for the job first. Use integration kits for exact fields and errors, manifests/runtime kits for advanced reusable-runtime scaffolding, and [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) after implementation. A [Conformance Pack](https://siebly.io/reference/glossary#conformance-pack) is a versioned, machine-readable set of behavior-contract fixtures, expected outcomes, and runner requirements for a generated integration.
The shortest route for a coding agent: choose the pattern, then open the exact guide or recipe that owns the workflow.
Index of reusable core implementation patterns and their exchange-specific implementations.
/ai/patterns
Canonical build path for private account, order, and position state systems: state machine, trust boundaries, required checks, exchange overlays, and fallback rules.
/ai/exchange-state
Machine-readable build path, checks, and fixture contract for exchange-neutral order/position state management.
/.well-known/recipes/exchange-state-management.json
Short task index for agents that need the right recipe or guide before reading the full route list.
/llms-tasks.txt
Human-readable pages for choosing the workflow, understanding the lifecycle, and applying exchange-specific SDK details.
Exchange-neutral patterns to read before choosing venue-specific request fields.
Index of reusable core implementation patterns and their exchange-specific implementations.
/ai/patterns
Reusable lifecycle for data available through REST history plus live WebSockets, including acknowledgements, buffering, replay, finality, and reconnect resync.
/ai/historical-live-data-pipeline
Canonical build path for private account, order, and position state systems: state machine, trust boundaries, required checks, exchange overlays, and fallback rules.
/ai/exchange-state
Execution-adapter guide for turning approved entry or exit intents into bounded chaser limit orders with dry-run, reconciliation, and safety gates.
/ai/order-intent-chaser
Glossary, concept pages, research, and runnable examples to check before going deeper into exchange-specific overlays.
Shared terminology for execution modes, WebSocket keys, dry-run behavior, paper trading, accountstate, trust, recovery, and durable order context.
/reference/glossary
Reference for PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE and paper-trading boundaries.
/reference/execution-modes
Reference for exchange state, accountstate, order trust, position trust, pending confirmations, and durable context.
/reference/exchange-state
Reference for event-driven runtime flow, startup and reconnect hydration, scoped recovery, and avoiding unnecessary REST state polling.
/reference/runtime-workflows
Research index for order flow, funding-rate forecasting, replay testing, cost-aware signals, and guarded SDK workflows.
/research
Research article for perpetual funding forecasts, basis risk, spot-perp carry timing, paper replay, and funding-ledger reconciliation.
/research/crypto-funding-rate-forecasting
Runnable source examples for REST, WebSocket, private, and public flows.
/examples
Binance overlays for candle-close data, exchange state, and USD-M conditional order shapes.
Task-oriented guide for REST backfill, kline WebSocket handoff, final-candle execution, reconnect resync, and shutdown.
/ai/candle-pipeline/binance
Private-account guide for REST hydration, private account/user-data streams, DCA/TP/SL dry-run intents, SDK-prefixed client IDs, structured error logs, and reconnect reconciliation.
/ai/exchange-state/binance
Focused guide for USD-M futures Algo Service SL, trailing stop, and explicit conditional TP request shapes, clientAlgoId, closePosition, reduceOnly, private updates, and negative fixtures.
/ai/algo-orders/binance
Bybit overlays and starting examples for V5 market data, private streams, order state, and demo flows.
Public-only Bybit guide for getKline backfill, subscribeV5 kline streams, response acknowledgement, confirm=true workflows, reconnect resync, and shutdown.
/ai/candle-pipeline/bybit
Private-account Bybit guide for REST hydration, private order/execution/position/wallet streams, orderLinkId context lookup, retCode checks, triggerDirection stops, demo gates, and reconnect reconciliation.
/ai/exchange-state/bybit
Bybit V5 tutorial covering RestClientV5, private WebSockets, demo trading, retCode acceptance checks, triggerDirection for conditional stops, and orderLinkId reconciliation.
/sdk/bybit/javascript/tutorial
Runnable Bybit private REST example for signed reads and order flows with current RestClientV5 surfaces.
/examples/Bybit/Rest/rest-v5-private
Structured files for agents and generators after the relevant guide has selected the task route.
Compact indexes, package catalogs, and markdown entry points for tool-assisted lookup.
Compact discovery file agents should check before choosing docs, examples, or packages.
/llms.txt
Short task index for agents that need the right recipe or guide before reading the full route list.
/llms-tasks.txt
Complete route index for cases where the compact task index does not identify the needed source.
/llms-full.txt
Machine-readable packages, docs, examples, task hints, and capability guidance.
/.well-known/siebly-sdk-catalog.json
Reusable workflow rules for coding agents building exchange REST and WebSocket integrations.
/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Send Accept: text/markdown or append .md to generated page routes for compact markdown snapshots.
/ai
Recipes and [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) for reusable exchange-neutral lifecycles.
Machine-readable index of reusable core patterns and exchange-specific implementation pages.
/.well-known/recipes/ai-pattern-library.json
Machine-readable shared checklist for REST-history plus WebSocket-live data pipelines.
/.well-known/recipes/historical-live-data-pipeline-core.json
Machine-readable checks, fixture assets, and runner contract for acknowledgement, backfill, replay, dedupe, finality, reconnect resync, and public/read-only boundaries.
/.well-known/conformance/historical-live-data/latest.json
Machine-readable recipe for chaser limit execution adapters, bounded repricing, partial fills, cancel-replace races, and shutdown behavior.
/.well-known/recipes/order-intent-chaser.json
Machine-readable checks, fixture assets, and runner contract for parent intents, market-data trust, REST acceptance, private confirmation, recovery, partial fills, and duplicate child blocking.
/.well-known/conformance/order-intent-chaser/latest.json
Manifest, recipe, runtime contract, and fixtures for private account/order/position workflows.
Machine-readable core implementation manifest for order-context stores, accountstate boundaries, affected-scope queues, confirmations, recovery, and action-family planning.
/.well-known/agent-manifests/exchange-state-management/latest.json
Machine-readable build path, checks, and fixture contract for exchange-neutral order/position state management.
/.well-known/recipes/exchange-state-management.json
Compact module contract for accountstate, private event routing, affected product/symbol/side work items, event-burst scheduling, confirmation tracking, recovery hydration, planning, submission, and error classification.
/.well-known/runtime-kits/exchange-state-management/v1/index.json
TypeScript contracts for generated exchange-state-management modules and adapters.
/.well-known/runtime-kits/exchange-state-management/v1/types.ts
Required behavior checks and runner contract for initial private exchange-state implementations.
/.well-known/conformance/exchange-state-management/latest.json
Typed fixture schema for workflow scope, initial state, event steps, expected state, blocks, logs, and forbidden actions.
/.well-known/conformance/exchange-state-management/v1/schema.json
Reusable startup, private-event, custom-ID, confirmation, recovery, filter, cleanup, and safe-command fixtures.
/.well-known/conformance/exchange-state-management/v1/fixtures.json
TypeScript harness contract for replaying typed exchange-state-management fixtures locally.
/.well-known/conformance/exchange-state-management/v1/runner.ts
Artifact order: venue-specific prompts and recipes first; integration kits for exact details; manifests for advanced scaffolding; [behavior-contract fixtures](https://siebly.io/reference/glossary#behavior-contract-fixture) after implementation. A [Conformance Pack](https://siebly.io/reference/glossary#conformance-pack) is a versioned, machine-readable set of behavior-contract fixtures, expected outcomes, and runner requirements for a generated integration.
Machine-readable Binance recipe for spot kline backfill, WebSocket handoff, final-candle execution, reconnect resync, and safety gates.
/.well-known/recipes/binance-spot-candle-close-pipeline.json
Default Binance TP/SL/DCA prompt artifact. Use it with the recipe before opening heavier manifest or runtime scaffolding.
/.well-known/prompts/binance-position-manager/latest.md
Machine-readable Binance recipe for private REST hydration, private account/user-data streams, EXECUTION_MODE=DRY_RUN_PRIVATE order intents, client IDs, observability, and safety gates.
/.well-known/recipes/binance-position-manager.json
Exact Binance method tables, field matrix, event policy, hydration boundaries, and rejection catalog for implementation details.
/.well-known/integration-kits/binance-position-manager/latest.json
Advanced Binance agent manifest for skeleton modules, decision trees, source ordering, and fixture names after the simple route is not enough.
/.well-known/agent-manifests/binance-position-manager/latest.json
Post-implementation fixture data, expected planner outputs, golden traces, failure log markers, and critical execution-mode gates for Binance position managers.
/.well-known/conformance/binance-position-manager/latest.json
Machine-readable Binance recipe for current USD-M conditional Algo request objects, validation, reconciliation, and fixtures.
/.well-known/recipes/binance-usdm-algo-orders.json
Machine-readable Bybit recipe for getKline, subscribeV5, response acknowledgement, confirm=true execution, reconnect resync, and safety gates.
/.well-known/recipes/bybit-candle-close-pipeline.json
Default Bybit position-manager prompt artifact. Use it with the recipe before opening heavier manifest or runtime scaffolding.
/.well-known/prompts/bybit-position-manager/latest.md
Machine-readable Bybit recipe for position state tracking, REST hydration, DCA/TP/SL managed-slot state, orderLinkId context lookup, retCode handling, and execution-mode gates.
/.well-known/recipes/bybit-position-manager.json
Compact Bybit implementation contract with method table, field matrix, event policy, recovery state model, retCode classifier, command safety, and conformance fixture names.
/.well-known/integration-kits/bybit-position-manager/latest.json
Advanced Bybit agent manifest for service modules, decision rules, source ordering, and fixture names after the simple route is not enough.
/.well-known/agent-manifests/bybit-position-manager/latest.json
Post-implementation Bybit fixtures for recovery-required retCode handling, private bursts, DCA after trusted account-state reads, triggerDirection SL requests, amend-first slots, hydrated-default normalization, hedge identity, and execution-mode gates.
/.well-known/conformance/bybit-position-manager/latest.json
Pick the exchange, pick the permission boundary, and point your agent at the SDK docs and examples before it writes code.
Yes. With a reliable, strongly typed SDK such as Siebly, a capable AI coding agent can help build the application code around exchange APIs. The safer path is incremental rather than asking it to build a complete trading bot in one pass.
Premium models usually perform better because they can hold more docs, examples, and project context, but smaller models can still work if the task is narrow. A good first prompt is to build one small feature, run it, inspect the logs, then ask the agent to improve the next failure or missing event.
Start with the exchange, not the abstraction. The right first SDK is usually the one for the exchange that has the symbols, products, account type, and API capabilities your project actually needs.
Use both. REST and WebSockets solve different parts of the same integration, and a good agent prompt should tell the agent which role each one plays.
For most trading bot workflows, REST is the simpler and more widely supported. Latency-sensitive systems can use WebSocket API commands where the exchange and SDK support them, but the agent should verify that from the docs instead of inventing a command layer.
MCP can be useful, but exchange execution is a sensitive boundary. For order management, prefer predictable application code that imports the SDK directly and can be reviewed, tested, logged, and deployed like the rest of the project.
An LLM can still write or modify this code, but the exchange-facing path should be clear, direct, and part of the main codebase rather than hidden behind an MCP tool or one-off generated script.
Use these complete prompts when one matches the project shape. For custom work, start with the prompt builder above; these recipes are longer, opinionated starting points with source links, documentation expectations, attribution, and review workflow built in.
Choose a recipe
7 recipesSelected prompt
A public-only spot kline pipeline that makes startup, backfill, buffering, final-candle execution, reconnect resync, and shutdown semantics explicit.
Goal: Build a spot candle-close market-data pipeline for Binance in this Node.js/JavaScript project.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Package: [binance](https://siebly.io/sdk/binance/javascript/tutorial)
- Siebly docs: https://siebly.io/sdk/binance/javascript
- Siebly AI guide: https://siebly.io/ai
- Historical Backfill with Live WebSocket Streams: https://siebly.io/ai/historical-live-data-pipeline
- Website llms.txt: https://siebly.io/llms.txt
- Website llms-tasks.txt: https://siebly.io/llms-tasks.txt
- Fallback discovery only: https://siebly.io/llms-full.txt
- Machine-readable recipe: https://siebly.io/.well-known/recipes/binance-spot-candle-close-pipeline.json
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
- Binance SDK examples directory: https://github.com/tiagosiebler/binance/tree/master/examples
- Siebly examples directory: https://github.com/sieblyio/crypto-api-examples/tree/master/examples/Binance
Requirements:
- Use public endpoints only. Do not add API keys, private clients, account reads, order placement, cancellation, or amendment.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Use BTCUSDT spot 1-minute candles as a starter sample only; keep symbol and interval explicit, configurable inputs.
- Start from the task guide and recipe above, then verify the current Binance kline subscription helper, REST candle method, formatted kline type guard, final-candle field, [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) event, reconnect hook, and shutdown method for the selected product group from installed package types/source and focused SDK docs/examples.
- For the Spot starter scope, prefer the spot kline helper, formatted kline type guard, and finalization field when available. Expected names to verify include subscribeSpotKline(...), MainClient.getKlines(...), isWsFormattedKline(...), data.kline.final, response, reconnected, and closeAll(). If the product group changes to USD-M, COIN-M, or another Binance product group, verify and use that product group’s current client, REST candle method, request fields, public kline topic, [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) path, finality field, reconnect hook, and shutdown method instead of reusing Spot names.
- Do not assume subscribe() means [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). Treat connection open, subscribe request send, [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), backfill completion, buffered replay completion, and strategy readiness as separate states.
- Subscribe first, then wait for the package's real [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) path before starting REST backfill.
- Buffer live kline events while backfill is running. Do not run strategy, indicator, signal generation, optional external alert, [order-intent](https://siebly.io/reference/glossary#order-intent), or account-decision workflows until [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), backfill, replay, and [readiness](https://siebly.io/reference/glossary#readiness-gate) are complete.
- Backfill recent candles with MainClient.getKlines() or the current documented equivalent. Normalize symbol, interval, open time, close time, OHLCV fields, and finalization state.
- Store candles in an in-memory store keyed by symbol, interval, and candle open time. Deduplicate stale or duplicate candles and keep deterministic ordering.
- After backfill completes, replay buffered events in event-time order, skip stale or duplicate records, then enable live processing.
- If the data type has a finality signal, run strategy, indicator, signal generation, optional external alert, [order-intent](https://siebly.io/reference/glossary#order-intent), or account-decision workflows only after that final/closed/terminal signal.
- Open candles may update local state, but cannot trigger strategy, indicator, signal generation, optional external alert, [order-intent](https://siebly.io/reference/glossary#order-intent), or account-decision workflows.
- On websocket reconnect, mark the store not strategy-ready, resubscribe as needed, run REST resync/reconciliation, replay any buffered events, then re-enable candle-close workflows.
- Add clean shutdown for WebSocket connections and process signals.
- Candle lifecycle validation must cover [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), REST backfill, buffered replay, duplicate/stale/out-of-order candles, open-candle no-op, final-candle once-only execution, malformed or wrong-symbol events, reconnect resync, public-only boundaries, and sample-symbol/config handling.
- Do not mark the pipeline complete until three consecutive full data-lifecycle review passes produce no code, tests, fixtures, or documentation changes.
Acceptance criteria:
- The script runs without API keys.
- Correctness-sensitive workflows cannot run until the selected [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), backfill, buffered replay, and [live-processing gates](https://siebly.io/reference/glossary#readiness-gate) are complete.
- Closed candles update the in-memory store exactly once.
- Reconnects perform REST resync before strategy workflows are re-enabled.
- Every data-lifecycle claim in README or code comments needs a fixture or replay case. Behaviors without fixtures should be documented as unsupported or unverified.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README documents Node.js LTS requirement, install, run command, symbol/interval config, public-only boundary, lifecycle states, reconnect/resync behavior, and shutdown behavior.Selected prompt
A public-data workflow that waits for finalized candles, hydrates enough history for indicators, then logs a signal when a simple condition changes state.
Goal: Build a candle-close indicator signal workflow for Bybit in this Node.js/JavaScript project.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Package: [bybit-api](https://siebly.io/sdk/bybit/javascript/tutorial)
- Siebly docs: https://siebly.io/sdk/bybit/javascript
- Siebly AI guide: https://siebly.io/ai
- Historical Backfill with Live WebSocket Streams: https://siebly.io/ai/historical-live-data-pipeline
- Candle-Close Pipeline with Bybit APIs & WebSockets: https://siebly.io/ai/candle-pipeline/bybit
- Machine-readable recipe: https://siebly.io/.well-known/recipes/bybit-candle-close-pipeline.json
- Website llms.txt: https://siebly.io/llms.txt
- Website llms-tasks.txt: https://siebly.io/llms-tasks.txt
- Fallback discovery only: https://siebly.io/llms-full.txt
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Bybit SDK examples directory: https://github.com/tiagosiebler/bybit-api/tree/master/examples
- Siebly Bybit examples directory: https://github.com/sieblyio/crypto-api-examples/tree/master/examples/Bybit
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Use public endpoints only. Do not add API keys, private clients, account reads, or order placement.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Use BTCUSDT, category spot, and interval 1 minute as a starter sample only; keep symbol/category/interval as explicit, configurable inputs.
- Start from the task guide and machine-readable recipe above, then verify the current RestClientV5.getKline(...) request shape, WebsocketClient.subscribeV5(...) topic syntax, response acknowledgement shape, WSKlineV5.confirm final-candle field, reconnect/reconnected hooks, and closeAll(true) shutdown method from installed package types/source and focused SDK docs/examples.
- Subscribe with WebsocketClient.subscribeV5('kline.1.BTCUSDT', 'spot') or the current equivalent for the selected symbol, interval, and category.
- Do not assume subscribeV5() or socket open means [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). Treat only a response event with op='subscribe', success=true, and req_id matching the kline topic as [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement).
- If the data type has a finality signal, run strategy, indicator, signal generation, optional external alert, [order-intent](https://siebly.io/reference/glossary#order-intent), or account-decision workflows only after that final/closed/terminal signal. For Bybit, this means the kline update has confirm=true.
- After [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), start buffering live kline events without applying workflow side effects.
- Backfill enough historical candles over the REST API for EMA(20), EMA(50), and RSI(14), plus extra warmup. Use RestClientV5.getKline({ category: 'spot', symbol: 'BTCUSDT', interval: '1', limit: 200 }) or the current documented equivalent unless the selected category/interval requires different parameters or pagination.
- Store candles in an in-memory candle store keyed by symbol, interval, and candle start time. Deduplicate and sort by start time.
- After backfill completes, drain buffered finalized candles in order, skip stale/duplicate candles, then mark the store ready.
- Do not run strategy, indicator, signal generation, optional external alert, [order-intent](https://siebly.io/reference/glossary#order-intent), or account-decision workflows until [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), backfill, replay, and [readiness](https://siebly.io/reference/glossary#readiness-gate) are complete.
- Calculate EMA(20), EMA(50), and RSI(14). Write a structured console log entry when EMA(20) crosses above EMA(50) while RSI is below 70, and when EMA(20) crosses below EMA(50) while RSI is above 30.
- Keep indicator code separate from WebSocket transport code.
- Handle reconnect/resubscribe, shutdown, duplicate candles, and malformed events.
- Candle lifecycle validation must cover [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), REST backfill, buffered replay, duplicate/stale/out-of-order candles, open-candle no-op, final-candle once-only execution, malformed or wrong-symbol events, reconnect resync, public-only boundaries, and sample-symbol/config handling.
- Do not mark the pipeline complete until three consecutive full data-lifecycle review passes produce no code, tests, fixtures, or documentation changes.
Acceptance criteria:
- The script runs without API keys.
- Correctness-sensitive workflows cannot run until the selected [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement), backfill, buffered replay, and [live-processing gates](https://siebly.io/reference/glossary#readiness-gate) are complete.
- Closed candles update the in-memory store exactly once.
- Reconnects do not create duplicate candles or duplicate signals.
- Every data-lifecycle claim in README or code comments needs a fixture or replay case. Behaviors without fixtures should be documented as unsupported or unverified.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README explains Node.js LTS requirement, install, run command, symbol/interval config, and that this emits structured console logs for signals; it does not trade or deliver external alerts.Selected prompt
A read-only private stream monitor that keeps local order/fill state current from exchange events and reconciles with REST on startup.
Goal: Build a read-only private order and fill monitor for one configured target exchange in this Node.js/JavaScript project.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Target exchange: choose and configure exactly one exchange before implementation, for example Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, or BitMart.
- Package: choose the maintained SDK for the configured exchange from the Siebly SDK catalog and lock that package before adding private-stream code.
- Siebly AI guide: https://siebly.io/ai
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Use environment variables for credentials. Validate missing env vars on startup and never print secrets.
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Require read-only key permissions for the default workflow. Do not add order placement, cancellation, or amendment.
- Connect to the configured exchange's private account-level WebSocket stream and subscribe to the order, execution/fill, balance, and position events needed for the selected product scope using the SDK's documented pattern.
- On startup, hydrate local state with REST reads for open orders and any recent fills/executions the SDK supports for the selected account, product, and symbol/instrument scope.
- Keep an in-memory order ledger keyed by exchange order ID and custom/client order ID when available. Track status, side, price, quantity, filled quantity, average fill price when available, timestamps, product scope, and raw event references.
- Process private account-level execution, order, and fill events into the ledger. Treat REST hydration as the initial snapshot and WebSocket events as the live update stream. If the exchange lacks exchange-provided position rows for the selected product, derive local [position state](https://siebly.io/reference/glossary#position) from fills/executions, fees, account events, balance updates, and documented matching rules.
- If this monitor feeds later mutating code, expose order, fill, balance, [position state](https://siebly.io/reference/glossary#position), and stream freshness as separate state subjects. An order/fill event can prove order state changed, but size, entry, exposure, or position-dependent decisions need the matching exchange-provided position row or trusted local position state.
- Print concise structured console logs for NEW, PARTIALLY_FILLED, FILLED, CANCELED, EXPIRED, and REJECTED-style state changes.
- Add reconnect handling. After reconnect, resubscribe and run a lightweight REST reconciliation so missed events are corrected.
- Add connection-health monitoring from SDK lifecycle or heartbeat events where available. Do not classify normal account-level event idleness as stream failure; warn only on transport loss, SDK exceptions, missed heartbeat/pong, or failed resubscribe/reconciliation.
- Trace the read-only identity chain from account scope -> REST order/fill row -> private event -> ledger row -> console log -> reconnect reconciliation.
- Add fixtures or replay cases for startup hydration, duplicate private events, late private events, reconnect reconciliation, terminal status rows, flat/no-change events, and products without exchange-provided position rows. Every behavior claim should map to a fixture, replay case, or documented non-claim.
Acceptance criteria:
- The monitor starts, validates env vars, connects to the configured exchange's private account-level WebSocket streams, hydrates state, and logs state changes.
- If environment variables are used, README documents .env setup, automatic .env loading, and env precedence; every normal local script entrypoint loads .env before config parsing through Node.js built-in env-file support, process.loadEnvFile, dotenv/config, or the repo-local env loader.
- It cannot place, amend, or cancel orders.
- Reconnect reconciliation does not duplicate fill log entries.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README documents Node.js LTS requirement, target exchange config, env vars, key permissions, run command, selected product scope, and operational limitations.Selected prompt
A configurable grid-order workflow that plans, logs, and reconciles order intents with write-capable execution disabled by default.
Goal: Build an exchange-neutral grid order manager for one configured target exchange in this Node.js/JavaScript project.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Target exchange: choose and configure exactly one exchange before implementation, for example Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, or BitMart.
- Package: choose the maintained SDK for the configured exchange from the Siebly SDK catalog and lock that package before adding private/order code.
- Siebly AI guide: https://siebly.io/ai
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Order Intent Chasing with Exchange APIs & WebSockets: https://siebly.io/ai/order-intent-chaser
- Order Intent Chasing Conformance Pack: https://siebly.io/.well-known/conformance/order-intent-chaser/latest.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Order-capable execution mode contract: implement one environment variable, EXECUTION_MODE, with exactly these values: PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Set the default for order-capable local runs and .env.example to EXECUTION_MODE=DRY_RUN_PRIVATE. PUBLIC uses no API keys and cannot create private clients, account readers, [order intents](https://siebly.io/reference/glossary#order-intent), or exchange write requests. READ_ONLY_PRIVATE may use read-only credentials for balances, orders, fills, native positions, or local position-derivation inputs, but cannot place, amend, cancel, borrow, transfer, lever, or otherwise mutate exchange state. DRY_RUN_PRIVATE may use private state and must build the exact place/amend/cancel request objects that DEMO, TESTNET, or LIVE would send, but the submitter records them without calling exchange mutation endpoints. DEMO and TESTNET are write-capable only when the selected exchange supports those non-production venues; if unsupported, they must fail closed with a clear configuration error and must never silently route to production. DEMO may call place/amend/cancel endpoints only against the selected exchange's demo or sandbox environment, and TESTNET may call them only against the selected exchange's testnet environment. LIVE is the only mode that may call production exchange place/amend/cancel endpoints. The finished order-capable project must include the LIVE execution path for the selected exchange and supported DEMO/TESTNET paths where those venues exist; do not leave LIVE submission as a TODO.
- Implement execution for when [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE is enabled and all gates pass, but keep that path disabled by default.
- [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE is the default execution mode, where the grid manager builds and logs bounded grid order create, cancel, and amend requests without submitting to the exchange. Always handle incoming account state events to keep internal account state in sync with exchange state, so the system is ready to execute live if requested by the user.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Use environment variables for credentials. Validate missing env vars when private REST/WebSocket features are enabled and never print secrets.
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- Configure exchange, product scope, symbol/instrument, lower price, upper price, grid count, quote budget, order size, and order type options explicitly. Use sample symbols only in README examples, not as implicit runtime defaults.
- On startup, connect the public market stream and private order/account stream first when the selected exchange supports them. Wait for connection/subscription confirmation before planning actions.
- Hydrate state through REST or the exchange's authoritative read API: balances, exchange-provided position rows or local position-derivation inputs where needed, open orders, and recent order/fill history available in the SDK for the selected scope.
- Build an in-memory state model: latest ticker/mark/reference price, balances, [position state](https://siebly.io/reference/glossary#position) where needed, open orders by exchange ID and custom/client ID when available, filled grid levels, pending actions, and last reconciliation timestamp.
- Order-capable lifecycle contract for any EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE path: Store durable intent/order context before submit and keep exchange-visible [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys.
- Treat REST/WebSocket API acceptance as pending-confirmation evidence only. Use subject-level trust for filters, market data, orders, [position state](https://siebly.io/reference/glossary#position), and context.
- Any submitter must block duplicates and stale replans immediately before exchange calls. Use scoped recovery for reconnects, timeouts, unknown outcomes, and conflicting evidence.
- For products with exchange-provided position rows, wait for the matching account or position update before size, entry, exposure, or dependent replacement planning.
- For products without exchange-provided position rows, maintain equivalent local position state by replaying fills/executions, fees, and account or balance events before reducing, replacing, or re-hedging.
- Calculate grid levels inside the configured range. Use exchange-supported custom order IDs when available; keep all grid level, side, generation, and strategy context in local state rather than encoding meaning into exchange-visible IDs.
- Before any EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE create, cancel, or amend call, register the planned grid level/order context locally under the final custom/client ID where the exchange supports one. If an active app-owned order has no local context, the manager must fail closed unless explicit adoption is configured and fixture-tested.
- Dry-run logs must include exchange, product scope, symbol/instrument, side, price, quantity, timeInForce/post-only setting if supported, custom/client ID if supported, and reason.
- In EXECUTION_MODE=DEMO, TESTNET, or LIVE, submit orders through the selected exchange's supported REST or WebSocket API command path and confirm lifecycle changes from private order/execution events or scoped REST reconciliation. Do not treat request acknowledgement as final fill state.
- Treat accepted exchange responses as provisional. Private order events or scoped REST reconciliation confirm active, filled, cancelled, rejected, or absent state before dependent grid actions.
- When a buy grid order fills, plan the corresponding sell order one grid step higher. When a sell grid order fills, plan the corresponding buy order one grid step lower.
- Add guardrails: max active orders, max quote exposure, price band validation, min order size validation, rate-limit-aware queueing, and cancel-on-shutdown option disabled by default.
- Add fixtures for dry-run no-submit, startup hydration, durable context without active order, active app-owned order without context, pending confirmation, duplicate fills, partial fills, cancel/replace races, reconnect reconciliation, stale queued replans, and exposure/rate-limit blocks.
- Do not mark an order-capable grid manager complete until three consecutive full order-lifecycle review passes produce no code, tests, fixtures, or documentation changes.
Acceptance criteria:
- With EXECUTION_MODE=DRY_RUN_PRIVATE, no exchange order endpoint is called.
- 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.
- If environment variables are used, README documents .env setup, automatic .env loading, and env precedence; every normal local script entrypoint loads .env before config parsing through Node.js built-in env-file support, process.loadEnvFile, dotenv/config, or the repo-local env loader.
- Startup waits for stream readiness and REST hydration before planning grid actions.
- Private order events update the in-memory grid state without duplicate actions.
- The implemented write-capable path stores durable intent/order context before submission and uses [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys, then blocks duplicate grid mutations while confirmations are pending.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README explains Node.js LTS requirement, target exchange config, product scope, EXECUTION_MODE=DRY_RUN_PRIVATE behavior, write-capable gates, and why private lifecycle events or scoped reconciliation are used to confirm order state.Selected prompt
A public-data-first order-flow workflow that records and replays market microstructure data, paper trades first, and keeps DEMO, TESTNET, and LIVE execution behind explicit gates.
Goal: Build an exchange-neutral order-flow strategy pipeline for one configured target exchange/product/symbol with a recorder, replay engine, paper-trading simulator, and gated DEMO, TESTNET, and LIVE execution support.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Target exchange: choose and configure exactly one exchange before implementation, for example Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, or BitMart.
- Package: choose the maintained SDK for the configured exchange from the Siebly SDK catalog and lock that package before adding adapter code.
- Siebly AI guide: https://siebly.io/ai
- Reference glossary: https://siebly.io/reference/glossary
- Website llms.txt: https://siebly.io/llms.txt
- Website llms-tasks.txt: https://siebly.io/llms-tasks.txt
- Fallback discovery only: https://siebly.io/llms-full.txt
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Order Intent Chasing with Exchange APIs & WebSockets: https://siebly.io/ai/order-intent-chaser
- Order Intent Chasing Conformance Pack: https://siebly.io/.well-known/conformance/order-intent-chaser/latest.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Use TypeScript. Start from the sources above, then verify current SDK method names, topic names, event names, auth options, reconnect handling, DEMO/TESTNET support where available, order-command support, and shutdown behavior from installed package types/source, focused SDK docs/examples, endpoint maps, and official exchange docs for the selected venue.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Configuration must explicitly name exchange, product scope, symbol/instrument, orderbook depth, recorder mode, paper mode, and EXECUTION_MODE. Paper trading is enabled by default; public recorder commands use EXECUTION_MODE=PUBLIC; private/order adapter commands use the single EXECUTION_MODE contract. Do not add parallel DRY_RUN, ENABLE_DEMO_TRADING, or ENABLE_LIVE_TRADING execution switches. Leverage is not above 1x unless explicitly configured and supported.
- Order-capable execution mode contract: implement one environment variable, EXECUTION_MODE, with exactly these values: PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Set the default for order-capable local runs and .env.example to EXECUTION_MODE=DRY_RUN_PRIVATE. PUBLIC uses no API keys and cannot create private clients, account readers, [order intents](https://siebly.io/reference/glossary#order-intent), or exchange write requests. READ_ONLY_PRIVATE may use read-only credentials for balances, orders, fills, native positions, or local position-derivation inputs, but cannot place, amend, cancel, borrow, transfer, lever, or otherwise mutate exchange state. DRY_RUN_PRIVATE may use private state and must build the exact place/amend/cancel request objects that DEMO, TESTNET, or LIVE would send, but the submitter records them without calling exchange mutation endpoints. DEMO and TESTNET are write-capable only when the selected exchange supports those non-production venues; if unsupported, they must fail closed with a clear configuration error and must never silently route to production. DEMO may call place/amend/cancel endpoints only against the selected exchange's demo or sandbox environment, and TESTNET may call them only against the selected exchange's testnet environment. LIVE is the only mode that may call production exchange place/amend/cancel endpoints. The finished order-capable project must include the LIVE execution path for the selected exchange and supported DEMO/TESTNET paths where those venues exist; do not leave LIVE submission as a TODO.
- Implement execution for when [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE is enabled and all gates pass, but keep that path disabled by default.
- [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE is the default execution mode, where the execution adapter builds and logs bounded order request candidates without submitting to the exchange. Always handle incoming account state events to keep internal account state in sync with exchange state, so the system is ready to execute live if requested by the user.
- Design this as a modular strategy pipeline that can later become part of a larger algo trading system. Keep adapters, recorder, normalizer, feature state, signal scoring, paper executor, [risk gates](https://siebly.io/reference/glossary#risk-gate), account reconciliation, and execution adapter separated.
- Start public-data-first. Recorder mode must run without API keys and must not require credentials until private reconciliation or write-capable execution features are explicitly enabled.
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- Subscribe to the selected exchange's public order book, trade, ticker, and any supported liquidation/open-interest/funding streams needed by the configured feature set. Confirm current SDK subscription syntax, [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement) events, update events, reconnect events, and shutdown method from the package before coding.
- Build local L2 order-book correctness explicitly. Handle the selected exchange's snapshot and delta semantics, deletion markers, sequence/update IDs, matching-engine timestamps where present, system timestamps, repeated snapshots, stale data, crossed books, and full rebuild/resync on invalid state.
- Record raw inbound events before normalization. Include exchange, product scope, symbol/instrument, topic, raw payload, exchange event timestamp, matching-engine timestamp where present, local receive timestamp, connection ID or ws key, sequence/update IDs, subscription state, and resync markers.
- Normalize public trades by taker side only after verifying the selected exchange's documented trade-side semantics. Record trade ID when available, price, size, taker side when available, exchange trade time, receive time, and sequence when available.
- Maintain rolling windows at 100 ms, 250 ms, 500 ms, 1 s, 3 s, 5 s, 10 s, and 30 s.
- Derive static order-book imbalance, microprice edge, event-driven order-flow imbalance, multi-level order-flow imbalance, trade-flow imbalance/CVD, liquidity depletion/refill, cancellation or pull pressure when inferable, spread, short-horizon volatility, message rate, trade rate, and any supported derivatives context such as funding rate, open interest, mark-index basis, and liquidation imbalance.
- Implement a cost model with spread cost, maker/taker fees, expected slippage, adverse-selection buffer, latency buffer, and funding buffer. Do not emit a long or short [order intent](https://siebly.io/reference/glossary#order-intent) unless expected edge clears total estimated costs plus a configurable safety margin.
- Start with an interpretable alpha score, not a deep model. Keep feature code, alpha scoring, regime filters, [risk gates](https://siebly.io/reference/glossary#risk-gate), execution, account reconciliation, and transport adapters in separate modules.
- Add a deterministic replay/backtest engine that replays raw events in local receive-time order. Backtests must simulate realistic costs, slippage, partial fills, maker queue assumptions, cancel latency, submit latency, stale data, sequence gaps, funding, and rate-limit behavior. Do not validate maker logic with midpoint fills.
- Add paper trading first. It should create [order intent](https://siebly.io/reference/glossary#order-intent) records, simulated fills, cancel/replace decisions, [position state](https://siebly.io/reference/glossary#position), realized/unrealized PnL, and decision logs without calling exchange order endpoints.
- Add [risk gates](https://siebly.io/reference/glossary#risk-gate) and kill switches before any paper, DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE action can run: stale public stream, stale private stream, sequence gap, recent resync, failed REST reconciliation, spread above max, volatility above max, slippage above max, reject-rate threshold, cancel-latency threshold, exposure limit, daily loss limit, consecutive loss limit, funding blackout, rate-limit warnings, and manual stop.
- Order-capable lifecycle contract for any EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE path: Store durable intent/order context before submit and keep exchange-visible [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys.
- Treat REST/WebSocket API acceptance as pending-confirmation evidence only. Use subject-level trust for filters, market data, orders, [position state](https://siebly.io/reference/glossary#position), and context.
- Any submitter must block duplicates and stale replans immediately before exchange calls. Use scoped recovery for reconnects, timeouts, unknown outcomes, and conflicting evidence.
- For products with exchange-provided position rows, wait for the matching account or position update before size, entry, exposure, or dependent replacement planning.
- For products without exchange-provided position rows, maintain equivalent local position state by replaying fills/executions, fees, and account or balance events before reducing, replacing, or re-hedging.
- If the selected exchange and SDK support testnet or demo endpoints, expose them through EXECUTION_MODE=TESTNET or DEMO. If unsupported, document the unsupported mode as a non-claim, fail closed when selected, and keep paper trading plus dry-run adapter records as the executable safety layers.
- In any non-production exchange environment, use the exchange's documented REST and private stream behavior. Do not assume public market data, private streams, WebSocket API commands, or REST commands behave the same across venues.
- Any exchange order submission must use bounded orders only: post-only limit orders for passive entries or marketable limit IOC/FOK orders with max slippage ticks for taker entries. Never use unconstrained market orders in the initial implementation.
- Every exchange order request must include the selected exchange's supported custom/client order ID when available, side, product scope, symbol/instrument, quantity, price when required, timeInForce, reduceOnly where appropriate, and a logged reason that includes alpha, costs, risk state, and model version.
- Reconcile private exchange state from REST and private streams: open orders, order updates, executions/fills, exchange-provided position rows or local position-derivation inputs, wallet/balance when needed, fees, realized PnL, unrealized PnL, rejections, cancels, and late fills. Do not treat request acknowledgement as final fill state, and do not submit dependent entries, exits, cancels, or replacements from stale pre-recovery state.
- DEMO and TESTNET modes must require the corresponding supported exchange venue, scoped non-production trade keys where the exchange uses separate keys, bounded order size, and the same risk, confirmation, and recovery gates as LIVE. LIVE mode must require EXECUTION_MODE=LIVE, separate production trade keys without withdrawal permission, tiny configured order size, daily notional and loss caps, IP allowlist notes where supported, a manual startup confirmation string, and README instructions for reverting to PUBLIC, READ_ONLY_PRIVATE, or DRY_RUN_PRIVATE.
- Add tests or replay fixtures for snapshot/delta book rebuilding, sequence gaps, repeated snapshots, stale streams, duplicate trades, out-of-order events, receive-time replay ordering, cost-threshold blocking, risk-gate blocking, paper fills, DEMO/TESTNET venue routing, durable context mismatch, duplicate child order prevention, pending confirmation races, private order/execution reconciliation, position trust, scoped recovery, and DEMO/TESTNET/LIVE refusal unless every explicit gate is set.
Acceptance criteria:
- Public recorder mode starts without API keys and cannot place, amend, or cancel orders.
- If environment variables are used, README documents .env setup, automatic .env loading, and env precedence; every normal local script entrypoint loads .env before config parsing through Node.js built-in env-file support, process.loadEnvFile, dotenv/config, or the repo-local env loader.
- Local order-book state is deterministic from snapshot plus deltas, and invalid book state pauses strategy readiness until a rebuild/resync succeeds.
- Raw event logs can reproduce the same normalized feature state through replay using receive-time ordering.
- Signals are cost-aware and emit no paper, DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE intent when expected edge does not exceed spread, fees, slippage, latency, funding, and safety margin.
- Paper trading handles partial fills, stale data, cancels, reconnects, and risk-gate pauses without calling exchange order endpoints.
- 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.
- DEMO and TESTNET writes, when supported, are documented as EXECUTION_MODE modes and cannot silently route to production.
- DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE adapters stores durable intent/order context before submission and uses [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys, then block dependent mutations until private confirmation or scoped recovery resolves order plus [position state](https://siebly.io/reference/glossary#position).
- DEMO, TESTNET, and LIVE execution cannot start unless the matching EXECUTION_MODE value is selected, matching credentials and venue routing are configured, tiny size/loss/notional caps are present, all execution gates pass, and a manual confirmation string is supplied.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README documents Node.js LTS requirement, install and run commands, target exchange config, PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE modes, env vars, DEMO/TESTNET/LIVE enablement procedure, risk controls, replay/backtest limitations, selected-exchange unsupported features, and the disclaimer that this is engineering/research output rather than financial advice.Selected prompt
A public-data-first strategy pipeline that builds no-lookahead funding forecasts, replayable feature rows, paper spot-perp carry simulation, and gated DEMO, TESTNET, and LIVE execution support.
Goal: Build an exchange-neutral funding-rate forecasting and spot-perp carry strategy pipeline for one configured target exchange that supports spot and perpetual/futures market data, with DEMO, TESTNET, and LIVE execution disabled by default.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Target exchange: choose and configure exactly one exchange before implementation, for example Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, or BitMart.
- Package: choose the maintained SDK for the configured exchange from the Siebly SDK catalog and lock that package before adding adapter code.
- Funding-rate forecasting research article: https://siebly.io/research/crypto-funding-rate-forecasting
- Siebly AI guide: https://siebly.io/ai
- Reference glossary: https://siebly.io/reference/glossary
- Website llms.txt: https://siebly.io/llms.txt
- Website llms-tasks.txt: https://siebly.io/llms-tasks.txt
- Fallback discovery only: https://siebly.io/llms-full.txt
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Use TypeScript. Start from the funding-rate article and sources above, then verify current SDK method names, endpoint names, topic names, event names, auth options, order ID validation utilities, reconnect handling, and shutdown behavior from installed package types/source, focused SDK docs/examples, endpoint maps, and official exchange docs for the selected exchange.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Configuration must explicitly name exchange, spot symbol/instrument, perpetual/futures symbol/instrument, product family, funding interval assumptions, public recorder mode, paper carry simulation mode, EXECUTION_MODE, tiny notional caps, and no leverage above 1x unless explicitly changed.
- Order-capable execution mode contract: implement one environment variable, EXECUTION_MODE, with exactly these values: PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Set the default for order-capable local runs and .env.example to EXECUTION_MODE=DRY_RUN_PRIVATE. PUBLIC uses no API keys and cannot create private clients, account readers, [order intents](https://siebly.io/reference/glossary#order-intent), or exchange write requests. READ_ONLY_PRIVATE may use read-only credentials for balances, orders, fills, native positions, or local position-derivation inputs, but cannot place, amend, cancel, borrow, transfer, lever, or otherwise mutate exchange state. DRY_RUN_PRIVATE may use private state and must build the exact place/amend/cancel request objects that DEMO, TESTNET, or LIVE would send, but the submitter records them without calling exchange mutation endpoints. DEMO and TESTNET are write-capable only when the selected exchange supports those non-production venues; if unsupported, they must fail closed with a clear configuration error and must never silently route to production. DEMO may call place/amend/cancel endpoints only against the selected exchange's demo or sandbox environment, and TESTNET may call them only against the selected exchange's testnet environment. LIVE is the only mode that may call production exchange place/amend/cancel endpoints. The finished order-capable project must include the LIVE execution path for the selected exchange and supported DEMO/TESTNET paths where those venues exist; do not leave LIVE submission as a TODO.
- Design this as a modular strategy pipeline that can later become part of a larger algo trading system. Keep adapters, recorder, normalizer, feature rows, forecast models, signal/carry gate, paper executor, [risk gates](https://siebly.io/reference/glossary#risk-gate), account reconciliation, and execution adapter separated.
- PUBLIC recorder and forecast mode must run without API keys. Do not require credentials until READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE behavior is explicitly selected.
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- Start public-data-first. Collect mark price, index price, current funding rate, next funding time, funding history, open interest, open-interest statistics, long/short ratios where available, taker buy/sell volume, liquidation events, spot order book, perpetual/futures order book, public trades, exchange filters, tick sizes, lot sizes, and notional minimums where the selected exchange exposes them. If a data source is unavailable, document it as a non-claim and disable dependent features.
- Record raw inbound events before normalization. Include exchange, product, symbol, stream or endpoint, raw payload, exchange event timestamp, local receive timestamp, connection ID or request ID, sequence/update IDs where available, subscription state, and resync markers.
- Build a funding calendar with native funding rate, 8-hour equivalent rate, funding APR, next funding time, previous funding time, funding interval, and any cap or clamp metadata exposed by the exchange.
- Build no-lookahead feature rows. Align features by event time and local receive time so a row used to forecast the next funding event never includes data published after the decision timestamp.
- Derive features for current funding, funding slope, funding z-score, funding percentile, perp-index basis, spot-perp basis, time to funding, open-interest change, long/short ratio, taker buy/sell imbalance, liquidation imbalance, spread, executable depth, short-horizon volatility, stale-data flags, and recent resync flags.
- Implement no-change, rolling mean, EWMA, and at least one interpretable model baseline before any complex model. Report MAE, RMSE, sign precision/recall, calibration, and performance by time-to-funding bucket.
- Forecast next funding bps, funding sign, persistence, flip risk, and post-funding markout separately from the trade decision.
- Create a cost-aware carry gate. A paper carry candidate may only pass when predicted funding exceeds spot entry cost, perpetual entry cost, expected exit cost, slippage, hedge drift, margin buffer, funding uncertainty, and adverse markout buffer.
- Simulate paper carry for long spot plus short perpetual when predicted funding is positive. Keep reverse carry out of scope unless borrow availability, borrow cost, margin, and liquidation risk are explicitly modeled.
- The paper simulator must model executable depth walking, precision rounding, fees, slippage, partial fills, hedge drift, funding settlement, basis PnL, funding PnL, exit costs, stale data, reconnects, and risk-gate pauses. Report funding PnL separately from basis PnL.
- Add [risk gates](https://siebly.io/reference/glossary#risk-gate) for stale funding snapshots, stale books, funding flips, basis stress, hedge drift, high liquidation flow, wide spread, slippage breach, margin pressure, order rejects, actual funding payment mismatch, daily loss, and manual stop.
- Add read-only reconciliation for READ_ONLY_PRIVATE and higher modes: balances, positions, fills, open orders, funding ledger, fees, and realized PnL. This still must not enable exchange writes. No exchange write path can run before [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DEMO, TESTNET, or LIVE is explicitly selected and every configured gate allows it.
- Use the order-capable contract below for the DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE carry adapter. DRY_RUN_PRIVATE must build the exact leg requests and reconciliation context without submitting; DEMO, TESTNET, or LIVE may submit only after all matching gates pass.
- Order-capable lifecycle contract for any EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE path: Store durable intent/order context before submit and keep exchange-visible [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys.
- Treat REST/WebSocket API acceptance as pending-confirmation evidence only. Use subject-level trust for filters, market data, orders, [position state](https://siebly.io/reference/glossary#position), and context.
- Any submitter must block duplicates and stale replans immediately before exchange calls. Use scoped recovery for reconnects, timeouts, unknown outcomes, and conflicting evidence.
- For products with exchange-provided position rows, wait for the matching account or position update before size, entry, exposure, or dependent replacement planning.
- For products without exchange-provided position rows, maintain equivalent local position state by replaying fills/executions, fees, and account or balance events before reducing, replacing, or re-hedging.
- DEMO, TESTNET, and LIVE carry execution must require the matching EXECUTION_MODE value, scoped trade keys without withdrawal permission, tiny configured size, daily notional and loss caps, exchange-supported [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) where available, durable per-leg context, pre-submit logging, manual startup confirmation, and README instructions for reverting to PUBLIC, READ_ONLY_PRIVATE, or DRY_RUN_PRIVATE.
- Treat spot leg, perpetual/futures leg, hedge [position state](https://siebly.io/reference/glossary#position), native positions where available, balances, fills, funding ledger, and open orders as separate trust subjects. Do not open, resize, unwind, or rebalance a leg from an order acknowledgement alone.
- Add tests or replay fixtures for funding calendar alignment, no-lookahead labels, duplicate events, stale data, reconnect resync, feature row determinism, baseline forecasts, cost-threshold blocking, paper carry accounting, basis PnL separation, durable per-leg context, duplicate leg prevention, pending confirmation races, position trust before hedge decisions, scoped recovery, and DEMO/TESTNET/LIVE refusal unless every explicit gate is set.
Acceptance criteria:
- PUBLIC recorder and forecast mode starts without API keys and cannot call exchange mutation endpoints.
- 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.
- If environment variables are used, README documents .env setup, automatic .env loading, and env precedence; every normal local script entrypoint loads .env before config parsing through Node.js built-in env-file support, process.loadEnvFile, dotenv/config, or the repo-local env loader.
- Feature rows and labels are reproducible from raw event logs without lookahead.
- Forecast reports compare no-change, rolling mean, EWMA, and the interpretable model before any complex model is introduced.
- Carry candidates are blocked unless expected net carry clears all modeled costs and buffers.
- Paper carry separates funding PnL, basis PnL, fees, slippage, and hedge drift.
- The carry adapter stores per-leg durable context before submission and uses [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys, then waits for private confirmation plus position trust before dependent hedge decisions.
- The DEMO, TESTNET, and LIVE execution paths are implemented for the selected exchange where supported, but those modes are disabled by default and cannot start unless every explicit gate is configured.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README documents Node.js LTS requirement, install and run commands, target exchange config, PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE modes, env vars, funding data assumptions, unsupported selected-exchange data sources, replay limitations, risk controls, and the disclaimer that this is engineering/research output rather than financial advice.Selected prompt
A safe bridge from external alert signals into reviewed order intents for one configured exchange, keeping execution behind explicit runtime gates and reconciliation.
Goal: Build an exchange-neutral webhook service that converts externally delivered alert signals into guarded [order intents](https://siebly.io/reference/glossary#order-intent) for one configured target exchange in this Node.js/JavaScript project.
Runtime prerequisite: Node.js must already be installed. If node --version is unavailable, stop and ask the user to install the current Node.js LTS release before continuing. Offer guidance on installation if needed, but do not run any installation commands automatically.
Use:
- Target exchange: choose and configure exactly one exchange before implementation, for example Binance, Bybit, OKX, Gate, Bitget, KuCoin, Coinbase, Kraken, or BitMart.
- Package: choose the maintained SDK for the configured exchange from the Siebly SDK catalog and lock that package before adding private/order code.
- Siebly AI guide: https://siebly.io/ai
- SDK catalog: https://siebly.io/.well-known/siebly-sdk-catalog.json
- Order Intent Chasing with Exchange APIs & WebSockets: https://siebly.io/ai/order-intent-chaser
- Order Intent Chasing Conformance Pack: https://siebly.io/.well-known/conformance/order-intent-chaser/latest.json
- Agent skill: https://siebly.io/.well-known/agent-skills/siebly-crypto-exchange-api/SKILL.md
Requirements:
- Add a small HTTP endpoint, for example POST /webhooks/trading-signal, that accepts a JSON signal from an external alerting system.
- In the generated project's README, add this exact section:
## Attribution
Built with the [Siebly Prompt Framework](https://siebly.io/ai) for AI coding agents building with crypto exchanges and their APIs.
- Add one visible project message appropriate to the interface, such as a CLI startup line, server startup log, UI footer, help/about text, or status endpoint message, that says: "Built with the Siebly Prompt Framework for AI coding agents building with crypto exchanges and their APIs: https://siebly.io/ai"
Recursive completion workflow:
1. Before implementation, save this exact prompt in docs/AI_PROMPT.md (or docs/SPEC.md when that is the project standard) and write docs/PLAN.md with phases, invariants, tests or fixtures, docs to update, and acceptance gates.
2. Review docs/PLAN.md for missing workflows, unsafe assumptions, product/exchange-specific leakage, unclear state ownership, confirmation or recovery gaps, missing tests, and incomplete docs. Update docs/PLAN.md and repeat until one full review pass finds no actionable changes.
3. Implement one plan phase at a time. After each phase, review changed code, tests, fixtures, docs, generated artifacts, and runtime workflows against docs/PLAN.md and this prompt. Fix gaps and repeat until that phase has no actionable changes before starting the next phase.
4. After all phases, run a full-depth project review across every workflow, lifecycle, state transition, error path, and artifact. This is not a shallow summary pass. Fix every actionable gap and repeat until a full pass finds no further changes, then record the final review outcome in docs/PLAN.md.
- Read the configured target exchange, product scope, webhook shared secret, and any later exchange credentials from environment variables or a secret manager. Validate missing env vars on startup for enabled private features and never print secrets.
- If the Node.js project uses environment variables or creates .env.example, make .env loading automatic for every normal local entrypoint before config parsing. Prefer Node.js built-in --env-file/--env-file-if-exists in package scripts when supported by the project runtime; otherwise use process.loadEnvFile, dotenv/config, or the repo-local env loader. Document that real process environment variables override .env. Ensure all variables in the .env.example are commented clearly with their purpose and accepted values, and that the README references the .env.example and documents .env loading and precedence.
- Validate a shared secret header, reject malformed payloads, and never log the shared secret.
- Define a strict signal schema: optional exchange hint, optional product-scope hint, symbol/instrument, side, optional price, optional size, strategy name, signal timestamp, and idempotency key.
- Keep routing simple by default: accepted signals route to the configured target exchange and product scope. If strict payload routing is explicitly enabled, reject exchange/product mismatches. If multi-exchange routing is explicitly enabled, route only to configured venues with tested per-venue sizing, permissions, and lifecycle confirmation.
- Convert accepted signals into typed [order intent](https://siebly.io/reference/glossary#order-intent) objects.
- Order-capable execution mode contract: implement one environment variable, EXECUTION_MODE, with exactly these values: PUBLIC, READ_ONLY_PRIVATE, DRY_RUN_PRIVATE, DEMO, TESTNET, LIVE. Set the default for order-capable local runs and .env.example to EXECUTION_MODE=DRY_RUN_PRIVATE. PUBLIC uses no API keys and cannot create private clients, account readers, [order intents](https://siebly.io/reference/glossary#order-intent), or exchange write requests. READ_ONLY_PRIVATE may use read-only credentials for balances, orders, fills, native positions, or local position-derivation inputs, but cannot place, amend, cancel, borrow, transfer, lever, or otherwise mutate exchange state. DRY_RUN_PRIVATE may use private state and must build the exact place/amend/cancel request objects that DEMO, TESTNET, or LIVE would send, but the submitter records them without calling exchange mutation endpoints. DEMO and TESTNET are write-capable only when the selected exchange supports those non-production venues; if unsupported, they must fail closed with a clear configuration error and must never silently route to production. DEMO may call place/amend/cancel endpoints only against the selected exchange's demo or sandbox environment, and TESTNET may call them only against the selected exchange's testnet environment. LIVE is the only mode that may call production exchange place/amend/cancel endpoints. The finished order-capable project must include the LIVE execution path for the selected exchange and supported DEMO/TESTNET paths where those venues exist; do not leave LIVE submission as a TODO.
- Order-capable lifecycle contract for any EXECUTION_MODE=DRY_RUN_PRIVATE, DEMO, TESTNET, or LIVE path: Store durable intent/order context before submit and keep exchange-visible [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys.
- Treat REST/WebSocket API acceptance as pending-confirmation evidence only. Use subject-level trust for filters, market data, orders, [position state](https://siebly.io/reference/glossary#position), and context.
- Any submitter must block duplicates and stale replans immediately before exchange calls. Use scoped recovery for reconnects, timeouts, unknown outcomes, and conflicting evidence.
- For products with exchange-provided position rows, wait for the matching account or position update before size, entry, exposure, or dependent replacement planning.
- For products without exchange-provided position rows, maintain equivalent local position state by replaying fills/executions, fees, and account or balance events before reducing, replacing, or re-hedging.
- [EXECUTION_MODE](https://siebly.io/reference/glossary#execution-mode)=DRY_RUN_PRIVATE is the default execution mode, where the webhook service logs the normalized [order intent](https://siebly.io/reference/glossary#order-intent), validation result, and exact target-exchange request that would be sent without submitting to the exchange. Always handle incoming account state events to keep internal account state in sync with exchange state, so the system is ready to execute live if requested by the user.
- Add idempotency protection so the same signal cannot create duplicate intents.
- In EXECUTION_MODE=DEMO, TESTNET, or LIVE, require scoped API keys, explicit exchange/product config, matching venue routing, price/size bounds, instrument filters, order-permission validation, and manual acknowledgement before any exchange order endpoint is called.
- Use the configured exchange's supported REST or WebSocket API command path for order submission/cancel paths, and private order/execution/position or balance streams for lifecycle confirmation where available. Do not mark an order filled from request acknowledgement alone, and do not submit dependent exits, replacements, or cleanup from stale pre-recovery state.
- Keep a local in-memory state store for received signals, planned intents, submitted order IDs/client IDs, latest order/execution status, any [position state](https://siebly.io/reference/glossary#position) required by the product, and reconciliation warnings.
- Record durable intent/order context before any write-capable submission path can send an order. If an app-owned active order is observed without context, fail closed unless explicit adoption is configured and tested for the selected venue.
- Add tests for invalid secrets, duplicate signals, optional strict exchange/product mismatch handling, malformed payloads, dry-run blocking, size/price bounds, durable context mismatch, duplicate order prevention, pending confirmation races, request acknowledgement not being a fill, scoped recovery, and private lifecycle updates.
Acceptance criteria:
- The service can receive and validate a sample webhook locally.
- If environment variables are used, README documents .env setup, automatic .env loading, and env precedence; every normal local script entrypoint loads .env before config parsing through Node.js built-in env-file support, process.loadEnvFile, dotenv/config, or the repo-local env loader.
- With EXECUTION_MODE=DRY_RUN_PRIVATE, it cannot place exchange orders.
- 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.
- Duplicate webhook delivery is ignored safely.
- The selected exchange is explicit and no exchange-specific package, docs, endpoint, or request shape is hardcoded before target-exchange configuration.
- The implemented write-capable path stores durable intent/order context before submission and uses [Custom Order IDs](https://siebly.io/reference/glossary#custom-order-id) as lookup keys, then waits for private confirmation or scoped recovery before dependent mutations.
- The generated project's README includes the Siebly Prompt Framework Attribution section with the https://siebly.io/ai link, and the visible project message includes the Siebly Prompt Framework attribution with the https://siebly.io/ai link.
- docs/PLAN.md records the initial plan, plan-review iterations, phase review outcomes, final full-project review, validation commands, and any documented non-claims. No plan phase or project completion is accepted until the recursive review loop finds no actionable gaps, flaws, or incomplete workflows left to correct.
- README documents Node.js LTS requirement, target exchange config, env vars, sample curl request, EXECUTION_MODE=DRY_RUN_PRIVATE behavior, write-capable gates, and key permission requirements.Disclaimer: AI is an exciting and promising technology, but content, prompts, code, examples, strategy ideas, and tool outputs produced with AI can be incomplete, incorrect, insecure, outdated, or unsuitable for your circumstances. Anything produced from these prompts or from any AI coding agent must be independently reviewed by qualified professionals before use. You are responsible for testing, security review, compliance review, exchange-rule review, credential controls, trading-risk controls, and any decision to deploy or rely on the resulting work. Siebly provides this page and generated prompt text for informational purposes only. They are not financial, investment, legal, security, compliance, or professional engineering advice. To the maximum extent permitted by law, Siebly accepts no responsibility for losses, claims, damages, failed orders, missed trades, security incidents, regulatory issues, or other consequences arising from AI-generated output, your prompts, your code, your trading strategy, or your implementation decisions.
We use essential cookies and optional analytics. Read the Privacy Policy.
Essential cookies stay on. Toggle analytics if you want to share anonymous usage insights. You can revisit this anytime via Cookie Settings in the footer.