HOOX TRADING PLATFORM CONSOLIDATED SYSTEM INTELLIGENCE SPEC FILE: docs/enduser/home.md Welcome to the Hoox Developer Hub Hoox is a free, open-source, zero-latency algorithmic trading framework and automation engine deployed natively to the Cloudflare Edge Network. By utilizing a distributed microservice architecture, Hoox processes trade signals, evaluates risk parameters, executes order routing, and fires Telegram notifications—all within milliseconds and directly from the edge nodes closest to exchange servers. --- ️ Choose Your Path Whether you are a retail algorithmic trader setting up your first automated TradingView strategies, a quantitative analyst exploring low-latency DeFi order routing, or a DevOps engineer maintaining multi-exchange infrastructure, our docs are split into highly focused tracks: . Getting Started If you are brand new to the Hoox ecosystem, start here to prepare your machine, provision resources, and deploy your first live microservice in under minutes: Core Installation — Provision prerequisites (Bun runtime, Cloudflare credentials) and bootstrap a project. Platform Configuration — Declaratively define environment variables, JSON profile templates, and KV keys. -Minute Quick Start — Launch local worker runners and execute a simulated webhook trade signal. . Core Concepts Understand the underlying technology, low-latency edge architecture, and security layers that protect your api keys: How Hoox Works — The end-to-end lifecycle of a trade signal from webhook alert to order confirmation. Edge-First Architecture — Why V isolates and Cloudflare Workers outperform traditional VPS architectures by -%. Cloudflare Services Map — How D, KV, R, Queues, Vectorize, and Browser Rendering are integrated. Idempotency & Durable Objects — Preventing catastrophic double-execution and race conditions during high-frequency events. Signals & Trade Routing — How parameters map from webhook JSON schemas to live exchange payloads. AI Risk Manager — The -minute autonomous risk scanner, trailing-stop mathematician, and account kill-switch. . ️ Operational Guides Practical runbooks and blueprints for daily operations, local development, and system health maintenance: Local Dev & Workspaces — Run, hot-reload, and test workers locally via Bun or Docker container stacks. Terminal UI Operations — Launch and navigate the full-screen -view operations cockpit (./hoox-tui). Edge Database Operations — Manage global SQLite schemas, track drizzle migrations, and run D queries. Secrets & Network Security — Secure Cloudflare Zero Trust corridors and encrypt sensitive API credentials. Infrastructure Management — Spin up and inspect KV, Queues, R, and Vectorize indexes in one command. Deploying to Production — Roll out code, bind V isolates, and deploy Next.js dashboard consoles. Self-Healing & Repair — Diagnose connection dropouts, rotate API keys, and run interactive system repair tools. . Step-by-Step Tutorials Follow guided, end-to-end tutorials to integrate your trade sources and notification handlers: TradingView Webhook Integration — Write customized Pine Script v indicators that ping the Hoox webhook receiver. Telegram Bot Setup — Configure real-time order alerts, P&L reports, and secure chat commands. Email Signal Routing — Configure email parsing services to convert raw inbox alerts into edge trade executions. . Reference Material Deep specifications, schema registries, and command-line manual trees: CLI Commands Index — Complete options, positional arguments, and JSON flag trees for the hoox tool. API Spec & REST Routes — HTTP endpoints, request payloads, response templates, and edge errors list. Configuration Properties — Comprehensive dictionary of all env keys and KV key-value items. --- Offline Reference & AI Context Download our consolidated specifications or view complete text packages for feeding into LLMs: Download Enduser Full PDF Manual — Complete concatenated offline guide. Download DevOps Full PDF Manual — Complete concatenated offline DevOps spec. View Consolidated LLM Context Text — Giant single-file text format for AI/LLM models. --- Tip: Looking for deep engineering plans, DDL SQL schemas, or CI/CD deployment workflows? Check out the DevOps & Architecture Manual for developer-centric operator blueprints! FILE: docs/enduser/getting-started/installation.md Installation Guide This guide walks you through preparing your environment, installing the @jango-blockchained/hoox-cli tool, cloning the microservices monorepo recursively, and validating your local system prerequisites. --- System Prerequisites Before installing the Hoox command-line workspace, ensure your system meets the following standard software requirements: . Bun JavaScript Runtime (Version ≥ .) Hoox uses Bun as its primary package manager, script runner, and native testing engine. Bun's blazing-fast startup time and zero-config TypeScript compilation are critical to our local developer feedback loops. macOS / Linux: ``bash curl -fsSL https://bun.sh | bash ` Windows (via Powershell): `powershell powershell -c "irm https://bun.sh/install.ps | iex" ` . Cloudflare Account & Wrangler CLI All Hoox workers are compiled to run on Cloudflare's Edge V isolates. You will need a free Cloudflare account: Account: Register a free account (the free tier provides , requests/day, D database, KV storage, Queues, R, and vector search—costing $/month). Cloudflare CLI: Ensure you have wrangler installed globally (though Hoox manages local wrangler operations automatically, having it indexed globally is recommended): `bash bun add -g wrangler ` . Docker & Docker Compose (Optional) If you prefer running the entire Hoox local trading workspace in fully isolated container environments with one command, ensure you have Docker Desktop installed and running: Check status: docker compose version --- Option A: Install via Package Manager (Recommended) To install the global management CLI tool directly from npm/bun registry to manage new workspaces: `bash Install globally using Bun bun add -g @jango-blockchained/hoox-cli ` Once installed, verify that the hoox command is registered globally in your system path: `bash hoox --version ` --- ️ Option B: Build & Run from Source If you plan to contribute to the Hoox CLI packages or prefer working directly inside a monolithic source clone: `bash . Clone the parent repository with git submodules recursively git clone --recursive https://github.com/jango-blockchained/hoox-setup.git hoox-trading cd hoox-trading . Install all monorepo workspace dependencies via Bun bun install . Verify the locally linked CLI runs from root bun run build:cli ./packages/cli/bin/hoox.js --help ` Warning: You MUST use git clone --recursive or run git submodule update --init --recursive after cloning. If you omit submodules, the worker directories under workers/ will be empty and deployments will fail. --- Bootstrapping Your Trading Workspace Now, initialize your new algorithmic trading workspace. This compiles directories, configures workspace settings, and sets up Git tracking. `bash Bootstrap your trading folder hoox clone my-trading-empire cd my-trading-empire ` This command automatically structures your directories as a clean monorepo: ` my-trading-empire/ ├── packages/ │ ├── cli/ Workspace CLI management binaries │ ├── tui/ -view Terminal UI monitoring cockpit │ └── shared/ Reusable routers, rate-limiters, & errors ├── workers/ │ ├── hoox/ Gateway, rate-limiter, DO idempotency lock │ ├── trade-worker/ Multi-exchange execution engine │ └── ... Other analytical and web wallet workers └── package.json ` --- Running the Interactive Setup Wizard With your folder structured, execute the interactive bootstrap wizard: `bash hoox init ` The CLI wizard will guide you through critical setup phases: . Toolchain Validation: Probes your machine for bun, git, wrangler, and docker configurations. . Cloudflare Authentication: Prompts for your Cloudflare API token (with Account.D, Account.KV, Account.Workers permissions) and Account ID. . Microservice Profile Selection: Lets you declaratively toggle which edge workers to enable (e.g., enable Gateway and Trade Worker, disable Web Wallet if you only trade centralized exchanges). . Local Credentials Encryption: Generates safe local .dev.vars matrices and sets up initial KV configuration structures. ` ┌────────────────────────────────────────────────────────┐ │ hoox Setup & Initialization │ ├────────────────────────────────────────────────────────┤ │ bun (v..) found │ │ wrangler (v..) found │ │ git found │ │ Cloudflare Credentials Verified │ │ │ │ Enable central Gateway Worker? [Y/n]: y │ │ Enable Multi-Exchange trade-worker? [Y/n]: y │ │ Enable agent-worker AI Risk Manager? [Y/n]: y │ └────────────────────────────────────────────────────────┘ ` --- Verifying Local Prerequisites Verify that all dependencies and Cloudflare edge routes are accessible: `bash Perform detailed pre-flight diagnostic checklist hoox check prerequisites ` If all diagnostic checks pass, you are ready to proceed with configuration! --- Tip: Got installation issues? Run hoox repair check` to automatically analyze common path resolution issues, missing environment variables, or node-gyp build failures, and recover your local workspace seamlessly. Next Steps Configuration Matrix — Map out your -key environment variables and -key KV registries. -Minute Quick Start Guide — Execute your first simulated edge trade in under minutes. FILE: docs/enduser/getting-started/configuration.md ️ Platform Configuration Hoox uses a dual-layer configuration topology: a declarative build-time environment layer (managed via local files and Cloudflare Secrets) and an instantaneous runtime configuration layer (managed via Cloudflare KV key-value databases). This ensures maximum agility: deploy secure code once, and adjust trading parameters or flip kill switches in real-time without redeploying code. --- . Declarative Environment Variables (.env.local) For local operations, build-time variables, and workspace linking, Hoox loads a .env.local file at your project root. Copy the secure template during initialization: ``bash cp .env.example .env.local ` The Hoox environment is split into core logical sections. Below is the comprehensive dictionary of key configuration parameters: A. Cloudflare Core Infrastructure | Parameter | Required | Description | Example | | :---------------------- | :------: | :------------------------------------------------------------------- | :--------------------------------- | | CLOUDFLAREAPITOKEN | Yes | API token with D, KV, Queue, and Workers write permissions. | cfpatabc... | | CLOUDFLAREACCOUNTID | Yes | Your unique -character Cloudflare dashboard account hash. | debcebeabecbcdec | | SUBDOMAINPREFIX | Yes | Subdomain prefix under which your public gateway routes compile. | hoox-edge | B. Exchange API Keys (Securely Redacted) These credentials must be injected as secure encrypted environment variables into your Cloudflare Worker isolates. The Hoox CLI automates this injection. Binance: BINANCEAPIKEY — Your read/write exchange account trade permission key. BINANCEAPISECRET — Private secret key used to HMAC-SHA sign order payloads. Bybit: BYBITAPIKEY — Order routing account key. BYBITAPISECRET — Order signing private key. MEXC: MEXCAPIKEY — Order routing account key. MEXCAPISECRET — Order signing private key. C. Telegram Bot Alerts | Parameter | Required | Description | Example | | :------------------- | :------: | :--------------------------------------------------------------------- | :---------------------- | | TELEGRAMBOTTOKEN | No | HTTP API authentication token provided by Telegram's BotFather. | :ABCdefGh... | | TELEGRAMCHATID | No | The numeric chat ID of the user, group, or channel where alerts route. | | D. Multi-Provider AI Credentials Used to power autonomous risk assessments, Telegram conversation loops, and time-series summaries in agent-worker. OPENAIAPIKEY — Access key for OpenAI GPT models. ANTHROPICAPIKEY — Access key for Anthropic Claude models. GOOGLEAIAPIKEY — Access key for Google Gemini models. --- . Managing Environment & Secrets via CLI To prevent plain-text exposure and ensure proper edge variable binding, never manually paste sensitive keys into wrangler.jsonc files. Instead, utilize the high-integrity hoox config env command groups: `bash . Start the guided terminal config wizard hoox config env init . View active workspace configuration (sensitive credentials automatically redacted) hoox config env show . Validate env file structure against required platform variables hoox config env validate . Generate local decrypted .dev.vars files for every enabled worker hoox config env generate-dev-vars ` Note: Decrypted .dev.vars files contain local environment credentials and are excluded from git history via .gitignore automatically. Running hoox config env generate-dev-vars ensures that local worker testing via bun run dev has access to simulated credentials safely. --- . Worker Configurations (wrangler.jsonc) Each worker in the monorepo has a standard wrangler.jsonc file at its directory root. These configurations declare: . Service Bindings: Connects gateway routes (hoox) to internal compute units (trade-worker, d-worker) directly via microsecond V isolates—no TCP/TLS overhead, no public routes. . Resource Bindings: Declares which D databases, R storage buckets, and KV configurations are linked. . Execution Mode: Toggles latency-saving features like Smart Placement ("placement": { "mode": "smart" }). You can inspect, check, or change worker toggle status directly: `bash Print complete microservice enabled/disabled status tree hoox config show Declaratively enable/disable specific workers in the manifest hoox config set workers.web-wallet-worker.enabled false ` --- . Runtime KV Configuration (Sub-millisecond Settings) One of Hoox's core architectural features is instant runtime parameter updates. By using Cloudflare KV, certain settings can be modified globally in sub-milliseconds and take effect on the very next signal execution—without rebuilding or redeploying any worker. Hoox manages a standard -key runtime manifest inside the CONFIGKV namespace. Below are the most critical runtime parameters: | KV Key | Type | Default | Description | | :--------------------------------- | :-------: | :--------------: | :--------------------------------------------------------------------------------------------- | | trade:killswitch | boolean | false | Global Kill Switch. If set to true, all incoming trade execution loops immediately halt. | | trade:maxdailydrawdownpercent | number | | Maximum daily drawdown before the AI Risk Manager flips the kill switch. | | webhooks:queuemode | string | queuefailover | Trade delivery behavior: directonly, queuefailover, or queueeverywhere. | | exchanges:defaultrouting | string | bybit | Default centralized exchange router. Options: binance, bybit, mexc. | Managing KV Settings via CLI `bash Get the current value of the Global Kill Switch hoox config kv get trade:killswitch Manually trigger a global trading halt hoox config kv set trade:killswitch true Restore trading by flipping the switch back hoox config kv set trade:killswitch false Declaratively apply default manifest variables to Cloudflare KV hoox config kv apply-manifest `` --- Tip: Changed exchange configurations or toggled the kill switch? There is no need to redeploy. The changes are distributed across Cloudflare's + global edge locations near-instantaneously! Next Steps -Minute Quick Start Guide — Launch local worker runners and execute a simulated webhook trade signal. Deploying to Production — Deploy and bind all workers in the correct dependency sequence. FILE: docs/enduser/getting-started/quick-start.md -Minute Quick Start This guide gets you from a blank console to a fully active, edge-deployed algorithmic trading ecosystem on the Cloudflare network, processing simulated signals in under minutes. --- Step-by-Step Deployment Path Step : Initialize Workspace Credentials If you haven't already run the setup wizard during installation, execute the initial workspace configuration: ``bash hoox init ` Follow the interactive prompts to paste your Cloudflare Account ID and API Token, and define your unique SUBDOMAINPREFIX (e.g., alpha-trading). --- Step : Inject Encrypted Exchange API Keys For your safety, exchange credentials (API keys and private signatures) are never stored in plain text. Inject them as encrypted Cloudflare Workers Secrets bound securely to your compute instances: `bash Inject Bybit Credentials hoox secrets set BYBITAPIKEY "yourbybitkeyhere" hoox secrets set BYBITAPISECRET "yourbybitsecrethere" Optional: Inject Binance Credentials hoox secrets set BINANCEAPIKEY "yourbinancekeyhere" hoox secrets set BINANCEAPISECRET "yourbinancesecrethere" ` Warning: Cloudflare Secrets are encrypted at rest using hardware-level keys and are injected straight into your V execution isolates at runtime. They can never be decrypted or read back via the API, ensuring top-tier security for your capital. --- Step : Deploy All Workers in Sequence Hoox microservices communicate internally via Service Bindings. The CLI automatically manages the deployment sequence, ensuring databases, queues, and configuration stores compile first, followed by gateway routers and background compute tasks: `bash Compile and deploy all enabled workers hoox deploy all --auto ` This command automatically provisions: . D Edge Database (hoox-db) . CONFIGKV configuration namespace . Internal Workers (trade-worker, d-worker, telegram-worker) . Public Gateway (hoox gateway router) . Next.js Dashboard Command Center (workers/dashboard) Once completed, the CLI will output your public Gateway endpoint URL: https://hoox.alpha-trading.workers.dev --- Step : Fire a Simulated Trade Webhook Now, fire a test webhook trade signal to your live gateway using curl. `bash curl -X POST https://hoox.alpha-trading.workers.dev/webhook \ -H "Content-Type: application/json" \ -d '{ "apiKey": "your-hoox-webhook-passkey", "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": }' ` --- Webhook Payload Parameters Spec Every webhook payload fired to your Gateway must match the following JSON Schema: | Parameter | Type | Required | Description | | :--------- | :------: | :------: | :----------------------------------------------------------------------------------------------- | | apiKey | string | Yes | Your custom webhook authorization passkey (defined in CONFIG_KV). | | exchange | string | Yes | Target exchange router: binance, bybit, or mexc. | | action | string | Yes | Trading action direction: LONG (buy/open), SHORT (sell/open), or CLOSE (flatten position). | | symbol | string | Yes | Standard market symbol. | | quantity | number | Yes | Position size / quantity. | | leverage | number | No | Leverage coefficient. Defaults to (spot) if omitted. | --- Expected Success Response When a signal arrives, the Hoox Gateway authorizes the request, locks execution via Durable Objects, routes order calculations to the edge node nearest to Bybit's servers, executes the order, and registers the transaction in your D SQLite table. You will receive an instantaneous, low-latency JSON response: `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "exchange": "bybit", "symbol": "BTCUSDT", "action": "LONG", "result": { "orderId": "", "status": "Filled", "executedQty": ., "price": ., "timestamp": } } ` --- Tip: If the exchange is temporarily undergoing system maintenance or experiences high network congestion, Hoox will automatically intercept the failure, enqueue the trade in Cloudflare Queues with exponential backoff retry policies, and return a "status": "Enqueued"` response to guarantee delivery! Next Steps How Hoox Works — Take a deep dive into the edge processing pipelines. Terminal UI Guide — Run, hot-reload, and inspect live metrics in a full-screen console interface. Set Up Telegram Alerts — Link your bot to get order fills pushed straight to your phone. FILE: docs/enduser/concepts/how-hoox-works.md How Hoox Works At its core, Hoox functions as a highly resilient, low-latency pipeline that intercepts trading signals from external sources, validates and decodes the payloads, and converts them into cryptographically signed order placements on global exchanges in milliseconds. Here is the exact lifecycle of an edge trade execution, from alert trigger to brokerage fill. --- ️ The Execution Pipeline --- Detailed Pipeline Phase Analysis . Signal Arrival & Ingestion Signals represent specific instructions to buy, sell, or close positions. Hoox ingests these instructions through three primary channels: TradingView Webhooks: High-integrity trade alerts configured via Pine Script that issue JSON POST payloads to your gateway's public /webhook route. Telegram Commands: Direct user commands sent to your private Telegram Bot (e.g. /trade buy btc quantity=. exchange=bybit), parsed via your webhook router. Email Signals: Secure email triggers forwarded from specialized alerts (e.g. TradingView email alerts), parsed natively by email-worker. --- . Edge Firewall & Gateway Validation When a signal hits your public endpoint, the hoox gateway interceptor immediately evaluates the request inside a sandboxed V isolate: . API Key Authorization: Authenticates the payload's apiKey property against your secure manifest stored in Cloudflare KV. . IP Allow-listing: Verifies that the client IP matches a authorized IP range in KV (essential for restricting access solely to TradingView's known webhook IPs). . Global Kill Switch check: Ensures trade:kill_switch is false. If true, the pipeline aborts immediately to protect your capital. . Rate Limiting: Verifies that signal frequency does not exceed safe execution thresholds (default: orders/minute). . Idempotency Check: Locks a unique transaction trace ID using a SQLite-backed Durable Object. If the DO detects that the exact same signal hash was already processed, it drops the request to prevent double-ordering. --- . Service Binding Order Routing Once validated, the gateway bypasses public internet routing and calls the internal trade-worker directly via Service Bindings: Zero Latency: Communication occurs within a microsecond inside the V engine, with zero TCP handshakes or TLS decryption overhead. Private Isolation: The trade-worker does not expose any public URL, remaining completely isolated from external attacks. Dynamic Exchange Routing: The worker parses the symbol (e.g. BTCUSDT) and evaluates your KV config. If Bybit is undergoing maintenance, you can instantly redirect trades to MEXC or Binance with one command. --- . Exchange Execution & Cryptographic Signing The trade-worker loads your encrypted API credentials from Cloudflare Secrets, computes the HMAC-SHA signature for the order parameters, and pushes the signed request to the exchange's nearest API gateway: Smart Placement: Because Smart Placement is enabled, Cloudflare automatically runs your worker on the physical edge node located geographically closest to the exchange's servers (e.g. Frankfurt for Bybit, Tokyo for Binance), cutting network transit time by up to %. --- . Persistent D Logging & Telemetry Upon receipt of the order response (e.g. Filled, Partial, or Rejected), Hoox updates your ledger: D SQLite Database: Writes transaction logs, filled prices, execution fees, and order IDs to your D database. R Log Offloading: Offloads full JSON request-response packets to your secure R storage bucket to keep D database footprints compact. --- . User Notifications & Alerts Finally, the trade-worker pings telegram-worker via an internal binding: You receive an immediate Telegram notification on your phone detailing the symbol, filled price, order status, and transaction ID. Twice-daily, report-worker uses Browser Rendering to compile beautiful HTML reports of your trading metrics, generating PDFs and dropping the link directly in your chat. --- Tip: If the exchange API experiences transient network dropouts or severe rate limits, the Hoox Gateway automatically transfers the payload to Cloudflare Queues with an exponential retry schedule (s → m → m → m), keeping your strategy fully reliable even during periods of heavy market volatility. Next Steps Edge-First Architecture — Understand the absolute latency benefits of edge workers vs VPS. Signals & Trade Specifications — Analyze the complete JSON webhook and order formatting. FILE: docs/enduser/concepts/edge-architecture.md Edge-First Architecture In algorithmic trading, latency is leverage. A delay of just milliseconds between a signal firing and an order arriving at the exchange can mean the difference between a highly profitable fill and severe price slippage. Hoox solves the latency problem by abandoning traditional server-centric architectures (like AWS, DigitalOcean, or standard VPS instances) and executing order logic natively on Cloudflare Edge Workers. --- ️ The Physics of Latency: Why Traditional VPS Bots Fail Traditional trading bots are deployed on a single virtual private server (VPS) in a fixed geographical data center (e.g., Virginia, USA). The VPS Bottleneck (ms+ slippage) . Signal Generation: A TradingView alert fires in London. . Network Transit: The alert travels across the Atlantic to your Virginia VPS (~ms). . Execution Delay: The VPS boots a heavy Node/Docker runtime to process the signal (~ms). . Exchange Transit: The order travels from Virginia to Bybit's API servers in Tokyo or Frankfurt (~ms). . Total Transit Latency: ms before the exchange matches your order. `` [London Alert] ── (ms) ──> [Virginia VPS] ── (ms) ──> [Frankfurt Bybit] = ms Latency ` The Hoox Edge Path (Under ms latency) . Signal Generation: A TradingView alert fires in London. . Edge Ingestion: The alert hits Cloudflare’s nearest London Point of Presence (PoP) in .ms. . V Isolate Processing: A sandboxed V isolate processes and validates the order instantly ( [London PoP] ── (ms Service Binding) ──> [Frankfurt Node] ── (ms) ──> [Bybit] = .ms Latency `` --- V Isolates vs. Traditional VMs / Containers Traditional architectures run on Virtual Machines or Docker containers. These runtimes carry significant memory overhead and introduce cold starts—the time required to spin up a container after inactivity. | Architectural Dimension | Traditional VM / Container (VPS) | Cloudflare Edge Worker (V Isolate) | | :---------------------- | :---------------------------------------: | :----------------------------------------: | | Boot Architecture | Heavy guest OS, Node runtime, npm modules | Sandboxed JavaScript V Engine runtime | | Cold-Start Delay | ,ms – ,ms (system stalls) | Tip: By removing VPS management, you do not just save latency—you also save operational overhead. Cloudflare natively manages automatic scaling, load balancing, SSL negotiation, and route failovers for free. Next Steps Cloudflare Services Explained — Learn how D SQLite databases, KV, and Queues fit together on the edge. AI Risk Manager — Understand how autonomous risk checks run on global cron schedules. FILE: docs/enduser/concepts/cloudflare-services.md ️ Cloudflare Services Map Hoox is built natively on a serverless microservice architecture powered by a suite of fully integrated Cloudflare services. By offloading database scaling, messaging retry loops, file storage, and AI inference to Cloudflare's global infrastructure, Hoox runs with zero server maintenance, ultra-low latency, and $ monthly costs on the free tier. Here is an architectural map of how each service functions in the Hoox monorepo. --- ️ . D Database (Edge SQL Engine) Concept: A serverless, globally distributed SQLite database engine natively hosted at Cloudflare's edge locations. Hoox Implementation: Used to store critical transactional data, including executed trades ledger, historical win rates, daily asset balances, and position tracking tables. Why it Matters: Writes are atomic and ACID-compliant. Queries complete in under milliseconds because the database runs in the same V isolate context as your worker logic. No need to host, secure, patch, or configure connection pools for a separate database server (like PostgreSQL or MySQL). --- . KV Store (Sub-Millisecond Key-Value Configuration) Concept: A highly available, globally distributed key-value store optimized for high-read/low-write operations. Hoox Implementation: Houses the global -key runtime manifest, including the Global Kill Switch (trade:killswitch), exchange routing paths, rate-limiter profiles, and authorized client IP ranges. Why it Matters: Read operations are cached directly at Cloudflare's edge nodes, delivering sub-millisecond lookups. Updates propagate worldwide in under seconds. You can toggle settings in your terminal, and the change affects every worker globally in seconds, without code redeployment. --- . Cloudflare Queues (Asynchronous Messaging Guard) Concept: A high-integrity, serverless message broker guaranteeing at-least-once delivery with built-in retry schedules. Hoox Implementation: Acts as an asynchronous buffer and retry buffer for signal executions (queuefailover mode). Why it Matters: If a centralized exchange (like Bybit or Binance) undergoes system maintenance or experiences rate limits, the Hoox Gateway intercepts the API error, serializes the trade payload, and enqueues it. The queue automatically retries execution with an exponential backoff schedule (s → m → m → m → m). Your trades never get lost due to internet dropouts or API errors. --- . Durable Objects (Distributed Coordination & Idempotency) Concept: Single-threaded, in-memory compute isolates containing persistent local storage, ensuring that exactly one instance of an object runs globally. Hoox Implementation: Drives the Gateway's Idempotency Engine inside workers/hoox. Why it Matters: When TradingView fires multiple retries for the same alert (due to a transient network timeout), Durable Objects intercept the request, acquire an atomic mutex lock, and evaluate the trade's unique hash. Prevents disastrous duplicate trades (e.g. accidentally buying the same spot position twice) during moments of high market congestion. --- . R Object Storage (Zero-Egress Asset Vault) Concept: A fully S-compatible, serverless object storage bucket featuring zero bandwidth egress fees. Hoox Implementation: Stores large data payloads, verbose exchange API request/response packets, and compiled HTML/PDF reports. Why it Matters: Offloading heavy system logging to R saves massive write capacity on your D SQL database, keeping your database compact and responsive. Zero-egress pricing means you can retrieve, export, and audit your historic trade logs as many times as you like without incurring network charges. --- . Vectorize & Workers AI (Embedded RAG & LLMs) Concept: A serverless vector search database and an on-demand edge AI inference engine running specialized open-source models (like LLaMA , Qwen, and Mistral). Hoox Implementation: Integrates with the Telegram Bot (telegram-worker) to provide semantic trade analysis and context-aware natural language conversations. Why it Matters: User chat queries are converted into high-dimensional vector embeddings, searched against historical trades inside Vectorize, and fed into Workers AI as context. Deliver highly intelligent, context-aware risk analysis directly on your mobile chat without calling expensive external APIs. --- . Browser Rendering (Edge Puppeteer Renderer) Concept: Serverless Chrome instances running at Cloudflare's edge, allowing developers to automate browser actions, interact with websites, and convert web elements to documents. Hoox Implementation: Deployed in report-worker to generate twice-daily, styled PDF portfolio reports. Why it Matters: Reads D database P&L records, renders a beautiful, secure HTML dashboard report, captures it via Puppeteer, converts it to PDF, saves the file to R, and links it directly in your Telegram alert. Completely automated, running entirely in the background near-instantaneously. --- Tip: Every single one of these services is supported by the Hoox CLI! You can check database tables using hoox db query, provision R buckets with hoox infra r create, and sync your KV manifest using hoox config kv apply-manifest instantly. Next Steps Idempotency Mechanics — Dive into the V Durable Objects coordination engine. AI Risk Manager — Understand how autonomous edge cron jobs evaluate drawdowns and manage trailing stops. FILE: docs/enduser/concepts/idempotency.md Idempotency & Durable Objects In automated financial systems, execution integrity is everything. If a network dropout occurs at the exact millisecond after your gateway submits an order to an exchange but before the exchange sends back a confirmation, a standard system faces a dilemma: If it assumes the order failed and retries, it risks executing duplicate trades (e.g. accidentally buying the same spot position twice, doubling leverage, and exposing your account to high liquidation risks). If it assumes the order succeeded and does nothing, it risks missing critical trade entries. Hoox solves this problem natively at the edge gateway layer using Cloudflare Durable Objects to enforce an absolute exactly-once execution policy (idempotency). --- ️ The Danger: How Webhook Retries Lead to Double-Ordering Without idempotency, a typical signal failure sequence looks like this: `` [TradingView Webhook] ─── (Signal Post) ───> [Gateway Node] ─── (Submit Order) ───> [Exchange API] │ (Order Filled!) │ [TradingView Webhook] [Gateway Node] ─── (Submit Order) ───> [Exchange API] │ (DOUBLE-FILLED! ) ` --- ️ The Hoox Solution: Durable Objects Mutex Locking To enforce exactly-once execution, Hoox implements an atomic dedup lock inside workers/hoox utilizing Cloudflare Durable Objects. A Durable Object is a unique, single-threaded compute isolate managed by Cloudflare that maintains its own highly optimized, in-memory state and persistent on-disk SQLite storage. Because access to a specific Durable Object instance is single-threaded, it acts as an absolute distributed lock (mutex). The Idempotency Workflow ` [Incoming Webhook Payload] │ ▼ [Extract Trace ID / Mutex Key] │ ▼ [Ping Dedicated Durable Object Isolate] │ ┌───────┴──────────────────────────────────────────┐ │ Single-Threaded Mutex Lock Acquired │ │ │ │ Check local SQLite dedup log: │ │ "Has Trace ID 'bdebd...' been seen?" │ └───────┬──────────────────────────────────────────┘ │ ├─► [YES: Duplicate Detected] ─────────────────────┐ │ │ │ ▼ │ [Silent Dropping of Request] │ │ │ ▼ │ [Return Conflict Response] │ └─► [NO: Unique Transaction] ─────────────────────┐ │ ▼ [Record ID in SQLite Log] │ ▼ [Process Pipeline Execution] │ ▼ [Set TTL-based DO Alarm] ` --- The Dedup & Cleanup Algorithm . Trace ID Generation When a trade signal is fired, it must include a unique transaction signature. For TradingView webhooks, this is automatically generated as a combination of alert parameters and timestamps. If a client does not supply a transaction ID, the Hoox Gateway dynamically hashes the symbol, exchange, action, and timestamp to create a unique Idempotency Key. --- . Atomic Evaluation Before executing any order routing: . The gateway routes the request to the namespace-mapped Durable Object using the transaction ID as the binding key. . The Durable Object checks its internal state. Since DOs are single-threaded, there is zero risk of race conditions—if two identical HTTP requests hit Cloudflare simultaneously, they are processed sequentially inside the DO. . If the ID exists in the DO's SQLite log, the DO immediately intercepts the request and throws a Conflict exception, stopping the pipeline before hitting exchange APIs. . If unique, it registers the ID, saves the current timestamp, and returns a lock approval. --- . Automatic TTL & Storage Alarms To prevent the Durable Object's persistent storage from growing indefinitely and consuming unnecessary memory: The DO registers an atomic alarm scheduled for hours in the future. When the alarm fires, the DO runs an automatic garbage collection script that purges old IDs from its local storage. This ensures that while you are % protected against duplicates during network dropouts, your storage footprint remains lightweight. --- Warning: Never disable idempotency check bindings in your wrangler.jsonc` file in production. The performance cost of pinging the DO is less than milliseconds, while the cost of a duplicate order could be catastrophic. Next Steps Signals & Trade Specifications — Learn how to configure your Pine Script webhook payloads to transmit unique idempotency keys. Platform Security Guides — Deepen your understanding of Zero Trust headers and edge firewall configurations. FILE: docs/enduser/concepts/signals-and-trades.md Signals & Trade Spec This document details the exact specifications, JSON validation schemas, and internal translation logic that occurs when an external trade signal (such as a TradingView alert or Email parser) is ingested by the Hoox Gateway and mapped to an active exchange order. --- . Webhook Signal Ingestion Schema Every signal received by the public gateway at /webhook must contain a valid, authenticated JSON payload. Below is the strict TypeScript interface and parameter schema validated by the gateway's validation middleware: ``typescript export interface WebhookSignal { apiKey: string; // Authentication token exchange: "binance" | "bybit" | "mexc"; // Target exchange action: "LONG" | "SHORT" | "CLOSE"; // Position intent symbol: string; // Asset symbol (e.g. "BTCUSDT") quantity: number; // Order size (amount of asset or contracts) leverage?: number; // Optional leverage multiplier (default: ) idempotencyKey?: string; // Optional unique signature for dedup } ` Parameter Rules & Type Constraints apiKey: Must match the encrypted webhooks:apikey hash in your CONFIGKV namespace. symbol: Parsed and standardized by Hoox to match exchange requirements. For example, Hoox automatically converts variations like BTC-USDT, BTCUSDT, and btc/usdt to the exchange-compliant flat uppercase format BTCUSDT. quantity: Verified to be greater than zero. leverage: Checked against exchange limits (e.g. to depending on exchange margin profiles). --- . Dynamic Payload Translation & Side Mapping Exchanges do not understand actions like LONG, SHORT, or CLOSE. They process order instructions in terms of Side (BUY or SELL) and PositionSide (LONG or SHORT for multi-margin hedge modes). The trade-worker parses the incoming signal and translates the business logic into exchange-specific API calls: A. Translation Table (One-Way Margin / Spot) | Action | Position State | Translated Exchange Side | Operation Type | | :---------- | :-------------------- | :----------------------: | :---------------------------------------------- | | LONG | Closed / No Position | BUY | Opens a long position (spot or margin). | | SHORT | Closed / No Position | SELL | Opens a short position (margin/futures). | | CLOSE | Long Position Active | SELL | Closes and flattens an existing long position. | | CLOSE | Short Position Active | BUY | Closes and flattens an existing short position. | B. Dynamic Position Resolution When the action is CLOSE, the trade-worker automatically performs a sub-millisecond edge check: . Queries your local D transaction ledger to resolve the active position direction for the symbol. . If no position is tracked locally, it performs a real-time portfolio balance check against the exchange's private position endpoint. . Automatically sets the order quantity to match your current open exposure, ensuring a perfect, slippage-free execution that flattens the position without leaving residual micro-contracts. --- . Leverage Scaling & Order Math If the signal includes a leverage parameter greater than (e.g., "leverage": ), the trade-worker automatically executes a secure margin transition sequence: . Set Margin Mode: Configures the symbol's margin structure (Isolated vs. Cross) via the exchange API, matching your manifest defaults. . Set Leverage Coefficient: Submits a leverage update payload to the exchange prior to routing the order. . Calculate Collateral: If the order size is defined in USDT terms, the worker scales the execution quantity mathematically: $$\text{Contract Quantity} = \frac{\text{Order Size (USDT)} \times \text{Leverage}}{\text{Current Market Price}}$$ . Precision Rounding: Automatically rounds the calculated quantity down to match the exchange's strict asset decimal precision requirements, preventing API rejects. --- . D Database Transaction Ledger Every filled order is persistently written to your globally distributed edge SQLite table. The schema ensures a clean audit log: `sql CREATE TABLE trades ( id TEXT PRIMARY KEY, -- UUID generated by trade-worker requestid TEXT NOT NULL, -- Distributed trace ID mapping to gateway exchange TEXT NOT NULL, -- "bybit", "binance", or "mexc" symbol TEXT NOT NULL, -- e.g. "BTCUSDT" action TEXT NOT NULL, -- "LONG", "SHORT", or "CLOSE" side TEXT NOT NULL, -- "BUY" or "SELL" quantity REAL NOT NULL, -- Filled asset quantity price REAL NOT NULL, -- Execution entry price fee REAL NOT NULL, -- Exchange transaction fees orderid TEXT NOT NULL, -- Exchange-provided order hash status TEXT NOT NULL, -- "Filled", "Rejected", "Failed" createdat TIMESTAMP DEFAULT CURRENTTIMESTAMP ); ` You can view this ledger at any time from your local terminal: `bash Query the most recent trades in your D database hoox db query "SELECT createdat, exchange, symbol, action, price, quantity FROM trades ORDER BY created_at DESC LIMIT " ` --- Tip: By utilizing time-series logging via Cloudflare Analytics Engine, Hoox tracks the exact execution duration of these steps. You can audit the latency breakdown (e.g., Gateway auth took .ms, Trade-worker signing took .ms, Bybit API roundtrip took .ms`) directly in your Next.js dashboard! Next Steps Autonomous AI Risk Management — Learn how agent-worker tracks these D entries to manage trailing stops and drawdowns. CLI Reference Manual — Review commands to manage D tables, perform dry runs, and tail logs. FILE: docs/enduser/concepts/ai-risk-manager.md AI Risk Manager & AI Gateway The agent-worker is the autonomous central nervous system of the Hoox trading platform. Operating on a continuous -minute Cloudflare Cron trigger, it acts as an intelligent sentinel: it monitors open exchange positions, mathematically scales trailing stop-losses, and deploys a multi-provider fallback AI engine to analyze market conditions, audit risk, and send real-time summaries to your phone. --- ️ . Automated Risk Protection Engine Every minutes, agent-worker executes a multi-point risk diagnostic loop across all active exchanges: A. Trailing Stop-Loss Mathematics Rather than using static stops that leave profits exposed, the risk engine calculates a dynamic trailing stop-loss at the V compiler level: The Formula: $$\text{Trailing Stop Price (Long)} = \text{Peak Price} \times ( - \text{Trailing Deviation \%})$$ If a LONG trade entry is at $\$$ and has a $\%$ trailing deviation, the initial stop-loss is placed at $\$$. If the market price rallies to a peak of $\$$, the stop-loss is automatically adjusted up to $\$.$. If the price declines from $\$$ down to $\$.$, the stop is triggered at the exchange level, locking in a $\$.$ profit. The stop never moves downward. --- B. Scaled Take-Profits (Partial Fills) To manage extreme market swings, the agent-worker supports multi-target scaling: Target ($\%$ Profit): Automatically flattens $\%$ of open position size. Target ($\%$ Profit): Flattens another $\%$ and moves the stop-loss of the remaining $\%$ to break-even, eliminating downside risk. --- C. Max Daily Drawdown & Global Kill Switch If high volatility causes unexpected stop-outs, the agent-worker aggregates your real-time realized P&L: . Calculates cumulative daily loss: $$\text{Daily Drawdown \%} = \frac{\text{Starting Daily Balance} - \text{Current Balance}}{\text{Starting Daily Balance}} \times $$ . If the drawdown exceeds your KV threshold (e.g. trade:maxdailydrawdownpercent is ), the agent-worker immediately triggers the Global Kill Switch by writing trade:killswitch = true to CONFIG_KV. . Calls the trade-worker service binding to submit immediate market close orders, flattening all active positions across all exchanges near-instantaneously. ``bash Check current Kill Switch status via CLI hoox monitor kill-switch show Manually override to halt all trade processes during extreme macro events hoox monitor kill-switch on Resume operations once conditions stabilize hoox monitor kill-switch off ` --- . Multi-Provider AI Gateway & Reasoning Behind the scenes, agent-worker governs a Multi-Provider AI Gateway (supporting major providers) with built-in resilience. If you query the bot for trade advice, market summaries, or risk audits, the gateway processes the request through an automatic fallback chain: A. The Resilient Provider Fallback Chain ` [User Chat Query] │ ▼ [. Cloudflare Workers AI] (Zero cost, native LLaMA ) ──► Fail? ──┐ │ ▼ [. Anthropic API] (Claude . Sonnet) ◄───────────────────────────┘ │ Fail? ──► [. Google AI] (Gemini . Pro) ──► Fail? ──► [. OpenAI] (GPT-o) ` B. Custom Telemetry & Chat Endpoints The gateway exposes professional endpoints for secure inter-worker and external integrations: POST /agent/chat — Accepts user prompts and handles SSE (Server-Sent Events) streaming responses. POST /agent/vision — Analyzes charts, balance screenshots, or trading signals from Base images. POST /agent/reasoning — Interfaces with advanced reasoning models (like OpenAI o or DeepSeek) to audit trading strategies and margin structures. GET /agent/usage` — Provides detailed token counting and cost metrics across all providers. --- Tip: You can adjust all AI gateway defaults, Cron check intervals, and trailing deviations in real-time by writing to your KV configurations. No code deployments are ever required to tune your risk profile. Next Steps Zero Trust & Secret Security — Lock down your AI endpoints and exchange API keys. TUI Operations Cockpit — View live position drawdowns and trailing stops visually in your terminal. FILE: docs/enduser/guides/local-development.md Local Development Hoox provides a comprehensive local development workspace designed to match your production Cloudflare edge environment. You can run all microservices with hot-reload enabled, monitor them visually via the Terminal UI (TUI), and execute the full test suite using native Bun tools or isolated Docker containers. --- Starting the Local Workspace To spin up all enabled workers simultaneously: ``bash hoox dev start ` On execution, the CLI automatically detects your environment and prompts you to select a runtime: Option A: Native Runtime (Recommended for speed) Runs each worker in a separate background thread using wrangler dev (the official Cloudflare local server). Speed: Instant startup and sub-millisecond hot-reloading. Requirements: Local node/bun installation. Option B: Docker Runtime (Recommended for isolation) Launches a multi-container stack using Docker Compose. Isolation: All environment variables, SQLite databases, and queue handlers run in isolated Linux containers, ensuring zero conflicts with local packages. Requirements: Docker Desktop installed. Tip: The CLI saves your runtime preference inside wrangler.jsonc.dev.runtime. Subsequent launches skip the prompt. You can override your preference at any time using flags: `bash Force native execution hoox dev start --runtime native Force Docker Compose execution hoox dev start --runtime docker ` --- Docker Compose Profiles If you choose the Docker runtime, Hoox manages orchestration using three specialized Docker Compose profiles defined in docker-compose.yml: `bash Profile : Workers Only (No frontend dashboard) docker compose --profile workers up Profile : Dashboard Only (Next.js server only) docker compose --profile dashboard up Profile : Full Stack (All workers + Next.js dashboard) docker compose --profile full up ` --- Local Port Mapping & Endpoint Access During local development, all enabled workers are assigned dedicated local ports, simulating service boundaries locally: | Worker | Local Port | Endpoint URL | Purpose | | :-------------------- | :--------: | :---------------------- | :-------------------------------- | | hoox | | http://localhost: | Public Gateway & Webhook Receiver | | trade-worker | | http://localhost: | Trade Execution Engine | | telegram-worker | | http://localhost: | Telegram Bot Alerts & Commands | | d-worker | | http://localhost: | SQLite Database Operations | | web-wallet | | http://localhost: | On-Chain DeFi Execution | | dashboard | | http://localhost: | Next.js Dashboard Cockpit | | agent-worker | | http://localhost: | AI Risk Manager & Cron Engine | --- ️ Operating Individual Services If you only want to work on a single microservice rather than running the full stack, you can spin up individual modules: `bash Dev run a single worker (gateway) hoox dev worker hoox Dev run trade-worker with hot-reloading hoox dev worker trade-worker Dev run dashboard separately (Next.js dev server with Turbopack) hoox dev dashboard ` --- Running the Verification CI Pipeline Hoox features a rigorous local test pipeline to ensure that all TypeScript types, formatting, and unit tests pass perfectly before pushing to git: `bash Run the complete CI verification pipeline locally hoox test ` The pipeline executes four verification steps in a strict dependency sequence: . Lint Check (bun run lint): Validates ESLint styling rules across the monorepo. . Type Check (bun run typecheck): Compiles code via tsc --noEmit to verify type safety. . Unit Tests (bun test): Fires all unit and integration test assertions using Bun's native test runner. . Build Check (bun run build): Compiles all workspaces (cli, tui, shared, dashboard) to verify production packaging. ` Running local CI Pipeline... [STARTED] lint check... [PASSED] [STARTED] TypeScript typecheck... [PASSED] [STARTED] bun test runner... [PASSED] (, assertions) [STARTED] workspace builds... [PASSED] Local CI Pipeline Succeeded! ` --- Note: Local unit tests utilize Bun's native test runner for instantaneous execution. You can target specific workspace folders or run files individually: bun test workers/trade-worker/src/index.test.ts. Next Steps Terminal UI Operations — Launch the full-screen terminal cockpit (./hoox-tui`) to monitor these local runs. Database Migrations — Set up, query, and migrate your local SQLite D database. FILE: docs/enduser/guides/tui.md ️ Terminal UI (TUI) The Hoox Terminal User Interface (TUI) is a full-screen, keyboard-driven operations cockpit built natively with OpenTUI, React , and Zustand state stores. Designed for command-line efficiency, the TUI provides real-time visibility into your entire distributed trading infrastructure—allowing you to inspect compute instances, tail logs, query D databases, manage configurations, and deploy edge workers in seconds. --- Launching the TUI Launch the cockpit directly from your terminal using any of the following methods: ``bash . Recommended: Shell script launcher (from project root) ./hoox-tui . Recommended: Via the hoox CLI tool hoox tui . Development: Run direct hot-reload development server cd packages/tui && bun run dev . Flags: Override frame rate and disable mouse interaction hoox tui --fps --no-mouse ` --- ️ Global Keyboard Navigation Cheatsheet The TUI features a keyboard-first layout. All shortcuts are registered globally and can be triggered from any active view: | Keyboard Shortcut | Operation | View Name | | :------------------ | :----------- | :------------------------------------------------------ | | Ctrl+ | Jump to View | Dashboard — System Health Overview | | Ctrl+ | Jump to View | Workers Overview — -Column Cards Grid | | Ctrl+ | Jump to View | Worker Detail — Deep-Dive Metrics | | Ctrl+ | Jump to View | Trade Monitor — Real-Time Transaction Feed | | Ctrl+ | Jump to View | Logs Viewer — Streaming Log Console | | Ctrl+ | Jump to View | Service Manager — Deploy & Rebuild Controls | | Ctrl+ | Jump to View | Config Editor — Syntax-Highlighted TOML/JSON Editor | | Ctrl+ | Jump to View | Setup Wizard — Onboarding Flow | | Ctrl+ | Jump to View | Settings — UI Preferences & theme toggle | | Ctrl+P | Action | Command Palette — Fuzzy-search search overlay | | Ctrl+B | Action | Toggle Sidebar — Show/Hide menu | | Ctrl+R | Action | Force Refresh — Recalculate metrics | | Ctrl+Q | Action | Quit — Displays exit confirmation dialog | | Esc | Action | Close overlay / Dismiss modal / Go back | | Tab / Shift+Tab | Navigation | Cycle active focus between elements | | Enter | Navigation | Select / Execute / Toggle button | --- ️ Cockpit Tour: The Core Views . The Operations Dashboard (Ctrl+) Your high-signal, single pane of glass. Service Status Grid: Operational, Degraded, or Offline indicators for all edge workers. Telemetry Statistics: Session P&L, cumulative win rates, Sharpe ratio, and total API counts. Alert Box: Color-coded, scrolling logs of warnings, drawdowns, and security events. --- . Workers Overview (Ctrl+) A cards-based visual grid representing every running isolate. Displays worker status, uptime metrics, CPU cycles (ms), and active RAM footprint (MB). Shows active Durable Object instances (locks) and the number of processed signals. Selecting a worker and hitting Enter opens the Worker Detail deep-dive. --- . Worker Detail (Ctrl+) A -quadrant analytical layout focused on a single worker: Top Left: Metrics: Graphs representing memory allocation and request velocities over time. Top Right: Live Logs: Scrollable, real-time log terminal (press p to pause logging). Bottom Left: Durable Objects: SQLite state indexes and active DO alarm TTL counts. Bottom Right: Config Preview: Snapshot of active wrangler.jsonc binds. --- . Trade Monitor (Ctrl+) The financial ledger center. Live Feed: Scrolling record of recent fills (Symbol, Side, Execution Price, Contracts, P&L). Open Positions: Grouped active exposure showing current size, entry price, liquidation boundaries, and real-time unrealized P&L. Win Metrics: Graphical gauges for win/loss ratio, average trade duration, and daily performance metrics. --- . Logs Viewer (Ctrl+) A centralized console debugger: Filter Panel: Multi-select checkboxes for severity filters (INFO, WARN, ERROR), target worker select, and a fuzzy text search box. Log Stream: Scrolling terminal window showing formatted, color-coded lines. --- . Service Manager (Ctrl+) Your deployment pipeline: Worker Controls: Trigger direct deployments (hoox deploy) or soft restarts (wrangler dev resets) on individual workers. Interactive Edge Map: Displays locations of Cloudflare Points of Presence (PoPs) globally with status checks. Bulk Executions: Re-deploy the entire ecosystem in one click, secured by confirmation modals. --- . Configuration Editor (Ctrl+) An IDE-class terminal file editor: Syntax Highlighting: Supports full color-coded rendering for TOML and JSON structures. Live Linter: Evaluates brackets, balancing quotes, and JSON structures on the fly, showing error locations. Prettifier: Automatically formats code blocks (spacing, indentation) on save (Ctrl+S). --- . Guided Setup Wizard (Ctrl+) Onboards new machines in steps: . API Keys: Authenticate Cloudflare credentials. . Exchanges: Inject Bybit, Binance, or MEXC trade API keys. . AI Credentials: Set up multi-provider keys (OpenAI, Gemini, Anthropic). . Strategies: Configure default margins and symbols. . Telegram Bot: Link tokens and Chat IDs. . Kickoff: Initiate deployments. --- . Cockpit Settings (Ctrl+) Configure cockpit parameters: Theme: Swap color themes in real-time. Telemetry: Set metrics refresh rates (default: every seconds). Reset: Clean local TUI caching (~/.hoox/session.json). --- Offline Connection Resilience Store The TUI utilizes an advanced Zustand state machine to govern connectivity to your local API dev server or remote workers: ` [Connected (OK)] ────► [Connection Dropped] ▲ │ │ ▼ [State Restored] ◄─── [Reconnecting (Exponential Backoff)] ` States: Connected (Green dot), Reconnecting (Yellow/Orange pulsing dot), Offline (Red/Empty dot). Resilience: In the event of network dropouts, the TUI activates an exponential backoff engine (starting at ms, doubling up to s), trying to reconnect in the background without freezing or crashing the terminal display. --- ️ Troubleshooting & Terminal Compatibility alternate screen buffer cleanup If you force-close the terminal and find that your prompt remains garbled, execute a terminal reset: `bash reset or tput reset ` "Ctrl+Q" is intercepted by Flow Control If Ctrl+Q (Quit) fails to trigger, your terminal emulator is likely intercepting flow control commands (XON/XOFF). Disable software flow control by running this command before launching the TUI: `bash stty -ixon ` Garbled layout or text overlaps The TUI requires a minimum screen resolution of columns × rows. If your terminal is too small, resize the window. Additionally, ensure your system TERM variable is configured to support colors: `bash export TERM=xterm-color `` Next Steps Local Development Guides — Spin up the API dev server that feeds the TUI. CLI Reference Manual — Read the commands running under the TUI hood. FILE: docs/enduser/guides/database-ops.md ️ Database Operations Hoox utilizes Cloudflare D—a fully serverless, highly optimized SQLite database engine distributed globally across Cloudflare's edge network. This document serves as your operational runbook for executing database schemas, running schema migrations, querying transaction ledgers, and performing secure database backup and recovery. --- ️ The Core Database Tables The database schema defines five fundamental tables designed for trading operations: . trades: The primary ledger. Stores execution prices, contract quantities, timestamps, transaction fees, and exchange order IDs. . positions: Tracks open margin/futures exposure (average entry price, size, leverage, direction). . balances: Periodic snapshots of account equity, margin balance, and available free collateral. . tradesignals: Historical record of every raw incoming webhook alert before execution processing. . systemlogs: Crucial debug and error messages offloaded from compute nodes. --- Applying Schemas & Tables When launching a new workspace, you must initialize the required tables. The Hoox CLI handles this via declarative migration scripts: ``bash . Apply schema and seed initial tables to local dev SQLite hoox db apply . Deploy schema and seed tables directly to live production Cloudflare D hoox db apply --remote ` Warning: Running hoox db apply compiles migrations and seeds the database locally. For production deployment, you must append the --remote flag to execute operations directly on your active Cloudflare D instance. --- Managing Database Migrations When new features are added that require changes to the database structure, you must run migrations: `bash List all applied and pending database migrations in production hoox db migrate status --remote Apply all pending schema migrations sequentially to production D hoox db migrate --remote ` The migration engine tracks history inside a special dmigrations table, ensuring that migrations are never executed twice or applied in the wrong sequence. --- Inspecting & Querying Data from the CLI The Hoox CLI features a built-in SQL interface allowing you to run arbitrary queries directly against your local or remote database: `bash A. List all active tables in your production database hoox db list --remote B. Count the total number of executed trades hoox db query "SELECT COUNT() FROM trades" --remote C. Inspect the most recent trade fills with formatting hoox db query "SELECT createdat, symbol, action, price, quantity FROM trades ORDER BY createdat DESC LIMIT " --remote D. Check currently open positions on Bybit hoox db query "SELECT symbol, side, size, entryprice FROM positions WHERE size > " --remote ` --- Backup & Export Workflows To secure your historical P&L records, transaction ledger, and bot performance telemetry, execute regular exports: `bash Export the entire D database as a clean SQL script hoox db export --remote ` Export Output & Structure The export command creates a timestamped SQL dump inside your workspace directory: backups/db-backup----.sql This file contains standard DDL and DML commands: `sql PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS trades (...); INSERT INTO trades VALUES(...); COMMIT; ` --- ️ Database Reset (Destructive Operations) If you are running simulated paper trading and wish to wipe all ledger history to start fresh, you can reset the tables: `bash Wipe all tables in the local development database hoox db reset --confirm Wipe all tables in the live production D database (USE WITH EXTREME CAUTION) hoox db reset --remote --confirm ` Danger: Wiping your production D database is an irreversible operation. It will permanently delete all trade logs, position records, and asset histories. Always execute hoox db export --remote` before running a reset! Next Steps Local Development & Testing — Run your local V wrangler isolates with local D SQLite bindings. Infrastructure Management — Manage KV config namespaces, Queue parameters, and R storage buckets. FILE: docs/enduser/guides/secrets-security.md Secrets & Network Security Security is the most critical component of the Hoox trading platform. When deploying automated execution scripts, your capital and API credentials must be protected against malicious exploits, unauthorized webhook payloads, and network interceptions. This guide outlines our Zero Trust security architecture, encrypted secret management procedures, and edge-level firewall protection runbooks. --- ️ . Zero Trust Network Isolation Traditional trading systems expose database and exchange execution APIs to the public internet (secured by simple HTTP headers or ports). This creates an active attack surface. Hoox implements a strict Zero Trust microservice isolation topology: `` [Public Internet] ───► [Cloudflare WAF / Firewall] │ (IP & Auth Checks) │ ▼ [Gateway (hoox)] (Publicly Accessible Node) │ ┌────────────────┴────────────────┐ │ V Isolate Service Bindings │ │ (Private, Encrypted, Zero-TCP) │ └────────────────┬────────────────┘ │ ┌─────────────────┼─────────────────┐ ▼ ▼ ▼ [trade-worker] [d-worker] [agent-worker] (No Public URL) (No Public URL) (No Public URL) │ │ │ (Exchange Orders) (SQLite Queries) (AI Risk Audits) ` No Public Endpoints: The trade-worker, d-worker, and agent-worker literally do not exist on the public internet. They have no public IP addresses or URLs. V Service Bindings: Communication between the public gateway (hoox) and internal compute nodes is routed entirely inside Cloudflare's secure V engine isolates. Your trade routing data, database queries, and private logs never travel over the public internet, eliminating TLS decryption and packet-sniffing risks. --- . Encrypted Secret Management via CLI API keys, exchange secrets, and Telegram bot tokens are never committed to git repositories or written in plain-text configuration files. Instead, they are stored directly on Cloudflare’s hardware-secured key vaults. The Hoox CLI features deep encryption integrations to automate secret provisioning: `bash . Inject a secure exchange credential (e.g. Bybit Secret) hoox secrets set BYBITAPISECRET "yourprivatesignaturehere" . Check the synchronization status of all required edge secrets hoox secrets check ` The Secrets Diagnostic Report Running hoox secrets check queries Cloudflare's API to confirm that the key binding exists on the edge, without ever exposing or decrypting the actual values in your terminal: ` ┌────────────────────────────────────────────────────────┐ │ Cloudflare Edge Secrets Audit │ ├────────────────────────────────────────────────────────┤ │ BYBITAPIKEY ........... PRESENT (Active) │ │ BYBITAPISECRET ........ PRESENT (Active) │ │ TELEGRAMBOTTOKEN ...... PRESENT (Active) │ │ OPENAIAPIKEY .......... ️ MISSING (Optional) │ │ │ │ Audit Result: SECURE (All required secrets bound) │ └────────────────────────────────────────────────────────┘ ` --- . Webhook Firewall & TradingView IP Allow-listing To ensure that only TradingView's official servers can fire signals to your /webhook gateway: . Passkey Verification: The gateway checks the apiKey property inside the JSON payload against your secure manifest in CONFIGKV. . Cloudflare WAF (Web Application Firewall): Since TradingView publishes their official IP ranges, you can configure Cloudflare's edge firewall to block all webhook traffic that does not originate from these verified IPs. `bash Auto-configure WAF rules to lock the /webhook route to TradingView IPs hoox waf configure --TradingView-only ` --- . Security Best Practices Checklist Least Privilege API Keys: When creating API keys on Bybit, Binance, or MEXC, never enable "Withdrawal" permissions. Only check "Trade" and "Account Read" permissions. Credential Rotation: Automatically rotate your exchange API keys every days. Deleting old keys and injecting new ones takes less than seconds with hoox secrets set. Zero-Commit Rule: Verify that your .env.local and .dev.vars files are registered in your workspace's .gitignore file to prevent accidental pushes to public repos. Emergency Response: If you suspect a strategy error or exchange anomaly, immediately halt all execution via the CLI: `bash hoox monitor kill-switch on ` Next Steps Astro Docs Site Config — Map out your build-time environment configurations. Local Development & Testing — Run local wrangler sandboxes with securely encrypted .dev.vars`. FILE: docs/enduser/guides/manage-infra.md ️ Infrastructure Management Hoox is fully serverless, using Cloudflare’s distributed services as its compute and storage engine. Managing these resources—such as provisioning D databases, registering KV config buckets, setting up S-compatible R storage, and mounting asynchronous Queues—is done directly via the hoox infra command group. This guide is your operations manual for provisioning, inspecting, and managing Hoox edge infrastructure. --- . One-Click Quick Provisioning When setting up your trading workspace for the first time, you do not need to manually configure resources in Cloudflare’s dashboard. The Hoox CLI automatically parses your enabled workers' configurations and spins up the entire infrastructure stack in one command: ``bash Auto-provision all required KV, D, R, Vectorize, and Queue resources hoox infra provision ` This command performs a dependency audit and calls Cloudflare's APIs to provision: . D SQLite Database (hoox-db). . CONFIGKV Namespace bucket. . trade-execution messaging Queue. . trade-reports and system-logs R object storage buckets. . rag-index Vectorize vector search database. --- ️ . D Database Administration D databases store your critical transactional data (ledger, positions, balance history). `bash A. List all active D databases in your Cloudflare account hoox infra d list B. Create a new custom database instance hoox infra d create my-custom-db C. Delete a database instance (destructive) hoox infra d delete my-custom-db ` Note: Once a D database is created, the CLI will output its unique databaseid (a -character UUID). You must ensure this ID is bound in your worker's wrangler.jsonc file so the worker V isolate can establish a connection at runtime. --- . KV Configuration Namespace Management KV stores are used to manage fast-path configurations, global parameters, and the kill switch. `bash A. List all KV namespaces in your account hoox infra kv list B. Create a new KV namespace (e.g. for staging or production) hoox infra kv create CONFIG_KV C. Apply the default -key configuration manifest to your active namespace hoox config kv apply-manifest ` --- . Asynchronous Queues Setup Queues guarantee order delivery during periods of extreme exchange rate limits or network congestion. `bash A. List all active Cloudflare Queues hoox infra queues list B. Create the trade execution queue hoox infra queues create trade-execution ` Queue Parameters & Throttling During provisioning, Hoox configures the queue with: Retry Backoff: seconds initial delay, scaling exponentially up to minutes. Message Retention: days (ensuring messages are preserved even during prolonged exchange maintenance events). --- . R Object Storage Administration R is an S-compatible, zero-egress fee object storage service used to offload heavy JSON payloads and PDF portfolio reports. `bash A. List all R buckets hoox infra r list B. Create the trade-reports bucket hoox infra r create trade-reports ` --- . Vectorize RAG Index Management Vectorize indexes house high-dimensional vector embeddings that power semantic search and Telegram AI bot memory. `bash A. List all Vectorize indexes hoox infra vectorize list B. Create a vector index with specific dimensions (e.g. for OpenAI embeddings) hoox infra vectorize create rag-index --dimensions --metric cosine ` --- Warning: Destroying resources via hoox infra delete` is highly destructive and irreversible. Deleting a D database instantly wipes your trading records; deleting a KV bucket drops all configurations and triggers immediate gateway errors. Always backup ledgers before running deletions! Next Steps Database Migrations & SQL — Run queries, manage drizzle schemas, and restore backups. Take-to-Production Deployments — Deploy your compiled workers and bind V isolates globally. FILE: docs/enduser/guides/deploy-workers.md Deploying to Production Deploying your algorithmic trading ecosystem to Cloudflare’s production edge requires careful orchestration. Because workers communicate internally using fast-path Service Bindings, they have strict compile-time and deploy-time dependencies. This guide outlines our automated deployment sequence, Next.js OpenNext compilation steps, post-deployment URL bindings, and troubleshooting runbooks. --- ️ The Strict Deployment Dependency Chain When you deploy, workers must be uploaded in a specific sequence. If you attempt to deploy the public gateway (hoox) before the database or execution engines are live, the deployment will fail because the gateway's compile-time service bindings cannot resolve their targets. The Hoox CLI automates this dependency hierarchy: `` [. D Database Schema] ──► [. d-worker (SQL Hub)] ──► [. trade-worker (Execution Engine)] │ ┌───────────────────────────────────────────────────────────────┘ ▼ [. hoox Gateway (Public Router)] ──► [. agent-worker & telegram-worker] │ ▼ [. Next.js Dashboard (OpenNext)] ` --- Deployment CLI Commands To execute a complete production rollout: `bash . Compile and deploy all enabled workers in the correct dependency order hoox deploy all --auto . Deploy a single specific worker (e.g. after a custom logic update) hoox deploy worker trade-worker ` Critical Post-Deployment Automation Once hoox deploy all finishes uploading the workers, you must run three final scripts to link webhooks and sync environment databases: `bash A. Register your private Telegram Bot webhook with Cloudflare hoox deploy telegram-webhook B. Auto-update and bind internal Service URLs across all workers hoox deploy update-internal-urls C. Sync and apply the default CONFIGKV manifest variables hoox deploy kv-config ` --- ️ Next.js Dashboard Deployment (OpenNext) The Hoox Command Center is a modern Next.js web application that runs directly on Cloudflare Workers using the OpenNext adapter. When you run hoox deploy dashboard: . The CLI compiles the Next.js app using the Turbopack build engine. . The OpenNext compiler bundles the application logic into a single Edge-compliant V worker file: .open-next/worker.js. . All static files (images, JS chunks, CSS) are isolated under .open-next/assets/. . The CLI uses wrangler to deploy the worker and binds the static assets to Cloudflare's ASSETS binding, serving pages at sub-millisecond speeds. `bash Build and deploy the Next.js Dashboard to Cloudflare Workers hoox deploy dashboard ` --- Routine Update & Upgrade Workflow To pull the latest platform releases, run local tests, and update your active production edge: `bash . Fetch latest changes and update git submodules recursively git pull --recurse-submodules . Install updated dependencies bun install . Execute the full local CI verification pipeline hoox test . Roll out updates globally to the Cloudflare Edge hoox deploy all --auto ` --- ️ Post-Deployment Troubleshooting Matrix | Error Code / Symptom | Primary Root Cause | Guided Resolution | | :---------------------------- | :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------- | | Bad Gateway | Service binding target is missing or has crashed. | Ensure the dependency worker (e.g., trade-worker) has been deployed successfully. Run hoox deploy all to rebuild all bonds. | | Service Unavailable | The Global Kill Switch is active in KV. | Verify switch state: hoox monitor kill-switch show. If safe, restore trading: hoox monitor kill-switch off. | | Unauthorized | Webhook request failed passkey check. | Audit KV authorization key: hoox config kv get webhooks:apikey. Verify the payload apiKey matches this value. | | Conflict` | Durable Object intercepted a duplicate trace ID. | Verify TV alert settings. Do not configure rapid-fire duplicate alerts within the same minute unless idempotency keys are unique. | --- Tip: By utilizing Smart Placement in your production builds, Cloudflare will automatically route execution to the edge nodes located geographically closest to your exchanges (Frankfurt, Tokyo), ensuring high-speed fills! Next Steps Real-Time Observability & Monitoring — Audit live fills, tail console logs, and run health diagnostics. System Self-Healing & Repair — Rebuild broken bindings and recover from deployment anomalies. FILE: docs/enduser/guides/repair.md ️ Self-Healing & Repair Algorithmic trading environments must be resilient and self-healing. If you experience deployment failures, database routing discrepancies, expired authentication tokens, or missing git submodules, the Hoox CLI features a dedicated hoox repair command group designed to diagnose issues, check infrastructure status, and recover your workspace automatically. --- . Running the -Step System Diagnostics If your trading gateway throws errors or the dashboard reports connection issues, run a comprehensive diagnostic sweep: ``bash Execute the automated -step repair check hoox repair check ` The diagnostics engine runs a strict, sequential analysis of your entire monorepo environment: ` ┌────────────────────────────────────────────────────────┐ │ hoox Repair Diagnostic Checklist │ ├────────────────────────────────────────────────────────┤ │ [Step ] Submodule Integrity ......... COMPLETED │ │ [Step ] Dependency Resolutions ....... COMPLETED │ │ [Step ] TypeScript Type Safety ...... COMPLETED │ │ [Step ] Cloudflare Edge Bindings .... COMPLETED │ │ [Step ] Hardware Secrets Validation . COMPLETED │ │ │ │ Diagnostic Result: errors detected │ └────────────────────────────────────────────────────────┘ ` . Submodule Check: Verifies that all worker folders under workers/ are fully populated and registered in Git. . Dependency Check: Audits nodemodules across Bun workspaces for missing or duplicate libraries. . Type Safety Check: Compiles the CLI and shared packages to catch syntax or interface errors. . Edge Bindings Check: Connects to Cloudflare’s APIs to verify that your D, KV, and Queue namespaces physically exist on your account. . Secrets Check: Audits your Workers Secrets to ensure exchange keys and Telegram tokens are securely bound. --- . Targeted Component Repairs If a diagnostic check fails, you do not need to redeploy the entire stack. You can run highly targeted repairs: `bash A. Re-verify, provision, and repair missing Cloudflare bindings hoox repair infra B. Re-audit and sync encrypted Workers Secrets to Cloudflare hoox repair secrets C. Reset the CONFIGKV configuration namespace to default variables hoox repair kv D. Re-apply drizzle DQL schemas and run pending D database migrations hoox repair db E. Rebuild and redeploy a single, degraded worker hoox repair worker trade-worker ` --- . Full System Interactive Rebuild In the event of a catastrophic system failure (e.g. lost Cloudflare credentials, corrupted SQLite files, or major monorepo drift), you can execute a full, interactive self-healing rebuild: `bash Execute an interactive, guided workspace rebuild hoox repair rebuild ` The Rebuild Sequence When triggered, the CLI walks you through a structured recovery protocol: . D Database Backup: Automatically exports your current D ledger as a secure .sql file in backups/recovery-pre-rebuild.sql. . Infrastructure Tear-Down: Deletes corrupted D, KV, and Queue instances. . Fresh Provisioning: Recreates all database tables and config buckets on Cloudflare. . Sequenced Redeployment: Re-compiles and deploys all edge workers in correct dependency sequence. . Database Seeding: Restores your backup SQL data and re-applies schema migrations. . KV Sync: Applies the -key configuration manifest defaults. Danger: The hoox repair rebuild command performs destructive resets on D and KV instances. Ensure you carefully read the interactive prompts and confirm database backup completion before letting the script proceed! --- . Common Troubleshooting Scenarios | Symptom / Failure | Primary Root Cause | CLI Healing Action | | :----------------------------- | :---------------------------------------------------- | :---------------------------------------------------------------------------------------- | | bun install or build crashes | Git submodules are empty or out of sync. | git submodule update --init --recursive | | DERROR: no such table | SQLite D tables were not initialized. | hoox db apply --remote | | Internal Server Error | Missing or rotated exchange API secrets. | hoox secrets set BYBITAPIKEY "key" followed by hoox deploy update-internal-urls. | | Telegram Bot is mute | BotFather token is wrong, or webhook is unregistered. | hoox secrets set TELEGRAMBOT_TOKEN "token" followed by hoox deploy telegram-webhook`. | Next Steps Monitoring Operations Guide — Audit system status, tail console logs, and verify fills. CLI Reference Manual — Review all CLI commands, options, and JSON flags. FILE: docs/enduser/tutorials/tradingview-webhook.md TradingView Webhook Integration Connecting TradingView Alerts directly to your Hoox edge gateway is the most common way to automate your trading strategies. By combining TradingView's advanced charting engines with Hoox's low-latency edge execution, you can trigger orders instantly based on mathematical indicators, chart patterns, or custom Pine Script v logic. This tutorial walks you through writing a Pine Script v script, setting up a TradingView webhook alert, and testing executions. --- Step : Writing a Pine Script v Signal Indicator To trigger clean trade alerts, use TradingView's Pine Script v. Below is a copy-paste indicator script that evaluates a Moving Average Cross strategy and generates standardized trade alert signals: ``pinescript //@version= indicator("Hoox EMA Cross Signals", overlay=true) // . Inputs & Parameters fastLength = input.int(, title="Fast EMA Length") slowLength = input.int(, title="Slow EMA Length") // . Indicators Calculation fastEMA = ta.ema(close, fastLength) slowEMA = ta.ema(close, slowLength) plot(fastEMA, color=color.blue, title="Fast EMA") plot(slowEMA, color=color.orange, title="Slow EMA") // . Trade Conditions longCondition = ta.crossover(fastEMA, slowEMA) shortCondition = ta.crossunder(fastEMA, slowEMA) plotshape(longCondition, title="Long Cross", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small) plotshape(shortCondition, title="Short Cross", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small) // . Alert Payloads Construction (JSON compliant) longAlertJson = '{"apiKey": "your-hoox-webhook-passkey", "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": }' shortAlertJson = '{"apiKey": "your-hoox-webhook-passkey", "exchange": "bybit", "action": "SHORT", "symbol": "BTCUSDT", "quantity": ., "leverage": }' // . Trigger Alerts if (longCondition) alert(longAlertJson, alert.freqonceperbarclose) if (shortCondition) alert(shortAlertJson, alert.freqonceperbarclose) ` Tip: Replace "your-hoox-webhook-passkey" in your Pine Script with the actual passkey configured in your CONFIGKV store (webhooks:apikey). This is a critical security step—the gateway will reject any alerts with mismatched keys with a Unauthorized error. --- Step : Creating the TradingView Webhook Alert Once your script is saved and added to your chart: . Click the Alarm Clock (Alerts) icon on the top right panel in TradingView. . Select Condition: Choose your indicator "Hoox EMA Cross Signals" and select "Any Alert Function Call" (this directs TradingView to parse the custom JSON payloads from the alert() functions inside your script). . Under Expiration: Select your alert lifespan (Premium accounts support Open-Ended alerts). . Navigate to the Notifications Tab: Check the Webhook URL box. Paste your public Hoox Gateway endpoint URL: https://hoox.alpha-trading.workers.dev/webhook . Navigate to the Settings Tab: In the Message box, type: {{strategy.order.alertmessage}} (if using a Backtesting Strategy) or leave it blank (if using an Indicator, as the JSON payload is already defined inside our alert() function). . Click Create. --- Step : Verifying Execution in Production When the Moving Average crossover occurs on your chart: . TradingView compiles the JSON payload and POSTs it to your edge gateway. . The hoox gateway validates the signature and routes the order to Bybit. . Check the transaction directly in your terminal: `bash hoox monitor trades ` . Stream live gateway telemetry logs to verify execution latency: `bash hoox logs tail hoox ` --- ️ Webhook Troubleshooting Runbook | Symptom / Error | Primary Cause | Resolution | | :------------------------------------ | :-------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------- | | Alert fires but no trade executes | Mismatched API keys or WAF block. | Run hoox logs tail hoox to stream traffic. Check if the client IP was dropped by Cloudflare WAF. | | Unauthorized | Incorrect apiKey in Pine Script. | Run hoox config kv get webhooks:apikey to check your key. Paste the exact string into your Pine Script alert payload. | | Conflict | Double-alert fired within the same bar. | Adjust the alert frequency in Pine Script: use alert.freqonceperbarclose instead of alert.freq_all to prevent rapid-fire retries. | | Invalid Symbol API reject | Symbol format mismatch. | Hoox automatically converts variations (like BTC-USDT or btc/usdt) to BTCUSDT`, but ensure your script sends standard uppercase symbols. | Next Steps Setting Up Telegram Alerts — Integrate Telegram notifications to get fills pushed directly to your phone. API Endpoint Reference — Review full request schemas and status codes. FILE: docs/enduser/tutorials/telegram-bot.md Telegram Bot Setup The telegram-worker is a central operational pillar of the Hoox trading ecosystem. It serves two critical functions: . Push Notifications: Sends instant real-time order fill alerts, daily P&L audits, and system health status updates directly to your mobile phone. . Interactive Command Console: Provides a secure chat terminal allowing you to query open positions, check D balance logs, and trigger the Global Kill Switch directly via Telegram chat. This tutorial guides you through creating a bot, binding secrets, deploying the secure Cloudflare webhook, and using commands. --- Step-by-Step Configuration Path Step : Provision a Bot via BotFather . Open the Telegram app and search for the verified @BotFather account. . Click Start and send the command: ``telegram /newbot ` . Enter a friendly name for your bot (e.g. My Hoox Edge Bot). . Choose a unique username ending in "bot" (e.g. AlphaHooxTradeBot). . BotFather will output your HTTP API Token (save this securely): :AAFkLjL-kLl... --- Step : Retrieve Your Private Chat ID To ensure that only you can command your bot (and to prevent unauthorized users from viewing your trading balances), you must capture your private Telegram Chat ID: . Search for the username @userinfobot in Telegram and start a chat. . The bot will instantly return your numeric Id (e.g., ). --- Step : Inject Credentials via Hoox CLI Bind your bot token and authorized Chat ID as encrypted Workers Secrets in your workspace: `bash Inject the secure Telegram Bot token hoox secrets set TELEGRAMBOTTOKEN ":AAFkLjL-kLl..." Inject your authorized Telegram Chat ID hoox secrets set TELEGRAMCHATID "" ` --- Step : Register the Webhook with Telegram To allow Telegram’s servers to route incoming chat commands straight to your edge worker, you must register your deployed gateway URL as the bot's official webhook handler: `bash Automatically register the webhook endpoint with Telegram's APIs hoox deploy telegram-webhook ` The CLI calls Telegram’s API to configure the route: https://hoox.alpha-trading.workers.dev/telegram-webhook --- ️ Interactive Chat Commands Open your private bot chat in Telegram, click Start, and send the following commands to manage your edge: | Command | Action | Description | | :--------------- | :----------------- | :--------------------------------------------------------------------- | | /start | Onboarding | Verifies connection and returns system welcome message. | | /status | System Audit | Probes all workers and returns online/offline health status. | | /trades | Transaction Log | Retrieves a formatted table of the most recent executed fills. | | /positions | Exposure Audit | Lists all currently active long/short positions with unrealized P&L. | | /killon | Emergency Halt | Instantly activates the Global Kill Switch in KV, halting all trading. | | /killoff | Resume | Deactivates the Global Kill Switch, restoring signal processing. | --- Conversational AI Chat & Chart Audits Beyond static commands, telegram-worker is integrated with Cloudflare Workers AI and the Multi-Provider AI Gateway: Natural Language Queries: You can ask the bot conversational questions like "Should I close my BTC position?" or "Analyze my trade win rate today". The bot queries your D SQL database, aggregates context using Vectorize, and responds with a LLaMA- analytical summary. Chart Image Audits: If you upload a screenshot of a trading chart or a portfolio page, the AI Gateway uses vision models (like Claude . Sonnet or Gemini . Pro) to analyze the chart and return an automated risk audit. --- Warning: The telegram-worker strictly filters all incoming messages. If a message originates from a Chat ID that does not match your authorized TELEGRAMCHATID` secret, it is silently dropped and logged as a security alert, ensuring your account remains % secure. Next Steps Astro Docs Site Config — Review your system environment configurations. Real-Time Observability & Monitoring — Stream console logs and check queue depths. FILE: docs/enduser/tutorials/email-signals.md Email Signal Routing The email-worker is an ancillary input plugin that allows you to trigger automated trades via raw email alerts. While webhooks are the standard path, many legacy systems, charting platforms, or custom newsletters only distribute trade signals via email. This tutorial walks you through setting up email-worker credentials, configuring regex subject scanning patterns, and securely routing messages. --- . Injecting Email Connection Credentials To allow email-worker to log into your dedicated signals inbox, inject your SMTP/IMAP mailbox credentials as encrypted Workers Secrets: ``bash . Inject the IMAP/POP host address hoox secrets set EMAILHOST "imap.securemail.com" . Inject the mailbox username/email address hoox secrets set EMAILUSER "signals@my-trading-app.com" . Inject the secure mailbox app password hoox secrets set EMAILPASS "yourapppasswordhere" ` Warning: Always use a dedicated email address solely for trade signals. Never use your personal inbox. Additionally, configure your email provider (e.g., Gmail, Fastmail) to require an App Password rather than your master account credentials to ensure tight access control. --- . Configuring Regex Parsing Rules in KV Once email-worker establishes connection, it scans the inbox on a background schedule, evaluating incoming subjects and message bodies against Regular Expression (regex) patterns defined in CONFIGKV: `bash A. Define the prefix pattern required in the email subject line hoox config kv set email:scansubject "^TRADE SIGNAL:." B. Define the regex pattern used to extract the target asset token hoox config kv set email:coinpattern "(BTC|ETH|SOL|LINK|AVAX)" C. Define the regex pattern used to resolve trade action hoox config kv set email:actionpattern "(LONG|SHORT|CLOSE|BUY|SELL)" ` The Parsing Mechanism When an email is scanned: . The worker matches the subject. If the subject is "TRADE SIGNAL: Breakout Detected", the check passes. . The worker scans the email body using the regex patterns: Body: "...we are entering a LONG position on SOL/USDT..." Hitting email:coinpattern resolves: SOL Hitting email:actionpattern resolves: LONG (translated internally to BUY). . Automatically triggers an order via the trade-worker service binding. --- ️ . Security Audits: SPF & DKIM Validation To prevent malicious "spoofing" (e.g., an unauthorized sender trying to forge a trade signal to your inbox): Sender Validation: The email-worker parses the email's headers and matches the sender's address against a safe allowlist in KV: email:authorized_senders = ["alerts@tradingview.com"]. DNS Verification: The worker validates the SPF (Sender Policy Framework) and DKIM (DomainKeys Identified Mail) headers to verify that the message physically originated from the authorized domain and was not intercepted. --- . Testing Your Email Pipeline To verify that the email signal ingestion loop works perfectly: . Compose a mock email from your authorized sender address. . Subject: TRADE SIGNAL: Cross Over . Body: Action: SHORT, Symbol: ETHUSDT, Quantity: . . Send to your dedicated inbox. . In your terminal, tail the email worker's runtime logs to confirm the parse and order submission: `bash hoox monitor logs email-worker `` Next Steps Real-Time Observability & Monitoring — Audit executed fills, check logs, and inspect queues. API Endpoint Reference — Review full REST payloads and HTTP error returns. FILE: docs/enduser/reference/cli-commands.md ️ CLI Commands Reference The @jango-blockchained/hoox-cli tool manages the entire monorepo development, provisioning, deployment, monitoring, and self-healing pipelines. This reference provides the complete command tree, positional arguments, optional flags, and concrete examples for all command groups. --- ️ Global Flags These options are registered globally and can be appended to any command: | Flag | Description | Example | | :---------- | :------------------------------------------------------------------ | :------------------------------ | | --json | Outputs machine-parseable JSON format (ideal for script pipelines). | hoox monitor status --json | | --quiet | Suppresses headers, banners, and interactive prompts. | hoox deploy kv-config --quiet | | --help | Prints complete parameter and option listings. | hoox infra d --help | | --version | Outputs active CLI package build version. | hoox --version | --- ️ Command Groups Directory `` hoox Launch TUI (when run with no args) ├── init Interactive multi-phase setup wizard ├── clone [name] Bootstrap workspace from template ├── dev Local development execution engine │ ├── start Start all workers (native or Docker) │ ├── worker Start a single worker │ └── dashboard Start Next.js dashboard dev server ├── deploy Edge deployment pipelines │ ├── all Roll out all workers + dashboard in sequence │ ├── worker Deploy a single edge worker │ ├── dashboard Deploy Next.js dashboard via OpenNext │ ├── telegram-webhook Register Telegram bot webhook API │ ├── update-internal-urls Bind inter-worker Service Binding URLs │ └── kv-config Synchronize KV manifest variables ├── infra Cloudflare resource provisioning IaC │ ├── provision Auto-provision all required services │ ├── d [list/create/delete] Manage D databases │ ├── kv [list/create/delete] Manage KV namespaces │ ├── r [list/create/delete] Manage R object storage buckets │ ├── queues [list/create/delete] Manage Cloudflare Queues │ └── vectorize [create/delete] Manage vector search indexes ├── config Workspace and environmental variables │ ├── env [init/show/validate] Manage .env.local build variables │ ├── kv [set/get/list/delete] Get/Set dynamic KV runtime parameters │ └── show/set View or set wrangler.jsonc values ├── check Toolchain and route diagnostic suite │ ├── prerequisites Validate local machine tool installs │ ├── setup Audit .env configurations │ └── health Probe worker /health endpoints ├── db SQLite D Database administration │ ├── apply Apply DDL schemas to D │ ├── migrate Run schema migrations │ ├── list Display active SQLite tables │ ├── query Execute custom SQL reads │ ├── export Dump database as a secure SQL file │ └── reset Destructive truncate of all tables ├── monitor Observability and emergency controls │ ├── status Probe active worker health routes │ ├── trades [N] Aggregate recent filled transactions │ ├── logs [worker] Tail and inspect time-series logs │ ├── queue-depth Audit message counts in queues │ ├── backup Backup SQL ledger to backups/ │ └── kill-switch [show/on/off] Emergency global trading halt ├── repair System diagnostics & self-healing │ ├── check Run -step checklist │ ├── worker Rebuild a degraded worker │ ├── infra Verify and repair missing edge bindings │ ├── secrets Re-sync hardware secrets │ ├── kv Restore KV manifest defaults │ ├── db Re-apply Drizzle migrations │ └── rebuild Full destructive interactive rebuild ├── logs Time-series log extraction │ ├── tail Stream live edge logging console │ └── download Download logs to a local file ├── test Run verification pipeline (CI) └── waf Auto-configure Cloudflare WAF firewall rules ` --- Key Commands Detail & Examples A. Initialization & Bootstrap `bash Onboard a new machine, configure accounts and select worker profile hoox init Verify that git, bun, wrangler, and docker are correctly configured hoox check prerequisites ` B. Local Development `bash Start all workers in a Docker container stack hoox dev start --runtime docker Start only the Next.js frontend developer server hoox dev dashboard ` C. Edge Provisioning & Deployment `bash Provision all databases, buckets, and queues on your Cloudflare account hoox infra provision Deploy the entire microservices stack in sequence, automatically updating URLs hoox deploy all --auto ` D. Operational Monitoring & Emergency halting `bash Emergency Halt: halt all trade signals globally in under seconds hoox config kv set trade:killswitch true Audit active trade history table hoox monitor trades ` E. Database Administration `bash Query the total sum of fees paid today across Bybit hoox db query "SELECT SUM(fee) FROM trades WHERE createdat >= date('now')" --remote ` F. Self-Healing & Diagnostics `bash Run a full workspace system audit hoox repair check ` --- Tip: Every single subcommand is fully documented locally! Append --help to any command (e.g. hoox config env --help`) to view advanced positional arguments and specific flag options instantly. Next Steps Astro Docs Site Config — Map out your build-time environment configurations. API Endpoint Reference — Analyze REST routes, schemas, and gateway error structures. FILE: docs/enduser/reference/api-endpoints.md API Endpoint Specification This document details the public REST API endpoints exposed by the Hoox gateway (workers/hoox). These endpoints are used to ingest automated trade signals, register Telegram bots, query AI metrics, and check serverless V isolate health status. --- Request Headers & Security Policy Every public HTTP request submitted to the Hoox gateway must include the following headers: ``http Content-Type: application/json Accept: application/json ` CORS & Origin Policies For security, Cross-Origin Resource Sharing (CORS) is disabled by default on the /webhook route—it only accepts direct server-to-server POST requests (e.g. from TradingView or custom server scripts). To interact with the dashboard, the gateway verifies active authorization cookies and tokens inside the V engine context. --- . Ingest Trade Signal Webhook Receives, validates, and routes trade orders to exchange APIs. Endpoint: /webhook Method: POST Request Payload (JSON Schema) `json { "apiKey": "alphasecurekey", "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": , "idempotencyKey": "uuid-bdebd-bd" } ` Response Models A. Success Path (Order Filled Instantly - OK) `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "exchange": "bybit", "symbol": "BTCUSDT", "action": "LONG", "result": { "orderId": "", "status": "Filled", "executedQty": ., "price": ., "timestamp": } } ` B. Queue Failover Path (Exchange Offline / Rate-limited - Accepted) If the exchange is down, the signal is enqueued for guaranteed asynchronous delivery. `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "status": "Enqueued", "message": "Signal enqueued in trade-execution Queue for background execution retry." } ` --- . System Health Check Probes the gateway isolate, validating connections to D databases and CONFIGKV caches. Endpoint: /health Method: GET Success Response ( OK) `json { "status": "ok", "timestamp": , "bindings": { "d": "connected", "kv": "connected", "queue": "active" } } ` --- . Conversational AI Chat & Telemetry Integrates with the agent-worker Multi-Provider AI Gateway. A. Conversational Chat Stream Endpoint: /agent/chat Method: POST Headers: Accept: text/event-stream (Supports Server-Sent Events) Request Payload `json { "prompt": "Evaluate my trade performance over the last hours.", "stream": true, "provider": "anthropic" } ` --- B. AI Gateway Telemetry Endpoint: /agent/usage Method: GET Response Payload ( OK) `json { "success": true, "timestamp": , "usage": { "openai": { "inputTokens": , "outputTokens": , "costUSD": . }, "anthropic": { "inputTokens": , "outputTokens": , "costUSD": . }, "workersAi": { "neuronsUsed": , "costUSD": . } } } ` --- . Standard Platform Error Models When an API check fails, the gateway uses the shared @jango-blockchained/hoox-shared package to return a standardized JSON error format: A. Bad Request (Payload Validation Failure) `json { "success": false, "error": { "code": "VALIDATIONERROR", "message": "Invalid JSON payload structure.", "details": [ { "field": "quantity", "issue": "Must be greater than zero." }, { "field": "exchange", "issue": "Invalid exchange router. Options: binance, bybit, mexc." } ] } } ` B. Unauthorized (Invalid API Key / IP Address) `json { "success": false, "error": { "code": "UNAUTHORIZED", "message": "Authentication failed. Mismatched apiKey or unauthorized origin IP." } } ` C. Conflict (Duplicate Request Intercepted) `json { "success": false, "error": { "code": "DUPLICATEREQUEST", "message": "Order rejected. Durable Object locked: trace ID already processed in the last hours." } } ` D. Service Unavailable (Kill Switch Engaged) `json { "success": false, "error": { "code": "KILLSWITCHACTIVE", "message": "Trading halted globally. The emergency Global Kill Switch is currently turned ON in CONFIG_KV." } } `` --- Tip: Every error code is designed to map directly to a readable prompt in the Telegram bot and Next.js dashboard UI, allowing you to instantly diagnose execution problems. Next Steps Astro Docs Site Config — Map out your build-time environment configurations. CLI Commands Reference — Review all CLI commands, options, and JSON flags. FILE: docs/enduser/reference/configuration.md ️ Configuration Dictionary This document serves as the absolute, exhaustive reference dictionary for every environment variable, encrypted Workers Secret, and dynamic KV runtime setting utilized in the Hoox trading ecosystem. --- . Environment Variables & Secrets Matrix ( Keys) These parameters are configured in your local .env.local file for building/deploying or injected as encrypted Workers Secrets for runtime isolate compute. A. Core Platform & Infrastructure | Variable | Required | Type | Default | Description | | :---------------------- | :------: | :------: | :----------: | :-------------------------------------------------------------------- | | CLOUDFLAREAPITOKEN | Yes | string | — | Cloudflare API Token with Workers, D, and KV read/write permissions. | | CLOUDFLAREACCOUNTID | Yes | string | — | Your -character Cloudflare Dashboard Account hash. | | SUBDOMAINPREFIX | Yes | string | — | Subdomain prefix under which public worker gateways deploy. | | NODEENV | No | string | production | Environment profile: development, staging, or production. | | HOOXAPIURL | No | string | — | Local API target URL (automatically configured during dev runs). | --- B. Exchange API Credentials (Encrypted Secrets) | Variable | Required | Type | Scope | Description | | :------------------- | :------: | :------: | :------------: | :----------------------------------------- | | BYBITAPIKEY | No | string | trade-worker | Bybit order placement account credential. | | BYBITAPISECRET | No | string | trade-worker | Bybit HMAC-SHA private order signature. | | BINANCEAPIKEY | No | string | trade-worker | Binance trade permission credential. | | BINANCEAPISECRET | No | string | trade-worker | Binance private HMAC order signature. | | MEXCAPIKEY | No | string | trade-worker | MEXC trade permission credential. | | MEXCAPISECRET | No | string | trade-worker | MEXC private HMAC order signature. | --- C. Telegram Bot Alerts & Telemetry | Variable | Required | Type | Scope | Description | | :------------------- | :------: | :------: | :---------------: | :-------------------------------------------------------- | | TELEGRAMBOTTOKEN | No | string | telegram-worker | Telegram HTTP API bot auth token from @BotFather. | | TELEGRAMCHATID | No | string | telegram-worker | Authorized numeric Chat ID for pushed fills and commands. | --- D. Multi-Provider AI Credentials | Variable | Required | Type | Scope | Description | | :------------------ | :------: | :------: | :------------: | :------------------------------- | | OPENAIAPIKEY | No | string | agent-worker | OpenAI API access key. | | ANTHROPICAPIKEY | No | string | agent-worker | Anthropic Claude API access key. | | GOOGLEAIAPIKEY | No | string | agent-worker | Google Gemini API access key. | --- E. DeFi & Web Wallet Settings | Variable | Required | Type | Scope | Description | | :----------------- | :------: | :------: | :-----------: | :------------------------------------------------------------ | | ETHMNEMONIC | No | string | web-wallet | Secure or -word seed phrase for on-chain contract swaps. | | RPCPROVIDERURL | No | string | web-wallet | HTTP Ethereum / EVM JSON-RPC provider (e.g. Infura/Alchemy). | --- F. Email Parsing Inbox Connection | Variable | Required | Type | Scope | Description | | :----------- | :------: | :------: | :------------: | :--------------------------------------------- | | EMAILHOST | No | string | email-worker | POP/IMAP mailbox server address. | | EMAILUSER | No | string | email-worker | Target signal mailbox email address. | | EMAILPASS | No | string | email-worker | Secure app password for signal mailbox access. | --- . Dynamic KV Manifest Settings ( Keys) These runtime variables exist inside the CONFIGKV namespace. They are accessed globally at sub-millisecond speeds and take effect instantly upon being modified. | KV Key | Type | Default | Operational Impact | | :--------------------------------- | :-------: | :--------------: | :---------------------------------------------------------------------- | | trade:killswitch | boolean | false | Global emergency halt. If true, all executions halt. | | trade:maxdailydrawdownpercent | number | . | Maximum daily loss before the AI Risk Manager triggers the kill switch. | | webhooks:apikey | string | yourkey | Public webhook passkey checked during signal ingestion. | | webhooks:queuemode | string | queuefailover | Routing behavior: directonly, queuefailover, queueeverywhere. | | exchanges:defaultrouting | string | bybit | Default CEX fallback router: binance, bybit, or mexc. | | routing:dynamic:enabled | boolean | false | Enables/disables dynamically shifting routes based on symbols. | | email:scansubject | string | TRADE | Prefix required in signal email subjects. | | email:coinpattern | string | (BTC\|ETH) | Regex expression used to extract asset tokens from email bodies. | | email:actionpattern | string | (BUY\|SELL) | Regex expression used to resolve buy/sell actions in email bodies. | | email:authorizedsenders | array | [] | List of email addresses authorized to submit trade signals. | | webhook:tradingview:ip_check | boolean | false | Toggles dropping payloads that don't originate from TradingView IPs. | --- Tip: You can sync, check, or reset this entire KV manifest in one command: hoox config kv apply-manifest! Next Steps -Minute Quick Start Guide — Deploy all workers and fire your first simulated webhook. API Endpoint Reference — Review full REST schemas, parameters, and error models. FILE: docs/devops/home.md ️ DevOps Manual Welcome to the Hoox DevOps & System Operations Manual. This manual is the primary, production-grade reference for system administrators, security engineers, and platform operators responsible for provisioning edge databases, orchestrating secure V service bindings, deploying multi-exchange execution workers, auditing secrets, and monitoring system health. --- ️ Operator's System Directory The DevOps manual is structured into five core architectural operational layers: . Operations & Setup Runbooks Complete guides for bootstrapping environments, managing interactive terminal dashboards, and diagnosing local runner configurations: Operations & Troubleshooting — Core operations manual, -key environment variable matrices, and diagnostic codes. Core Installation Flow — Guided, step-by-step local machine and edge provision setup. Terminal UI Cockpit Development — Code architectures, stores, and operations of the OpenTUI monitor. . ️ Architectural Specifications Deep dives into latency structures, isolation parameters, and bindings linkages: System Topology Overview — Architectural layout, regional edge clustering, and scaling limits. Isolate Communication — Deep dive into Service Bindings, zero-TCP routing, and V engines. Data Flow Architecture — Flowcharts for trade execution, backup queues, and cron risk monitoring. Bindings Matrix — Exact mapping of D, KV, Queues, R, and Service Bindings. Storage Engineering — Persistent storage boundaries, SQLite DDL parameters, and R buckets. Internal Endpoints Map — Sub-millisecond binding paths and routing maps. Visual Tokens & Design System — Monochromatic token mappings and visual SVGs catalog. . ️ Edge Worker Microservices ( Profiles) Individual developer profiles for each running isolate, cataloging bindings, custom middlewares, and API formats: hoox Gateway · trade-worker · agent-worker · telegram-worker d-worker · web-wallet-worker · email-worker · analytics-worker report-worker · dashboard (Next.js OpenNext) . Deployment, WAF, & CI/CD Pipelines Rollout manuals, Access gates, and GitHub Actions telemetry: Production Deployment — Wrangler commands, Account provisioning, and production variables. CI/CD Workflow pipelines — GitHub Actions secrets, syntax tests, and automated edge uploads. Monitoring & Telemetry — Live wrangler logs streaming and custom Analytics Engine metrics. Cloudflare Zero Trust Corridor — Setting up Access client corridors, IP firewalls, and WAF rules. . Developer & API Reference TypeScript interfaces, compiler settings, Bun test specs, and HTTP schemas: Wrangler Dev Setup · Testing Standards · Debugging Runbook Exposed API Routes · Request Payloads · Standard Responses CLI Commands Engine — Command-line argument parsing, binary execution, and JSON flags. --- Tip: First time deploying a Hoox workspace to production? Start with the Production Deployment Manual to verify your Cloudflare Account permissions and execute sequencial deployments seamlessly. Quick Links & Offline Reference End-User Documentation Hub — Standard setup, cURL webhooks, and TradingView Pine Scripts. Hoox Git Submodules — Central monorepo codebase. Download Enduser Full PDF Manual — Complete concatenated offline guide. Download DevOps Full PDF Manual — Complete concatenated offline DevOps spec. View Consolidated LLM Context Text — Giant single-file text format for AI/LLM models. FILE: docs/devops/setup_and_operations.md Operations & Runbook This manual is the primary, production-grade operations runbook for Hoox administrators. It outlines the complete system topology, toolchain prerequisites, environment variables, sequential deployment protocols, and guided troubleshooting matrices. --- . Complete Environment Variables Matrix ( Keys) These variables are defined in .env.local for local building/deploying or injected as encrypted Workers Secrets for runtime isolate compute. A. Core Platform & Infrastructure CLOUDFLAREAPITOKEN: Cloudflare API Token with Workers, D, and KV read/write permissions. CLOUDFLAREACCOUNTID: Your unique -character Cloudflare dashboard account hash. SUBDOMAINPREFIX: Subdomain prefix under which your public gateway routes compile. NODEENV: Target environment profile: development, staging, or production. HOOXAPIURL: Local API target URL (automatically configured during dev runs). B. Exchange API Credentials (Encrypted Secrets) BYBITAPIKEY & BYBITAPISECRET: Bybit order placement account key and HMAC-SHA signature key. BINANCEAPIKEY & BINANCEAPISECRET: Binance trade permission key and private HMAC signature. MEXCAPIKEY & MEXCAPISECRET: MEXC trade permission key and private HMAC signature. C. Telegram Bot Alerts & Telemetry TELEGRAMBOTTOKEN: Telegram bot token from @BotFather. TELEGRAMCHATID: Authorized numeric Chat ID for pushed fills and commands. D. Multi-Provider AI Credentials OPENAIAPIKEY: OpenAI API access key. ANTHROPICAPIKEY: Anthropic Claude API access key. GOOGLEAIAPIKEY: Google Gemini API access key. E. DeFi & Web Wallet Settings ETHMNEMONIC: Secure or -word seed phrase for EVM swaps. RPCPROVIDERURL: HTTP Ethereum / EVM JSON-RPC provider (e.g. Infura/Alchemy). F. Email Parsing Inbox Connection EMAILHOST: POP/IMAP mailbox server address. EMAILUSER: Target signal mailbox email address. EMAILPASS: Secure app password for mailbox access. --- . Worker Deployment Sequence Because Hoox microservices communicate internally using fast-path Service Bindings, they have strict compile-time and deploy-time dependencies. Deploy workers in the following strict sequential hierarchy: `` . analytics-worker (No dependencies) . report-worker (Depends on: analytics-worker) . d-worker (Depends on: analytics-worker) . telegram-worker (Depends on: trade-worker, hoox, analytics-worker) . web-wallet-worker (Depends on: telegram-worker, analytics-worker) . email-worker (Depends on: trade-worker, analytics-worker) . trade-worker (Depends on: d-worker, telegram-worker, analytics-worker) . agent-worker (Depends on: d-worker, trade-worker, telegram-worker, analytics-worker) . hoox Gateway (Depends on: trade-worker, telegram-worker, analytics-worker) . dashboard (Depends on: all services being live) ` `bash Automated Sequenced Deployment via CLI hoox deploy all --auto Or deploy a single specific worker hoox deploy worker trade-worker ` --- . Secret Management Runbook Secrets are securely uploaded to Cloudflare's hardware key vaults using the CLI: `bash Inject Bybit Credentials hoox secrets set BYBITAPIKEY "yourbybitkey" hoox secrets set BYBITAPISECRET "yourbybitsecret" Check active secret synchronization on Cloudflare hoox secrets check ` --- . Global Kill Switch & Emergency Operations The Global Kill Switch is your emergency brake. Stored inside the sub-millisecond CONFIGKV namespace, flipping this parameter instantly blocks all incoming trade signals globally in under seconds: `bash View active state of the Kill Switch hoox monitor kill-switch show Emergency HALT - disable all trade execution immediately hoox monitor kill-switch on Resume normal operations hoox monitor kill-switch off ` --- ️ . Troubleshooting & Diagnostics Alt Alternate Screen Buffer Cleanup If you force-close the terminal and find that your prompt remains garbled, execute a terminal reset: `bash reset or tput reset ` Bad Gateway Root Cause: Service binding target is missing or has crashed. Fix: Ensure the dependency worker (e.g. trade-worker) has been deployed successfully. Run hoox deploy all to rebuild all bonds. Service Unavailable Root Cause: The Global Kill Switch is active in KV. Fix: Verify switch state: hoox monitor kill-switch show. If safe, restore trading: hoox monitor kill-switch off`. Next Steps Astro Docs Site Config — Map out your build-time environment configurations. Architecture & Edge Topology — In-depth architectural outlines and Service Bindings routing maps. FILE: docs/devops/installation-flow.md Cloudflare Workers Setup Flow This document details the step-by-step installation, bootstrapping, and validation workflows executed by the Hoox CLI during project initialization. Developer Note: The Hoox CLI enforces strict type validation for all configuration files via the Config and WorkerConfig TypeScript interfaces defined in packages/cli/src/core/types.ts. Avoid using as any or type bypasses when extending wrangler parameters to prevent build-time CLI crashes. --- ️ Interactive Setup Wizard (hoox init) To start the system bootstrap, run the init wizard from the monorepo root: ``bash hoox init ` The setup wizard guides you through critical onboarding phases: Phase : Toolchain Diagnostics Probes your machine to verify that essential developer tools are accessible: Bun: Used for monorepo package management, CLI binaries execution, and fast unit testing. Git: Used to verify recursive cloning of worker submodules. Wrangler: Cloudflare's CLI used to login, tail logs, and upload V isolates. --- Phase : Global Configuration Mapping Configures your master workspace credentials stored in .env.local and wrangler.jsonc: Cloudflare API Token: Generates and checks permissions. Cloudflare Account ID: Uniquely identifies your hosting space. Subdomain Prefix: Defines the worker routing domain (e.g. hoox routes to https://hoox.alpha-trading.workers.dev). --- Phase : Microservice Profile Selection Lets you selectively enable or disable specific workers from the workers/ directory based on your trading intent (e.g., cross-margin futures execution vs. Web DeFi wallet swaps). Disabling unnecessary workers saves deployment bandwidth and keeps resource bindings clean. --- Phase : SQLite Database Provisioning Checks if enabled workers require persistent D storage. If yes, it creates the database and initializes database schemas: `bash Done automatically by the wizard wrangler d create trade-data-db ` --- Phase : Manifest Compilation Consolidates all chosen parameters and writes your central wrangler.jsonc file, mapping out variables and bindings for every worker. --- Phase : Workers Secrets Injection Secures sensitive credentials (exchange API keys, Telegram tokens, AI API keys) by encrypting and uploading them to Cloudflare as encrypted Workers Secrets. --- Phase : Initial Rollout Compiles, lint-checks, type-checks, and deploys all enabled workers to Cloudflare's edge in the correct mathematical dependency sequence. --- Configuration Files Spec The Hoox platform uses a dual configuration file architecture to track workspace states: A. wrangler.jsonc (Central Settings) This file represents the declarative single source of truth for your monorepo's active workers: `jsonc { "global": { "cloudflareaccountid": "debcebeabecbcdec", "subdomainprefix": "cryptolinx", }, "workers": { "d-worker": { "enabled": true, "path": "workers/d-worker", "vars": { "databasename": "trade-data-db" }, }, "trade-worker": { "enabled": true, "path": "workers/trade-worker", "secrets": ["BYBITAPIKEY", "BYBITAPISECRET", "TELEGRAMBOTTOKEN"], }, }, } ` --- B. .install-wizard-state.json (Onboarding State) During the interactive setup, the CLI caches your current step and intermediate inputs inside .install-wizard-state.json at your project root. State Recovery: If your terminal session is disconnected or wrangler login prompts timeout, you can run hoox init again. The CLI will detect the state file and seamlessly resume your onboarding from the last incomplete step. Auto-Cleanup: Upon final completion of Phase , the state file is automatically purged to keep your root directory clean. --- Secret Bindings Architecture Hoox utilizes Cloudflare's hardware-secured Secret Store to bind environment credentials to V isolates without exposing them in git history. Local Mocking (.dev.vars) During local development, wrangler dev looks for a local, gitignored file called .dev.vars inside each worker's directory to simulate secrets: `bash workers/trade-worker/.dev.vars BYBITAPIKEY=mockbybitdevelopmentkey BYBITAPISECRET=mockbybitdevelopmentsecret ` --- Production Secret Bindings When deploying to production, wrangler binds these variables using direct encrypted environments in your worker's wrangler configuration: `json { "secretsstore": { "bindings": [ { "binding": "BYBITAPIKEYBINDING", "storeid": "bcafddcefd", "secretname": "BYBITAPIKEY" } ] } } ` This guarantees that secrets are never logged, never cached in plain text on disk, and are only accessible inside your worker's sandboxed execution isolate memory. --- Tip: Made a configuration mistake or changed your subdomain? You can re-run hoox check-setup` at any time to execute high-integrity type validation and ensure all bindings and configurations match production examples perfectly! Next Steps DevOps Setup & Operations Manual — Dive into complete operations, variable matrices, and troubleshooting. Terminal UI Cockpit — Run, hot-reload, and monitor your local workers via TUI. FILE: docs/devops/tui.md ️ TUI Code Architecture The Hoox Terminal UI (TUI) is a full-screen, keyboard-driven operations center built natively using OpenTUI, React , and Zustand state stores. This document outlines the TUI code architecture, directory structure, data flows, and error recovery mechanisms for senior engineers and system operators. --- ️ Architectural Blueprint The cockpit is designed as a modular Single Page Terminal Application (SPTA), structured around three decoupled layers: --- ️ Store Architecture & State Flow TUI state is managed using three specialized Zustand stores combined with Immer middleware to allow safe, mutating updates to deeply nested state trees: . UI Store (src/stores/ui-store.ts) State Managed: Active view index, sidebar visibility toggles, active modal overlays (e.g. confirmation dialogs), and the Command Palette fuzzy-search string. Key Actions: setView(index), toggleSidebar(), pushModal(modal), popModal(). . Service Store (src/stores/service-store.ts) State Managed: Real-time worker health matrices, trade logs history, analytics telemetry, log buffers, and the connection status. Key Actions: updateWorkerStatus(name, status), addLogEntry(worker, log), addTradeFill(trade), setConnectionState(state). . Config Store (src/stores/config-store.ts) State Managed: UI themes (dark/light), data refresh intervals, Telegram alert routes, and custom keyboard binds. Persistence: Automatically serialized and saved to disk at ~/.hoox/config.json. --- Connection Resilience State Machine The TUI maintains a strict connection lifecycle to track connectivity to the local API server or remote worker tunnels: Exponential Backoff Intervals If the API connection drops out: . The status bar immediately transitions to a yellow/orange pulsing RECONNECTING dot. . The polling engine schedules reconnect attempts using exponential backoff: $$\text{Backoff Interval} = \min(^{\text{retry\count}} \times \text{ms}, \text{ms})$$ . Active views display a subtle "Stale Data: Last updated Xm ago" warning badge, allowing the operator to read static stats without freezing the screen layout. . After failed attempts, the state transitions to OFFLINE (red dot). The engine continues running minimal background checks and restores live statistics automatically as soon as the API recovers. --- Dual-Channel Data Communication To maintain high performance and low thread overhead: . REST API (Polling Channel) Frequency: Configurable in CONFIGKV (default: every seconds). Data Transferred: Core worker health status checks, database statistics, and configuration files. . Server-Sent Events (Real-Time Ingestion Channel) Protocol: HTTP SSE streaming. Data Transferred: High-frequency real-time logs and exchange trade fills. Memory Buffer Constraints: To prevent memory leaks during extended sessions in the terminal, the TUI implements strict ring-buffer limits: Trade Feed: entries max. Log Stream: , lines max. Alert Console: lines max. When a buffer limit is hit, the oldest entry is automatically dropped. --- ️ Double-Layer Crash Protection Since the TUI is designed to be an enterprise-grade command center, a rendering bug or syntax error in one pane must never crash the entire application. Layer : Per-View Error Boundaries Every view (e.g. WorkerDetail, ConfigEditor) is wrapped inside a custom React ErrorBoundary component: If a rendering exception occurs within the ConfigEditor (e.g. due to a Tree-sitter WASM parsing exception), the error is caught, a clean error panel is displayed inside that specific tab, and a [Retry] button is mounted. No Side Effects: The rest of the terminal, sidebar, and status bar continue running normally, ensuring uninterrupted monitoring. Layer : Process-Level Trap (CrashRecoveryApp) If an uncaught exception or unhandled promise rejection occurs at the root level of the Node/Bun process: . The process trap intercepts the signal and prevents a hard exit to a broken shell. . Displays a styled Terminal Recovery Screen detailing the error stack. . Offers three instant recovery options: [Restart]: Cleans Zustand stores and performs a fresh reboot. [Safe Mode]: Disables heavy analytics feeds and WASM syntax highlighting to restore operations in minimal capacity. [Report Bug]: Automatically exports the error trace and logs to a file at logs/crash-report.log. --- Tip: Adding custom components or views? Ensure all JSX elements comply with OpenTUI's native terminal components (using only lowercase intrinsic tags like `, , and ). Absolute layout dimensions must be integers representing terminal characters or "%"` values. Next Steps DevOps Setup & Operations Manual — Complete runbook, variable matrices, and troubleshooting. Architecture & Edge Topology — In-depth architectural outlines and Service Bindings routing maps. FILE: docs/devops/architecture/overview.md ️ System Topology & Overview Hoox is an enterprise-grade, serverless algorithmic trading platform built entirely on Cloudflare's Edge V isolates and globally distributed resources. By using a modular, service-oriented architecture, Hoox decomposes complex trading processes into ten highly specialized micro-workers. These workers communicate privately in microseconds, auto-scale globally near exchange servers, and store transaction logs in localized databases—all while running within Cloudflare's $ free tiers. --- ️ High-Level System Architecture The ecosystem splits public-facing ingress points from private internal compute layers: --- Comprehensive Micro-Worker Catalog | Worker Name | Runtime Scope | Cron Trigger | Public Routing | Smart Placement | Primary Observability | | :--------------------- | :--------------: | :----------: | :------------------: | :------------------------: | :-------------------: | | hoox | Gateway Router | No | Yes (/webhook) | Yes (Fast path) | Time-series Telemetry | | trade-worker | Order Execution | No | No (Isolated) | Yes (Exchange Proxied) | Execution Logs | | agent-worker | Risk Management | Cron / | No (Isolated) | Yes (Account Auditing) | Alert Logs | | telegram-worker | Alerts & Chat | No | No (Isolated) | Yes (Telegram APIs) | Command Logs | | d-worker | SQLite Manager | No | No (Isolated) | Yes (SQLite Bound) | Query Latency | | report-worker | Puppeteer PDF | Cron , | No (Isolated) | Yes (Rendering APIs) | Print Status | | email-worker | IMAP Parsing | Cron / | No (Isolated) | No | Parse Statistics | | web-wallet | DeFi Swap Engine | No | No (Isolated) | No | Tx Sign Logs | | analytics-worker | Observability | No | No (Isolated) | No | Metrics Dataset | --- ️ The -Layer Security Architecture Security is designed as concentric protective corridors: `` [ WAF: IP Range Allow-list ] -> [ Gateway: Webhook Passkey ] -> [ Isolation: Service Bindings ] -> [ Worker Auth: INTERNALKEY ] -> [ Mutex: Durable Objects ] ` Layer : Edge-Level Firewall & WAF Cloudflare’s global WAF drop connections immediately at the edge if: The payload does not originate from verified TradingView webhook IP ranges. The request rate exceeds threshold ceilings ( requests/minute). --- Layer : Webhook Passkey Authentication The hoox gateway validates that the payload apiKey string exactly matches the encrypted webhooks:apikey stored inside your CONFIGKV namespace. Mismatched signals are instantly dropped with a Unauthorized response. --- Layer : Service Binding Encrypted Isolation Internal workers (trade-worker, d-worker, agent-worker) expose zero public HTTP endpoints. They cannot be targeted or accessed from the public internet. They can only be invoked internally by other V isolates using Cloudflare Service Bindings. --- Layer : Standardized Internal Authorization To prevent internal bypass or privilege escalation, all internal microservice boundaries enforce a strict bearer authorization check: All internal workers (hoox, trade-worker, d-worker, agent-worker, telegram-worker) are bound to the same INTERNALKEY_BINDING secret. Every service-to-service invocation is audited by the shared requireInternalAuth middleware from @jango-blockchained/hoox-shared/middleware`, dropping unauthorized calls. --- Layer : Durable Object Idempotency Locks If the network drops after an order fill, TradingView will resend the webhook. The gateway uses a single-threaded Durable Object to lock the request trace ID. If the transaction ID has already been logged, the duplicate is dropped before hitting exchange APIs, preventing double-ordering. --- Tip: Smart Placement is enabled across all critical execution paths. This ensures that even though your webhook might hit a Cloudflare edge node in London, the actual transaction logic automatically shifts to Frankfurt or Tokyo (wherever the exchange APIs reside), eliminating network slippage entirely. Next Steps Worker Communication Specifications — Deep dive into service bindings, zero-TCP routing, and V engines. Data Flow Maps — Step-by-step sequence charts of trade executions and cron risk evaluations. FILE: docs/devops/architecture/communication.md Isolate Communication Spec In a traditional server-based monorepo or Docker cluster, microservices communicate over TCP/IP connections using protocols like REST, gRPC, or WebSockets. These introduce significant networking overhead: DNS resolution, TCP handshakes, TLS negotiation, and data serialization. Hoox completely bypasses the networking stack by leveraging Cloudflare's Service Bindings. This document details the low-level V routing mechanics, internal authentication protocols, and diagnostic mocking configurations of the Hoox communication layer. --- . Service Bindings: Zero-Overhead V Routing Cloudflare Service Bindings allow one edge worker to call another without ever hitting the public internet. The Under-the-Hood V Mechanics Direct Execution: When hoox calls env.TRADESERVICE.fetch(), the Cloudflare runtime does not construct a TCP packet or route it through a virtual network. Instead, the runtime spawns the target worker's V isolate in the same physical memory thread and executes its entry point function directly. Zero Serialization Overhead: Payloads are passed directly as active V memory pointers, cutting JSON serialization and parsing costs. Latency Guarantee: Internal isolate transitions are completed in under microsecond, making microservice communication practically instant. ``jsonc // Declarative bindings inside workers/hoox/wrangler.jsonc { "services": [ { "binding": "TRADESERVICE", "service": "trade-worker" }, { "binding": "TELEGRAMSERVICE", "service": "telegram-worker" }, { "binding": "ANALYTICSSERVICE", "service": "analytics-worker" }, ], } ` --- . Complete Service Invocations Implementation Below is the standard, production-grade template used to route authenticated, structured HTTP payloads between workers: `typescript import { requireInternalAuth } from "@jango-blockchained/hoox-shared/middleware"; export interface Env { TRADESERVICE: Fetcher; // Service Binding Fetcher INTERNALKEYBINDING: string; // Authorized Internal Key secret } export default { async fetch(request: Request, env: Env): Promise { // . Build and validate payload const payload = { exchange: "bybit", action: "LONG", symbol: "BTCUSDT", quantity: ., }; // . Invoke the internal trade-worker V isolate try { const tradeResponse = await env.TRADESERVICE.fetch( "https://trade-worker/webhook", { method: "POST", headers: { "Content-Type": "application/json", "X-Internal-Auth-Key": env.INTERNALKEYBINDING, // Bearer Auth }, body: JSON.stringify(payload), } ); if (!tradeResponse.ok) { throw new Error( Internal binding returned HTTP status: ${tradeResponse.status} ); } const result = await tradeResponse.json(); return new Response(JSON.stringify({ success: true, result }), { status: , headers: { "Content-Type": "application/json" }, }); } catch (error: any) { return new Response( JSON.stringify({ success: false, error: error.message }), { status: , // Bad Gateway headers: { "Content-Type": "application/json" }, } ); } }, }; ` --- . Internal Authorization Middleware Standard To prevent unauthorized, cross-tenant, or direct internal calls, every internal endpoint is secured using the shared requireInternalAuth middleware from @jango-blockchained/hoox-shared/middleware: `typescript import { requireInternalAuth } from "@jango-blockchained/hoox-shared/middleware"; // Inside target worker's router or fetch handler: export async function handleRequest( request: Request, env: Env ): Promise { // Returns Unauthorized Response if the header is invalid or missing const authError = requireInternalAuth(request, env, "INTERNALKEYBINDING"); if (authError) return authError; // Key is valid — continue execution return new Response("Authorized", { status: }); } ` Standardization Alert: Every single internal worker (hoox, trade-worker, d-worker, agent-worker, telegram-worker, email-worker) binds the exact same secret name: INTERNALKEYBINDING. This eliminates variable footprint drift and simplifies secret deployments across your workspace. --- . Testing & Mocking Service Bindings During local testing (via native bun test), you can mock the Service Binding Fetcher object cleanly to run full-coverage unit tests without provisioning real Cloudflare APIs: `typescript import { expect, test, mock } from "bun:test"; test("Should mock internal trade-worker service bindings", async () => { const mockEnv = { INTERNALKEYBINDING: "secretlocaltestkey", TRADESERVICE: { fetch: async (url: string, init?: RequestInit) => { // Confirm headers are present and valid const headers = init?.headers as Record; if (headers["X-Internal-Auth-Key"] !== "secretlocaltestkey") { return new Response(JSON.stringify({ success: false }), { status: , }); } return new Response( JSON.stringify({ success: true, orderId: "mockorder", }), { status: } ); }, } as Fetcher, }; // Run call test assertions const res = await mockEnv.TRADESERVICE.fetch( "https://trade-worker/webhook", { headers: { "X-Internal-Auth-Key": "secretlocaltestkey" }, } ); const data = await res.json(); expect(res.status).toBe(); expect(data.orderId).toBe("mockorder_"); }); `` Next Steps Data Flow Mapping — Step-by-step sequence charts of trade executions, backups, and metrics. Bindings Catalog — Review complete environment namespaces and bound objects. FILE: docs/devops/architecture/data-flow.md System Data Routing Spec Hoox operates as a highly orchestrated distributed event loop. Because execution logic is split into isolated compute nodes, data flows recursively through multiple V transitions, asynchronous queues, time-series datasets, and database ledgers. This document provides complete, low-level technical specifications and Mermaid sequence diagrams for our four primary data routing pipelines: Webhook Trade execution, AI Risk management, PDF browser rendering, and Observability tracking. --- . Webhook to Trade Execution Flow (High-Speed Path) This is the primary transaction pipeline. When a trade signal is received, the system validates the payload, locks the trace ID, executes the order at the edge closest to the exchange, records the fill, and alerts the user. --- . Autonomous AI Risk Monitoring Flow (Cron Cycle) Running on a strict -minute Cron schedule, the risk management loop queries SQLite records, audits active exposures, calculates trailing stop deviations, and manages emergency halts. --- . PDF Portfolio Report Rendering Flow Runs twice daily to automate HTML dashboard rendering, compile PDFs via Puppeteer on the edge, offload to R storage, and dispatch download corridors. --- . Observability & Time-Series Analytics Flow To maintain complete cross-worker telemetry without blocking critical order threads, Hoox routes analytics data points asynchronously to a dedicated metrics warehouse. --- . Global Data Persistence Mapping | Storage Platform | Namespace / Database Name | Data Payload Details | Associated Compute Workers | | :--------------- | :----------------------------- | :------------------------------------------------------------- | :------------------------------------------ | | D Database | trade-data-db (SQLite) | Executed fills, open position matrices, Drizzle tracking logs. | d-worker, trade-worker, agent-worker | | CONFIGKV | CONFIGKV (Key-Value) | -key global runtime manifest, emergency Kill Switch. | All Workers + Next.js Dashboard | | SESSIONSKV | SESSIONSKV (Key-Value) | Session access states and API authorization cookies. | hoox Gateway | | R Storage | trade-reports (S Bucket) | Compiled PDF portfolio reports. | report-worker | | R Storage | hoox-system-logs (S Bucket) | Verbose JSON exchange API payloads (REST & WebSocket logs). | trade-worker | | Vectorize | my-rag-index (Vector DB) | Semantic chat and history vector embeddings. | telegram-worker | Next Steps Bindings Catalog — Check wrangler settings and resource declarations. Storage Engineering Manual — Dive into Drizzle database schemas and SQLite properties. FILE: docs/devops/architecture/bindings.md Infrastructure Bindings Index In Cloudflare’s serverless architecture, bindings represent the declarative bridges linking your isolate compute logic to other internal microservices and storage platforms. This document serves as the absolute, production-grade reference registry for all resource bindings configured in the Hoox monorepo. --- . Secrets & Environment Variables Matrix These parameters represent encrypted variables injected directly into V execution isolates at runtime. | Variable Name | Type | Bound Workers | Operational Impact | | :---------------------------- | :----: | :--------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- | | INTERNALKEYBINDING | Secret | hoox, trade-worker, d-worker, telegram-worker, email-worker | Cryptographic auth key used by the requireInternalAuth middleware to validate service-to-service calls. | | TGBOTTOKENBINDING | Secret | telegram-worker | Secret bot token issued by @BotFather to authenticate Telegram API commands and alerts. | | TELEGRAMSECRETTOKEN | Secret | telegram-worker | Webhook verification token to authorize Telegram push events. | | WEBHOOKAPIKEY | Secret | hoox | General passkey validated during incoming webhook signal requests. | | BYBITAPIKEY / SECRET | Secret | trade-worker | Credentials used to execute cryptographically signed order routes to Bybit's APIs. | | BINANCEAPIKEY / SECRET | Secret | trade-worker | Credentials used to execute trade routes to Binance's APIs. | | MEXCAPIKEY / SECRET | Secret | trade-worker | Credentials used to execute trade routes to MEXC's APIs. | | CFAPITOKEN | Secret | report-worker | Access token used to invoke the Cloudflare Puppeteer Browser Rendering APIs. | --- . Service Bindings (Compute Connectors) Service Bindings link workers' V runtimes together locally in memory, with microsecond latency and zero external internet hops. | Binding Name | Ingesting Worker | Target Service | Purpose | | :----------------- | :----------------------------------------------------------- | :---------------- | :--------------------------------------------------------- | | TRADESERVICE | hoox, agent-worker, email-worker | trade-worker | Handles leverage calculation, size scaling, and execution. | | TELEGRAMSERVICE | hoox, trade-worker, agent-worker, report-worker | telegram-worker | Dispatches real-time alerts and parses slash commands. | | DSERVICE | trade-worker, agent-worker, report-worker, dashboard | d-worker | Serves as the high-integrity proxy SQL data manager. | | AGENTSERVICE | dashboard | agent-worker | Triggers risk audits, chat streams, and telemetry updates. | --- . KV Namespace Caches Key-Value caches store parameters that require sub-millisecond read access. | Binding Name | Bound Workers | Purpose | | :------------ | :-------------------------- | :---------------------------------------------------------------------------- | | CONFIGKV | All Workers + Dashboard | Primary cache for the -key runtime manifest, rate-limiter, and Kill Switch. | | SESSIONSKV | hoox Gateway | Stores active webhook session credentials and token cookie states. | --- . Asynchronous Queues Queues guarantee message delivery during times of heavy exchange network congestion or API rate limits. | Binding Name | Ingesting Worker | Queue Name | Type | Operational Action | | :------------ | :--------------- | :---------------: | :----------: | :---------------------------------------------------------- | | TRADEQUEUE | hoox Gateway | trade-execution | Producer | Serializes and enqueues signal payloads during failover. | | TRADEQUEUE | trade-worker | trade-execution | Consumer | Pulls enqueued signals and retries executions with backoff. | --- . SQLite-Backed Durable Objects Durable Objects enforce exactly-once execution, preventing catastrophic double-trading. | Binding Name | Bound Worker | Target Class Name | Purpose | | :------------------ | :------------- | :----------------- | :------------------------------------------------------------------------ | | IDEMPOTENCYSTORE | hoox Gateway | IdempotencyStore | Mutex locking engine with local SQLite and auto-alarm garbage collection. | --- . R Object Storage Buckets R Buckets store heavy files with zero bandwidth egress retrieval fees. | Binding Name | Bound Workers | Bucket Name | Target Asset Payload | | :------------------- | :------------------------------ | :----------------- | :---------------------------------------------- | | REPORTSBUCKET | trade-worker, report-worker | trade-reports | Compiled PDF daily/weekly portfolio reports. | | SYSTEMLOGSBUCKET | trade-worker | hoox-system-logs | Verbose exchange API request-response logs. | | UPLOADSBUCKET | telegram-worker | user-uploads | User chart screenshots and conversation images. | --- . D SQLite Databases | Binding Name | Bound Workers | Database Instance Name | Purpose | | :----------- | :------------ | :--------------------- | :-------------------------------------------- | | DB | d-worker | trade-data-db | Primary transactional trade database storage. | --- . Workers AI & Vectorize Indexes | Binding Name | Bound Workers | Target Asset Name | Operational Purpose | | :---------------- | :-------------------------------------------------------- | :---------------- | :------------------------------------------------ | | AI | hoox, trade-worker, agent-worker, telegram-worker | Edge LLM Models | Runs LLaMA- inference, risk analysis, and chat. | | VECTORIZEINDEX | telegram-worker | rag-index | Custom semantic search vector DB for RAG queries. | --- . Puppeteer Browser Rendering The report-worker invokes Cloudflare’s Browser Rendering Chrome isolates using a secure REST API (no binding required): Route: POST https://api.cloudflare.com/client/v/accounts/{account_id}/browser-rendering/pdf Headers: ``http Authorization: Bearer Content-Type: application/json ` JSON Payload: `json { "html": "...", "options": { "format": "A", "printBackground": true } } ` --- Tip: Adding new bindings to your workers? Always update your wrangler.jsonc manifest at the workspace root, and then execute hoox deploy update-internal-urls` to sync bindings and URLs globally! Next Steps Storage & SQLite DDL — Dive into Drizzle schemas, R bucket configurations, and database rules. Production Deployments — Learn how Wrangler compiles and maps these bindings to the live edge. FILE: docs/devops/architecture/storage.md Storage & Data Engineering Spec Hoox operates a multi-tier edge storage topology to balance high-speed read/write performance, relational transactional safety, and long-term analytical capacity. By separating high-frequency dynamic states from static parameters and verbose event logs, Hoox ensures that latency remains in the single-digit milliseconds while keeping storage costs at $/month. --- . The Multi-Tier Storage Architecture Hoox segregates data into four distinct edge storage tiers based on consistency, read/write latency, and size constraints: | Storage primitive | Engine Technology | Consistency Model | Read Latency | Write Latency | Ideal Use Case | | :------------------ | :------------------ | :------------------- | :----------: | :-----------: | :----------------------------------------------------------- | | Durable Objects | In-Memory Mutex | Strong Consistency | Danger: Never attempt to run raw migration files directly on your production D database without first running a backup. Ensure your database status is fully tracked and synchronized using Drizzle migrations: hoox db migrate --remote. Next Steps Internal Endpoints Mapping — Map out exposed ports, URLs, and service bindings. Wrangler Setup & Tooling — Configure Wrangler to bind local D and KV instances for dev testing. FILE: docs/devops/architecture/endpoints.md Internal Endpoints Map This document catalogs all internal REST, service-to-service, and queue endpoints exposed across the Hoox microservice monorepo. Because internal workers have zero public IP footprints and are completely isolated by Cloudflare’s Zero Trust service bindings, this map serves as the primary integration blueprint for routing, debugging, and dashboard interactions. --- ️ Interactive Compute & Routing Flow All external webhooks flow through the public hoox gateway, which authenticates payloads and routes them to private workers inside localized V engine isolates: --- ️ Endpoints Directory by Worker Every internal HTTP request between V isolates must transmit the standard bearer header: X-Internal-Auth-Key: --- . hoox (Gateway Router) Status: Public Ingress Node Bindings Mounts: TRADESERVICE, TELEGRAMSERVICE, ANALYTICSSERVICE, CONFIGKV, TRADEQUEUE | Route | Method | Description | Request Shape | Success Response | | :------------------ | :----: | :----------------------------------------------- | :------------------- | :------------------------------ | | /webhook | POST | Primary webhook receiver for TradingView alerts. | WebhookSignal JSON | OK (Orderfilled metadata) | | /health | GET | Probes gateway, D connectivity, and DO status. | N/A | {"status": "ok"} | | /telegram-webhook | POST | Processes chat commands pushed from Telegram. | Telegram Updates | OK | --- . trade-worker (Execution Engine) Status: Private Compute Node (No Public URL) Bindings Mounts: DSERVICE, TELEGRAMSERVICE, ANALYTICSSERVICE, CONFIGKV | Route | Method | Description | Request Shape | Success Response | | :------------- | :----: | :------------------------------------------------ | :------------------- | :-------------------------- | | /webhook | POST | Direct fast-path execution trigger. | WebhookSignal JSON | OK (Fill detail JSON) | | /dex | POST | Dispatches EVM orders on-chain via web wallet. | DexTrade JSON | OK (Tx Hash metadata) | | /api/signals | GET | Retrieves recent signal logs from D. | Query params filters | OK (Array of signals) | | /health | GET | Probes CPU thread state and exchange connections. | N/A | {"status": "ok"} | --- ️ . d-worker (SQLite Hub) Status: Private Data Proxy (No Public URL) Bindings Mounts: DB (D SQLite database binding) | Route | Method | Description | Request Shape | Success Response | | :--------------------- | :----: | :-------------------------------------------------------- | :------------------------------------------------ | :------------------------------------ | | /query | POST | Executes a single SQL query against the SQLite database. | {"query": "SELECT FROM trades", "params": []} | {"success": true, "results": [...]} | | /batch | POST | Executes multiple transactional SQL operations. | {"queries": [{"query": "...", "params": []}]} | {"success": true, "results": [...]} | | /api/dashboard/stats | GET | Computes aggregated Win Rate, drawdown, and daily totals. | N/A | {"success": true, "stats": {...}} | | /{tableName} | GET | Lists rows inside a specific SQLite table (with filters). | Query params | {"success": true, "rows": [...]} | --- . agent-worker (AI Risk Manager) Status: Private Compute Node (Runs primarily on Cron schedule / ) Bindings Mounts: TRADESERVICE, DSERVICE, TELEGRAMSERVICE, AI | Route | Method | Description | Request Shape | Success Response | | :-------------- | :----: | :--------------------------------------------------------- | :---------------------------------------- | :---------------------------------- | | /agent/chat | POST | Starts a conversational market/risk query (SSE supported). | {"prompt": "...", "stream": true} | text/event-stream stream | | /agent/vision | POST | Analyzes image bytes using multimodal AI models. | {"image": "base...", "prompt": "..."} | {"analysis": "..."} | | /agent/status | GET | Returns active trailing stops and current drawdowns. | N/A | {"status": "active", "stops": []} | | /health | GET | Probes AI model availability and Cron loop timers. | N/A | {"status": "ok"} | --- . telegram-worker (Push alerts) Status: Private Compute Node Bindings Mounts: ANALYTICSSERVICE, AI, VECTORIZEINDEX | Route | Method | Description | Request Shape | Success Response | | :-------- | :----: | :---------------------------------------------------- | :------------------------------------ | :------------------ | | /alert | POST | Sends a push trade fill notification or daily digest. | {"chatId": "...", "message": "..."} | {"success": true} | | /health | GET | Probes Telegram API connection. | N/A | {"status": "ok"} | --- Tip: Every internal-to-internal transaction automatically inherits the requestId trace UUID generated by the gateway. This trace ID is attached as the X-Request-Id header, allowing you to trace a single webhook alert across D database writes, R log outputs, and Telegram alerts instantly! Next Steps Astro Docs Site Config — Map out your build-time environment configurations. System Storage Architecture — Deep dive into R logs offloading and Drizzle ORM schemas. FILE: docs/devops/architecture/design-system.md Visual Tokens & Design System To maintain visual cohesion across the entire Hoox ecosystem (web landing pages, Astro documentation sites, Zustand Next.js dashboards, and terminal UIs), the platform implements a standardized, high-integrity design system. This document catalogs our color tokens, spacing densities, border-radius behaviors, and provides the complete SVG Icon Mapping Catalog used inside the documentation navigation chrome. --- . OKLCH Color Palette Hoox utilizes OKLCH color values to ensure perceptually uniform brightness and high contrast across all edge screens and operating systems: Dark Mode (Primary Visual Standard) Background (--background): oklch(. ) — Deep charcoal/black. Foreground (--foreground): oklch(. ) — Bright neutral Zinc/white. Card (--card): oklch(. ) — Slightly elevated dark panel grey. Accent (--accent): oklch(. . ) — High-contrast bright orange (used for focal actions and headers). Muted Foreground (--muted-foreground): oklch(. ) — Secondary readability text. Borders (--border): oklch(. ) — Low-contrast dark grey dividers. --- . Layout, Borders & Density Border Radius (--radius): Restored globally to .rem (px) to soften panel boundaries without losing the clean command-center aesthetic. Shadows: Cards and active modal prompts bind a highly contrasting deep shadow: shadow-xl -> box-shadow: px px -px rgba(, , , .); Spacing Density: Standardize grid gutters using Tailwind flex/grid spaces: Cards Grid: gap- (px) for dashboard cards. Sidebar Items: gap-. (px) vertical padding between nav links. --- . Typography & Runtimes | Aesthetic Layer | Font Family | CSS Utility | Ideal Operational Use Case | | :------------------- | :------------------------------------- | :------------- | :---------------------------------------------------- | | Primary Titles | "Bebas Neue", sans-serif | font-heading | Main high-signal card headers, page titles. | | Prose & Body | "IBM Plex Sans Variable", sans-serif | font-sans | Explanatory text, paragraphs, tables. | | Technical Chrome | "IBM Plex Mono", monospace | font-mono | Navigation links, settings inputs, SQL queries, code. | --- . SVG Icon Mapping Catalog To ensure visual consistency and completely eliminate platform-inconsistent emojis, the navigation chrome (Sidebar.astro and MobileNav.astro) maps dynamic section keys to clean, flat, inline SVGs: A. Rocket Icon (getting-started) Used to represent system setup and installation paths. ``html ` --- B. Book Icon (guides) Used to represent operational manuals and setup instructions. `html ` --- C. Lightbulb Icon (concepts) Used to represent structural theories and edge architectures. `html ` --- D. Book-Open Icon (reference) Used to represent dictionary definitions, configuration matrices, and API details. `html ` --- E. Target Icon (tutorials) Used to represent step-by-step walkthroughs and integration guides. `html ` --- F. Gear Icon (devops & workers) Used to represent background cron engines, system setups, and deployment configs. `html ` --- G. Home House Icon (home) Used to return to the parent portal. `html `` Next Steps System Topology Overview — Analyze edge isolates and data layers integrations. Isolate Communication Spec — Check service bindings and standard Bearer Auth middleware. FILE: docs/devops/workers/hoox.md hoox Gateway Isolate Profile The hoox gateway is the public-facing entry point of the trading ecosystem. Running as an ultra-low-latency Cloudflare Worker, the gateway is responsible for authorizing incoming trade signals (TradingView alerts, email routing, manual commands), executing rate-limiting checks, locking transaction trace IDs via Durable Objects to prevent duplicate fills, and routing validated events privately to background compute nodes. --- ️ Architectural Topology --- . Declared Wrangler Configurations & Bindings The gateway's wrangler.jsonc defines its private service binding links and resource bounds: ``jsonc { "name": "hoox", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "placement": { "mode": "smart", }, "vars": { "ENVIRONMENT": "production", }, "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, { "binding": "SESSIONSKV", "id": "ffabedaacc", }, ], "services": [ { "binding": "TRADESERVICE", "service": "trade-worker" }, { "binding": "TELEGRAMSERVICE", "service": "telegram-worker" }, { "binding": "ANALYTICSSERVICE", "service": "analytics-worker" }, ], "queues": { "producers": [{ "queue": "trade-execution", "binding": "TRADEQUEUE" }], }, "durableobjects": { "bindings": [ { "name": "IDEMPOTENCYSTORE", "classname": "IdempotencyStore" }, ], }, "migrations": [ { "tag": "v", "newsqliteclasses": ["IdempotencyStore"], }, ], } ` --- . Environmental Variables & Encrypted Secrets For security, build-time credentials are never stored in plain text. They are bound at deploy time as encrypted secrets: WEBHOOKAPIKEY: The custom authentication passkey expected inside incoming signal payloads. INTERNALKEYBINDING: The shared bearer authorization token used by requireInternalAuth middleware to invoke internal V isolates. Local Development Mocking (.dev.vars) When running tests or starting local Wrangler dev, create a gitignored .dev.vars file in the gateway directory: `bash WEBHOOKAPIKEY=devwebhookauthpasskey INTERNALKEYBINDING=devsharedinternalsecuritykey ` --- . API Route Specifications The gateway exposes three public entryways: A. Ingest Signal Webhook Endpoint: /webhook Method: POST JSON Payload: `json { "apiKey": "devwebhookauthpasskey", "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": , "idempotencyKey": "uuid-bdebd-bd" } ` Success Response ( OK): `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "exchange": "bybit", "symbol": "BTCUSDT", "action": "LONG", "result": { "orderId": "", "status": "Filled" } } ` --- B. Telegram Bot Update Webhook Endpoint: /telegram-webhook Method: POST JSON Payload: Standard encrypted update structure forwarded by Telegram's webhook servers. --- C. Gateway Health Diagnostics Endpoint: /health Method: GET Success Response ( OK): `json { "status": "ok", "timestamp": , "bindings": { "d": "connected", "kv": "connected", "queue": "active" } } ` --- Tip: If exchange APIs experience high latency or go offline, the gateway intercepts the timeout error, serializes the payload, and pushes it to the TRADE_QUEUE producer in less than milliseconds, returning a "status": "Enqueued"` ( Accepted) response to TradingView. Next Steps trade-worker Spec — Review how trade executions, order math, and margin settings compile on the edge. D Database Operations — Manage schema migrations, query ledgers, and execute SQL scripts. FILE: docs/devops/workers/trade-worker.md trade-worker Isolate Profile The trade-worker is the execution engine of the Hoox trading platform. Deployed as a private compute isolate behind the edge firewall, this worker is responsible for calculating order parameters, executing leverage scaling, performing cryptographic HMAC-SHA signature calculations, placing trades on Bybit, Binance, and MEXC, and offloading transactional metrics. --- . Declared Wrangler Configurations & Bindings The trade-worker does not expose a public URL, communicating internally via V Service Bindings. Its wrangler.jsonc maps out its critical storage, queue, and database hooks: ``jsonc { "name": "trade-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "placement": { "mode": "smart", }, "ddatabases": [ { "binding": "DB", "databasename": "trade-data-db", "databaseid": "caefffba", }, ], "rbuckets": [ { "binding": "REPORTSBUCKET", "bucketname": "trade-reports" }, { "binding": "SYSTEMLOGSBUCKET", "bucketname": "hoox-system-logs" }, ], "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "queues": { "consumers": [ { "queue": "trade-execution", "maxbatchsize": , "maxbatchtimeout": , }, ], }, "secrets": [ "INTERNALKEYBINDING", "BYBITAPIKEY", "BYBITAPISECRET", "BINANCEAPIKEY", "BINANCEAPISECRET", "MEXCAPIKEY", "MEXCSECRETBINDING", ], } ` --- . The Provider-Based ExchangeRouter Pattern To support multiple centralized exchanges with different API schemas while maintaining a clean code structure, trade-worker implements a Provider Composition Pattern: A. Generic Exchange Provider Interface The client abstraction is defined inside the shared monorepo package @jango-blockchained/hoox-shared/types: `typescript export interface IExchangeProvider { readonly name: string; createClient(env: TEnv): TClient; hasCredentials(env: TEnv): boolean; } ` B. Dynamic Runtime Routing The ExchangeRouter evaluates the incoming symbol and parses settings in CONFIGKV in sub-milliseconds: . Default Path: Routes trades to the default CEX declared in exchanges:defaultrouting (typically bybit). . Dynamic Symbol Redirects: Parses overrides in KV (e.g. exchanges:routing:SOLUSDT = binance). If present, the router bypasses Bybit and instantiates the BinanceProvider instantly without redeploying code. --- . Internal REST API Specification A. Process Order Pipeline Invoked by the hoox gateway or the TRADEQUEUE consumer batch runner. Endpoint: /process Method: POST Headers: X-Internal-Auth-Key: JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": } } ` Success Response ( OK): `json { "success": true, "result": { "orderId": "", "status": "Filled", "price": . }, "error": null } ` --- ️ . Standardized Exception Handling All execution rejects and validation failures are intercepted by the trade-worker error middleware and formatted using the shared Errors factory from @jango-blockchained/hoox-shared/errors: ``typescript import { Errors } from "@jango-blockchained/hoox-shared/errors"; // . Parameter Validation Failure if (quantity Tip: If the exchange API rejects an order due to account rate-limiting, the queue consumer automatically returns a retry flag. Cloudflare Queues will back off and re-route the batch at intervals starting at seconds, protecting your strategy from missed fills. Next Steps hoox Gateway Profile — Review WAF rules and Durable Object idempotency locks. D Database Operations — Manage Drizzle schemas, migrations, and query operations. FILE: docs/devops/workers/agent-worker.md Agent Worker - Hoox Autonomous AI & Risk Manager Last Updated: May (Post-Enhancement) The agent-worker serves as the proactive intelligence layer of the Hoox trading ecosystem. Rather than waiting for webhooks, it runs continuously on a cron schedule to monitor portfolio health, enforce risk limits, and optimize position exits. Core Capabilities | Feature | Description | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | ️ Cron-Driven Observation | Automatically runs every minutes (/ ) to fetch live market data from Binance, Bybit, and MEXC. | | ️ Global Kill Switch | Calculates total account PnL and instantly locks out the hoox gateway from new entries if the maxdailydrawdownpercent is breached. | | Dynamic Trailing Stops | Stores watermark prices in CONFIGKV and automatically triggers CLOSE payloads if the market reverses. | | Scale-Out Take Profits | Detects when a position reaches a specific profit target and automatically sends partial close commands to secure gains. | | AI System Summarization | Periodically fetches systemlogs from the d-worker, analyzes them via LLAMA B, and sends natural language health reports to Telegram. | | Multi-Provider AI | Seamlessly switches between Workers AI, OpenAI, Anthropic, Google AI, and Azure OpenAI with automatic fallbacks. | | Advanced Models | Supports vision, embeddings, reasoning (extended thinking), and code generation models. | Architecture & Flow . Trigger: Cloudflare Cron triggers the worker. . State Sync: Fetches active OPEN positions via the d-worker. . Market Pulse: Pings public exchange APIs for the latest markPrice. . Risk Evaluation: Cross-references current price with KV-stored watermarks and global drawdown limits. . AI Processing: Uses configured AI provider with automatic fallback chain. . Execution: Dispatches actions to trade-worker (closing positions) and telegram-worker (alerts) via internal Service Bindings. Endpoints & Interactions Management Endpoints GET /agent/config Returns current agent configuration including provider settings. ``json { "success": true, "config": { "defaultProvider": "workers-ai", "fallbackChain": ["workers-ai", "openai"], "modelMap": { ... }, "trailingStopPercent": ., "takeProfitPercent": . } } ` POST /agent/config Update agent configuration at runtime. `json { "defaultProvider": "openai", "fallbackChain": ["openai", "workers-ai", "anthropic", "google", "azure"], "modelMap": { "workers-ai": "@cf/meta/llama-.-b-instruct", "openai": "gpt-o-mini---", "anthropic": "claude--haiku-", "google": "gemini-.-flash-", "azure": "gpt-o-mini" }, "timeoutMs": , "retryCount": } ` GET /agent/models Returns all available models from Cloudflare Workers AI and external providers. POST /agent/test-model Test a specific AI model. `json { "prompt": "Say hello", "model": "@cf/meta/llama-.-b-instruct", "provider": "workers-ai" } ` GET /agent/health Returns health status of all configured AI providers. `json { "success": true, "providers": { "workers-ai": { "healthy": true, "latency": }, "openai": { "healthy": true, "latency": } } } ` AI Interaction Endpoints POST /agent/chat Send a chat request with automatic provider fallback and SSE streaming support. Request: `json { "messages": [{ "role": "user", "content": "Analyze BTC market sentiment" }], "systemPrompt": "You are a professional crypto trading analyst.", "temperature": ., "maxTokens": , "stream": true } ` Streaming Response (SSE): ` data: {"content": "Based on current market conditions..."} data: {"content": " technical indicators suggest..."} data: [DONE] ` POST /agent/vision (NEW!) Analyze images with AI vision models. Supports both URL and base input. `json { "imageUrl": "https://example.com/chart.png", "prompt": "Analyze this price chart and identify key support/resistance levels", "model": "@cf/meta/llama-.-b-vision-instruct" } ` Or with base: `json { "imageBase": "iVBORwKGgoAAAANSUhEUgAA...", "prompt": "What pattern do you see in this chart?" } ` POST /agent/reasoning (NEW!) Extended thinking queries with reasoning models like OpenAI o. `json { "prompt": "Design a risk management strategy for a $k portfolio", "model": "o-preview", "reasoningEffort": "medium" } ` Response: `json { "reasoning": "Let me think through this step by step...", "answer": "Here's a comprehensive risk management strategy...", "model": "o-preview" } ` GET /agent/usage (NEW!) Get AI API usage statistics across all providers. `json { "success": true, "usage": { "workers-ai": { "requests": , "tokens": }, "openai": { "requests": , "tokens": } } } ` GET /agent/prompts (NEW!) List available prompt templates. `json { "success": true, "prompts": ["trading-analyst", "risk-assessor", "market-scanner"] } ` POST /agent/embedding Generate text embeddings using Workers AI embedding models. `json { "text": "Bitcoin price analysis for position sizing", "provider": "workers-ai" } ` Legacy Endpoints POST /agent/risk-override Manually enforce or release risk locks. `json { "action": "engagekillswitch", "reason": "Manual override from dashboard" } ` GET /agent/status Retrieve the real-time health of the agent and active trailing stops. Configuration KV Keys All configuration is stored in CONFIGKV for real-time adjustments. | KV Key | Default | Description | | -------------------------------------------- | ----------- | --------------------------------------- | | agent:config | JSON object | Main provider configuration | | agent:openaikey | - | OpenAI API key | | agent:anthropickey | - | Anthropic API key | | agent:googlekey | - | Google AI API key | | agent:azureapikey | - | Azure OpenAI API key | | agent:azureendpoint | - | Azure OpenAI endpoint URL | | trade:maxdailydrawdownpercent | - | Account PnL % that triggers Kill Switch | | trade:killswitch | false | When true, halts all new trades | | trade:watermark:{exchange}:{symbol}:{side} | N/A | High/low watermark | Default Agent Config `json { "defaultProvider": "workers-ai", "fallbackChain": ["workers-ai", "openai", "anthropic", "google", "azure"], "modelMap": { "workers-ai": "@cf/meta/llama-.-b-instruct", "openai": "gpt-o-mini---", "anthropic": "claude--haiku-", "google": "gemini-.-flash-", "azure": "gpt-o-mini" }, "timeoutMs": , "retryCount": , "maxDailyDrawdownPercent": -, "trailingStopPercent": ., "takeProfitPercent": . } ` Supported Models Workers AI Models | Task | Workers AI Model | | ------------- | ---------------------------------------------- | | Chat | @cf/meta/llama-.-b-instruct | | Vision | @cf/meta/llama-.-b-vision-instruct | | Reasoning | @cf/deepseek-ai/deepseek-r-distill-qwen-b | | Code | @cf/qwen/qwen.-coder-b-instruct | | Embeddings | @cf/baai/bge-base-en-v. | | Summarization | @cf/facebook/bart-large-cnn | External Providers | Provider | Models | | --------- | --------------------------------------- | | OpenAI | GPT-o, GPT-o-mini, GPT- Turbo, o | | Anthropic | Claude Haiku, Sonnet, Opus | | Google | Gemini . Flash, Gemini . Pro | | Azure | GPT-o, GPT-o-mini (custom deployment) | AI Gateway Features The AI Gateway provides: Fallback Chain: Automatically tries providers in order on failure Health Checks: Providers self-report health status every minutes Retry Logic: Exponential backoff with configurable max retries Timeout Protection: Configurable per-request timeout (default s) Usage Tracking: Automatic token and request counting per provider Internal Service Bindings The agent-worker requires the following bindings to operate: DSERVICE: To fetch open positions and system logs. TRADESERVICE: To execute trailing stops and profit-taking. TELEGRAMSERVICE: To broadcast AI summaries and emergency alerts. CONFIGKV: For dynamic configuration and state. AI: Workers AI binding for inference. Testing The agent-worker includes comprehensive tests ( tests across files): `bash Run all tests bun test Run specific test file bun test tests/ai/providers/openai.test.ts Run with coverage bun test --coverage ` Test Coverage: >% across all modules Test Structure ` tests/ ├── ai/ │ ├── providers/ Tests for each AI provider │ ├── gateway.test.ts AI Gateway fallback tests │ ├── streaming.test.ts SSE streaming tests │ └── prompts.test.ts Prompt template tests ├── handlers/ Tests for all endpoints ├── middleware/ Tests for auth, validation, logging ├── market/ Tests for exchange clients ├── risk/ Tests for risk manager/executor ├── routine/ Tests for housekeeping └── integration/ End-to-end integration tests `` --- Cloudflare and the Cloudflare logo are trademarks and/or registered trademarks of Cloudflare, Inc. in the United States and other jurisdictions. FILE: docs/devops/workers/telegram-worker.md telegram-worker Isolate Profile The telegram-worker serves as the dynamic communicator of the Hoox trading ecosystem. Running as an isolated edge microservice, it parses incoming chat commands forwarded from Telegram's webhooks, executes retrieval-augmented generation (RAG) queries via Vectorize, analyzes screenshots using AI vision models, and dispatches real-time HTML/Markdown formatting order alerts to your mobile. --- . Declared Wrangler Configurations & Bindings The telegram-worker mounts multiple storage and vector search services to implement AI-powered chatbot features. Its wrangler.jsonc specifies: ``jsonc { "name": "telegram-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "placement": { "mode": "smart", }, "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "rbuckets": [ { "binding": "UPLOADSBUCKET", "bucketname": "user-uploads", }, ], "vectorize": [ { "binding": "VECTORIZEINDEX", "indexname": "rag-index", }, ], "ai": { "binding": "AI", }, "secrets": [ "INTERNALKEYBINDING", "TGBOTTOKENBINDING", "TELEGRAMCHATIDDEFAULT", "TELEGRAMWEBHOOKSECRET", ], } ` --- . Environmental Variables & Encrypted Secrets TGBOTTOKENBINDING: Private HTTP bot token generated by @BotFather. TELEGRAMCHATIDDEFAULT: Your authorized Chat ID acting as a fallback receiver and admin lock. TELEGRAMWEBHOOKSECRET: A secure, random token appended to the webhook URL path to validate that the request originated from Telegram’s servers. INTERNALKEYBINDING: Shared key used to validate calls from hoox or trade-worker. Local Development Mocking (.dev.vars) `bash TGBOTTOKENBINDING=mocktelegrambottoken TELEGRAMCHATIDDEFAULT= TELEGRAMWEBHOOKSECRET=localsecureroutetoken INTERNALKEYBINDING=devsharedinternalsecuritykey ` --- . Internal REST API Specification A. Dispatch Notification Endpoint Endpoint: /alert Method: POST Headers: X-Internal-Auth-Key: JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "chatId": "", "message": " Bybit LONG Filled!\nSymbol: BTCUSDT\nPrice: $,.\nQuantity: .", "parseMode": "HTML" } } ` Success Response ( OK): `json { "success": true, "result": { "messageId": }, "error": null } ` --- B. Telegram Ingress Webhook Route Receives chat commands, /start signals, and image binaries. Endpoint: /telegram/ Method: POST JSON Payload: Standard Telegram update JSON schema. Access Control: The worker extracts the incoming message.chat.id. If it does not match your authorized TELEGRAMCHATIDDEFAULT secret, the payload is silently dropped with a OK return to Telegram to prevent malicious commands. --- . AI-Powered Chatbot & RAG Mechanics The bot does not just return static responses. When you send a natural language question (e.g., "What is my average entry price on SOL?"): . Embedding Generation: The worker calls env.AI to generate high-dimensional text embeddings for your prompt using the @cf/baai/bge-base-en-v. model. . Vector Query: Passes the vector to env.VECTORIZE_INDEX to retrieve semantically related transaction rows and market summaries from past trades. . Context Construction: Formats the matched history into a rich LLM context window. . LLM Inference: Invokes LLaMA- instruct via env.AI using your multi-provider API keys to generate a highly informed financial summary. --- Tip: Secure your bot webhook instantly after deployment: hoox deploy telegram-webhook`. The CLI automatically queries your secrets, makes the HTTP setup call to Telegram's servers, and validates the TLS tunnel! Next Steps hoox Gateway Profile — Review how incoming commands route to the gateway. Setting Up Telegram Bot Alerts — Step-by-step tutorial for BotFather configuration. FILE: docs/devops/workers/d1-worker.md ️ d-worker Isolate Profile The d-worker is the data routing hub of the Hoox trading platform. Deployed as an isolated, private micro-worker, it acts as a centralized SQL execution proxy. By encapsulating database interactions behind secure Service Bindings, it allows other lightweight compute workers to execute parameterized queries, trigger transactional batch operations, and retrieve structured dashboard telemetry without direct database driver overhead. --- . Declared Wrangler Configurations & Bindings The d-worker binds directly to the production SQLite database (trade-data-db) and does not expose any public endpoints: ``jsonc { "name": "d-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "placement": { "mode": "smart", }, "ddatabases": [ { "binding": "DB", "databasename": "trade-data-db", "databaseid": "caefffba", }, ], "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "secrets": ["INTERNALKEYBINDING"], } ` --- . Internal REST API Specification Every endpoint is secured via requireInternalAuth and expects the X-Internal-Auth-Key header. A. Execute Single SQL Query Endpoint: /query Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "query": "SELECT createdat, symbol, action, price FROM trades WHERE symbol = ? ORDER BY createdat DESC LIMIT ?", "params": ["BTCUSDT", ] } ` Success Response ( OK): `json { "success": true, "results": [ { "createdat": , "symbol": "BTCUSDT", "action": "LONG", "price": . } ], "meta": { "rowsread": , "rowswritten": , "duration": . } } ` --- B. Execute Transactional Batch Operations Allows running multiple statements atomically in a single network trip, reducing latency. Endpoint: /batch Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "queries": [ { "query": "INSERT INTO trades (id, symbol, price) VALUES (?, ?, ?)", "params": ["trade-", "BTCUSDT", ] }, { "query": "UPDATE positions SET size = size + ? WHERE symbol = ?", "params": [., "BTCUSDT"] } ] } ` Success Response ( OK): `json { "success": true, "results": [{ "meta": { "changes": } }, { "meta": { "changes": } }] } ` --- C. Dashboard Telemetry Statistics Calculates aggregated win ratios, active positions size, and time-series P&L. Endpoint: /api/dashboard/stats Method: GET Success Response ( OK): `json { "success": true, "stats": { "totalTrades": , "winRate": ., "totalPnlUSDT": ., "activePositionsCount": , "dailyTradesCount": } } ` --- ️ . Security & SQL Injection Protection To protect financial transaction ledgers and portfolios against SQL injection attacks, d-worker enforces strict development rules: Parameterized Bindings: All inputs must utilize parameterized placeholders (? or ?) mapped to env.DB.prepare().bind(). Never concatenate raw request strings directly into SQL statements. Access Isolation: The database does not exist publicly. By binding D solely to this worker and accessing it via V Service Bindings, you prevent external crawlers or bots from querying database nodes directly. --- Tip: If you are extending schemas or adding tables, generate migration scripts locally using Drizzle: hoox db migrate --remote`. This keeps edge schema histories atomic and securely tracked. Next Steps System Storage Architecture — Review SQLite properties and R bucketing pipelines. Database Operations Manual — Learn commands to run query ledgers and restore backups. FILE: docs/devops/workers/web3-wallet-worker.md web-wallet-worker Isolate Profile The web-wallet-worker is the on-chain gateway of the Hoox trading ecosystem. Running as an isolated private micro-worker, this service is responsible for securely managing EVM mnemonics and private keys (bound as encrypted Workers Secrets), querying multi-chain gas limits and token balances, executing native/ERC- transfers, and signing smart contract swap payloads (e.g. Uniswap/inch routers) via JSON-RPC providers. --- . Declared Wrangler Configurations & Bindings The web-wallet-worker does not expose a public URL, communicating internally via V Service Bindings. Its wrangler.jsonc specifies: ``jsonc { "name": "web-wallet-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "vars": { "DEFAULTCHAIN": "ethereum", }, "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "secrets": [ "INTERNALKEYBINDING", "WALLETMNEMONICSECRET", "WALLETPKSECRET", "RPCPROVIDERURL", ], } ` --- . Environmental Variables & Encrypted Secrets WALLETPKSECRET: Encrypted private key used for single-account execution. WALLETMNEMONICSECRET: Encrypted or -word HD wallet seed phrase used to derive multiple accounts. RPCPROVIDERURL: High-availability HTTP Ethereum / EVM RPC provider (e.g., Infura, Alchemy, or QuickNode). INTERNALKEYBINDING: Shared key used to validate calls from internal compute nodes. Local Development Mocking (.dev.vars) `bash WALLETPKSECRET=xabcdefabcdefabcdefabcdef WALLETMNEMONICSECRET="abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" RPCPROVIDERURL=http://localhost: INTERNALKEYBINDING=devsharedinternalsecuritykey ` --- . Internal REST API Specification A. Execute On-Chain Transaction Endpoint: /process Method: POST Headers: X-Internal-Auth-Key: JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "action": "sendTransaction", "chain": "arbitrum", "to": "xbecdabeedeacdf", "value": ".", "data": "xacbb...", "gasLimit": } } ` Success Response ( OK): `json { "success": true, "result": { "txHash": "xaebfddacbcfddacbcfddacbcfdab", "nonce": , "gasUsed": , "effectiveGasPrice": "" }, "error": null } ` --- B. Query Token Balance Endpoint: /process Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "action": "getBalance", "chain": "polygon", "address": "xbecdabeedeacdf", "tokenAddress": "xcddcaccaebbef" } } ` Success Response ( OK): `json { "success": true, "result": { "balance": ".", "symbol": "USDT", "decimals": }, "error": null } ` --- ️ . On-Chain Security Best Practices Operating hot wallets on public blockchain networks introduces extreme security vectors: Harden Private Keys: Never write keys to wrangler config files or print them in telemetry logs. Always provision keys via encrypted Cloudflare Secrets. Gas Price Limit Traps: To prevent severe loss during network congestion or flash crashes, the worker enforces a gas limit trap—if current network gas price exceeds your KV configured limit (web:maxgaspricegwei), transactions are dropped before signing to prevent massive fee consumption. Isolate Access: All calls must originate internally via Service Bindings. The wallet worker does not bind to public ports, meaning external scrapers cannot send raw transaction payloads or try to brute-force auth codes. --- Tip: Testing on-chain logic locally? Use the Docker runtime stack (hoox dev start --runtime docker`) to launch an isolated Hardhat/Anvil node container and test private wallet swaps on a simulated local EVM fork safely! Next Steps trade-worker Profile — Review how execution orders route transactions to EVM wallet nodes. D Database Operations — Manage your SQLite schemas and sync positions logs. FILE: docs/devops/workers/email-worker.md email-worker Isolate Profile The email-worker is an ancillary signal ingestion plugin. Deployed as a private compute isolate, this service is responsible for intercepting trading signals distributed via email lists, newsletters, or alert emails (e.g. from TradingView or custom notification pipelines). It validates domain security (SPF/DKIM), parses message subjects and bodies using dynamic Regular Expressions, and routes the extracted signals privately to trade-worker via V Service Bindings. --- . Declared Wrangler Configurations & Bindings The email-worker does not expose any public endpoints, connecting internally to active executors and metrics collectors: ``jsonc { "name": "email-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "vars": { "USEIMAP": "true", }, "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "services": [ { "binding": "TRADESERVICE", "service": "trade-worker" }, { "binding": "ANALYTICSSERVICE", "service": "analytics-worker" }, ], "secrets": [ "INTERNALKEYBINDING", "EMAILHOSTBINDING", "EMAILUSERBINDING", "EMAILPASSBINDING", "MAILGUNAPIKEY", ], } ` --- . Environmental Variables & Encrypted Secrets EMAILHOSTBINDING: POP/IMAP mailbox server address (e.g., imap.gmail.com). EMAILUSERBINDING: Dedicated signals email mailbox username. EMAILPASSBINDING: Secure app-specific password. MAILGUNAPIKEY: Key used to validate incoming SMTP webhooks if using Mailgun routing. INTERNALKEYBINDING: Shared key used to validate calls from internal compute nodes. --- ️ . Regex Parsing Mechanics in V When a new email is scanned or received via webhook, the worker evaluates the content against regular expression arrays stored in CONFIGKV: | Configuration Key | Type | Default Pattern | Parser Purpose | | :-------------------------- | :------: | :------------------------- | :----------------------------------------------------------- | | email:scansubject | string | ^TRADE SIGNAL:. | Resolves whether the email should be parsed or ignored. | | email:coinpattern | string | (BTC\|ETH\|SOL\|LINK) | Matches uppercase asset tokens in the email body. | | email:actionpattern | string | (BUY\|SELL\|LONG\|SHORT) | Resolves buy/sell execution parameters. | | email:quantitymultiplier | number | . | Coefficient applied to parsed quantities to scale positions. | `typescript // Under the hood regex parsing logic const subjectRegex = new RegExp(env.CONFIGKV.get("email:scansubject")); const coinRegex = new RegExp(env.CONFIGKV.get("email:coinpattern")); const actionRegex = new RegExp(env.CONFIGKV.get("email:actionpattern")); if (subjectRegex.test(email.subject)) { const asset = email.body.match(coinRegex)?.[]; // Extracts "BTC" const action = email.body.match(actionRegex)?.[]; // Extracts "LONG" // Routes to trade-worker... } ` --- . API Interface Specification While the worker primarily runs background Cron scan loops, it exposes two ingestion endpoints for webhook integrations (e.g. Mailgun/SendGrid): A. Mailgun Webhook Router Endpoint: /webhook/mailgun Method: POST Headers: Mailgun-Signature, Mailgun-Timestamp, Mailgun-Token Security: The worker computes the HMAC-SHA signature of the timestamp and token using your MAILGUNAPIKEY secret. If the calculated signature doesn't match the header, the request is instantly rejected ( Unauthorized). --- B. Direct JSON Payload Ingestion Used primarily by administrative automation tools or local testing scripts. Endpoint: /process Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "sender": "alerts@tradingview.com", "subject": "TRADE SIGNAL: Breakout SOL", "body": "Action: LONG, Asset: SOLUSDT, Size: ." } } ` Success Response ( OK): `json { "success": true, "result": { "symbol": "SOLUSDT", "action": "LONG", "quantity": . }, "error": null } `` --- ️ . Domain Ingress Protections: SPF & DKIM To protect your wallet against email spoofing attacks: . DKIM Check: Validates the cryptographic DKIM signature in the email header to prove the message body was not altered in transit. . SPF Check: Matches the sending server's IP address against the DNS TXT SPF record of the authorized domain, dropping forged emails before parsing. Next Steps trade-worker Profile — Review how execution orders route transactions to EVM wallet nodes. System Storage Architecture — Review SQLite properties and R bucketing pipelines. FILE: docs/devops/workers/analytics-worker.md analytics-worker Isolate Profile The analytics-worker is the observability engine of the Hoox trading platform. Deployed as a private internal microservice, it aggregates time-series metrics, database query latencies, execution performance ratios, and API status codes across all V isolates. By translating incoming events and writing them to Cloudflare Analytics Engine, it provides the backend telemetry used to draw live charts in the Next.js Dashboard. --- . Declared Wrangler Configurations & Bindings The analytics-worker binds directly to Cloudflare’s Analytics Engine dataset and does not expose any public endpoints: ``jsonc { "name": "analytics-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "analyticsenginedatasets": [ { "binding": "ANALYTICSENGINE", "dataset": "hooxtelemetry", }, ], "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "secrets": [ "INTERNALKEYBINDING", "CLOUDFLAREAPITOKEN", // Required to run SQL queries against Analytics datasets ], } ` --- . Environmental Variables & Encrypted Secrets CLOUDFLAREAPITOKEN: A secure token with Account.Analytics read permissions, allowing the worker to query stored datasets. INTERNALKEYBINDING: Shared key used to validate calls from other V isolates. --- . Internal REST API Specification Every endpoint is secured via requireInternalAuth and expects the X-Internal-Auth-Key header. A. Track Telemetry Event Invoked by other workers (like hoox or trade-worker) immediately upon completing an action. Endpoint: /track/api-call Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "worker": "trade-worker", "endpoint": "/webhook", "latencyMs": ., "success": true } } ` Under-the-Hood Analytics Engine Write When received, the worker formats and writes a time-series data point using standard Blobs (metadata strings) and Doubles (numeric values): `typescript env.ANALYTICSENGINE.writeDataPoint({ blobs: [ payload.worker, // Blob : Worker Name payload.endpoint, // Blob : Endpoint Path payload.success ? "" : "", // Blob : Success state ], doubles: [ payload.latencyMs, // Double : Latency in milliseconds ], indexes: [ payload.requestId, // Custom index for distributed tracing ], }); ` Response ( OK): `json { "success": true } ` --- B. Query Metrics (SQL interface) Used primarily by the Next.js Dashboard to extract data points for chart rendering. Endpoint: /query Method: POST JSON Payload: `json { "query": "SELECT sum(double) as totallatency, count() as totalcalls FROM hooxtelemetry WHERE blob = ? AND timestamp >= now() - INTERVAL '' DAY", "params": ["trade-worker"] } ` Success Response ( OK): `json { "success": true, "results": [{ "totallatency": ., "totalcalls": }] } ` --- . Dashboard Visual Integrations The metrics written to hoox_telemetry are queried by the dashboard to render: . System Health Indicators: Real-time error spikes trigger warning banners in under seconds. . Isolate Latency Charts: Visual line graphs showing V processing speeds vs exchange API transit speeds. . Volume Load Heatmaps: Visualizes peak trading hours and signal traffic volumes globally. --- Tip: Testing analytics locally? Local Wrangler dev automatically intercepts writeDataPoint` calls and logs the parsed Blobs and Doubles straight to your terminal standard output, ensuring easy debugging! Next Steps System Observability Guides — Deepen your understanding of time-series logging and metrics. trade-worker Profile — Review how execution latency details are generated and offloaded. FILE: docs/devops/workers/report-worker.md report-worker Isolate Profile The report-worker is the automated document compiler of the Hoox trading platform. Deployed as a scheduled cron isolate, this worker runs twice daily (at : and : UTC) to pull D transactional stats, construct a highly styled HTML portfolio report, spin up a serverless Cloudflare Browser Rendering Chrome instance to compile the page into a PDF buffer, offload the file to R, and push a private download link to your Telegram. --- . Declared Wrangler Configurations & Bindings The report-worker mounts storage buckets, notification bindings, and is triggered by Cloudflare's background cron engine: ``jsonc { "name": "report-worker", "main": "src/index.ts", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "placement": { "mode": "smart", }, "triggers": { "crons": [" ", " "], // Runs twice daily }, "rbuckets": [ { "binding": "REPORTSBUCKET", "bucketname": "trade-reports", }, ], "services": [ { "binding": "DSERVICE", "service": "d-worker" }, { "binding": "TELEGRAMSERVICE", "service": "telegram-worker" }, ], "secrets": [ "INTERNALKEYBINDING", "CFAPITOKEN", // Required to call Browser Rendering REST API ], } ` --- . Environmental Variables & Encrypted Secrets CFAPITOKEN: Your Cloudflare API Token with Account.Browser Rendering and Account.R write permissions. INTERNALKEYBINDING: Shared key used to validate calls from other V isolates. --- . Browser Rendering & PDF Print Pipeline When the Cron schedule triggers, report-worker runs the following programmatic pipeline: Step : Data Aggregation & HTML Compilation The worker pings DSERVICE to retrieve P&L, win rate, and total daily fees, inserting the metrics into a styled HTML template utilizing Tailwind CSS and CSS Grid styling: `html Daily P&L +$,. ` --- Step : Cloudflare Chrome Isolate Print Pushes the HTML template to Cloudflare's headless Chrome rendering pool via the REST API: `typescript const response = await fetch( https://api.cloudflare.com/client/v/accounts/${env.ACCOUNTID}/browser-rendering/pdf, { method: "POST", headers: { Authorization: Bearer ${env.CFAPITOKEN}, "Content-Type": "application/json", }, body: JSON.stringify({ html: htmlContent, options: { format: "A", printBackground: true, margin: { top: "cm", bottom: "cm", left: "cm", right: "cm" }, }, }), } ); ` --- Step : R Storage & Expiration . The API compiles the page and returns a raw PDF binary stream. . The worker uploads the stream to the REPORTSBUCKET R storage bucket using a unique, date-hashed key: reports/daily-pnl---.pdf . A lifecycle rule on the R bucket automatically purges reports older than days to maintain storage cleanliness. --- Step : Dispatch Telegram Alert Calls TELEGRAMSERVICE to send the link: `typescript await env.TELEGRAMSERVICE.fetch("https://telegram-worker/alert", { method: "POST", headers: { "X-Internal-Auth-Key": env.INTERNALKEYBINDING }, body: JSON.stringify({ chatId: env.TELEGRAMCHATIDDEFAULT, message: " Daily P&L PDF Report Compiled!\nDownload link: Download PDF", }), }); ` --- Tip: If CFAPI_TOKEN` is not configured, the worker gracefully fails by compiling a rich text-only P&L summary and pushing it directly via Telegram instead of generating a PDF, guaranteeing continuous operations without hard crashes. Next Steps telegram-worker Profile — Review push alert configurations and webhook tunnels. D Database Operations — Manage Drizzle schemas and execute custom queries. FILE: docs/devops/workers/dashboard.md ️ Next.js Dashboard & OpenNext Isolate The Hoox Dashboard is the web-based command center of the trading platform. Rather than running on a traditional server, the dashboard is a Next.js application compiled using the OpenNext adapter and hosted natively on Cloudflare Workers. This edge-first layout allows for real-time portfolio monitoring, dynamic form-based settings editing, and interactive kill-switch controls at microsecond speeds. --- ️ Next.js to Cloudflare Edge Architecture When deploying the dashboard, the monorepo uses @opennextjs/cloudflare to convert standard Node.js server-side features into Edge-compliant JavaScript: Server Isolate (.open-next/worker.js): Handles Server-Side Rendering (SSR), React Server Components (RSC) hydration, API routes, and cookies encryption. Static Assets (.open-next/assets/): Houses all static assets, which are bound to the worker via ASSETS bindings to serve static pages at sub-millisecond CDN latency. --- . Declared Wrangler Configurations & Bindings The dashboard's wrangler.jsonc maps out its internal service links to extract D databases metrics and agent status updates: ``jsonc { "name": "hoox-dashboard", "main": ".open-next/worker.js", "compatibilitydate": "--", "compatibilityflags": ["nodejscompat"], "accountid": "debcebeabecbcdec", "assets": { "directory": ".open-next/assets", "binding": "ASSETS", }, "kvnamespaces": [ { "binding": "CONFIGKV", "id": "caefffbd", }, ], "services": [ { "binding": "DSERVICE", "service": "d-worker" }, { "binding": "AGENTSERVICE", "service": "agent-worker" }, { "binding": "TELEGRAMSERVICE", "service": "telegram-worker" }, ], "vars": { "DSERVICEURL": "https://d-worker.cryptolinx.workers.dev", "AGENTSERVICEURL": "https://agent-worker.cryptolinx.workers.dev", "TELEGRAMSERVICEURL": "https://telegram-worker.cryptolinx.workers.dev", }, "secrets": [ "DASHBOARDUSER", "DASHBOARDPASS", "SESSIONSECRET", "INTERNALKEYBINDING", ], } ` --- . Environmental Variables & Encrypted Secrets DASHBOARDUSER & DASHBOARDPASS: Administrative credentials required to access the visual panel. SESSIONSECRET: A secure -character encryption key used to cryptographically sign session cookies at the edge. INTERNALKEYBINDING: Shared key used to validate calls to the d-worker and agent-worker service bindings. Local Development Mocking (.env.local) Create a gitignored .env.local file inside workers/dashboard/ for local Next.js runs: `bash DASHBOARDUSER=admin DASHBOARDPASS=admindevpasskey SESSIONSECRET=abandonabandonabandonabandon ` --- ️ . Schema-Driven Settings System To allow operators to extend the platform's settings without touching React code, the dashboard implements a schema-driven configuration manager parsed dynamically from config.schema.json: `json { "sections": [ { "id": "risk", "title": "Risk Management", "fields": [ { "key": "trade:maxdailydrawdownpercent", "label": "Max Daily Drawdown (%)", "type": "number", "default": , "category": "risk" } ] } ] } ` Form Submission Flow . When you save the settings form, the Next.js server actions intercept the payload. . The server action iterates over the JSON schema keys and writes the values directly to the bound CONFIG_KV namespace. . The changes propagate globally to your edge executors in under seconds. --- . Production Build & Rollout Runbook To compile and deploy the Next.js dashboard to Cloudflare: `bash . Navigate to the dashboard directory cd workers/dashboard . Build the application using OpenNext bun run opennext:build . Deploy the compiled bundles to Cloudflare Workers bun run opennext:deploy ` Warning: Framer Motion components and interactive visual elements used in Next.js pages must declare the 'use client' directive at the top of the file. Under OpenNext, client-side pages cannot export metadata directly—move metadata definitions to separate metadata.ts` files! Next Steps agent-worker Profile — Review AI chat streaming and risk evaluation structures. d-worker Profile — Check REST schemas that feed database metrics to the dashboard. FILE: docs/devops/deployment/production.md Production Deployment Runbook Deploying the Hoox trading ecosystem to production requires absolute operational rigor. Because the platform executes real-world trades using private capital, every V isolate, environment binding, and routing domain must be locked down, optimized for speed, and insulated against external failures. This runbook guides you through production prerequisites, manual and automated deployment commands, custom domain routing, and edge hardening strategies. --- . Production Rollout Pre-Flight Checklist Before rolling out updates to Cloudflare’s live edge networks: API Token Scoping: Confirm your active Cloudflare API Token inherits the strict minimal permission sets (Account.D: Edit, Account.KV: Edit, Account.Queues: Edit, Account.Workers: Edit, and Zone.DNS: Edit if mapping custom routing paths). Workspace Diagnostic Sweep: Run the automated pre-flight check to verify that all git submodules, local dependencies, and TypeScript variables compile without warnings: ``bash hoox check prerequisites hoox test ` Exchange Credentials Check: Ensure you have created dedicated exchange API keys with Withdrawal permissions turned OFF (disabled) to enforce least-privilege security. --- . Production Rollout Invocations The Hoox CLI automates the entire deployment sequence, compiling the shared libraries, deploying database schemas, synchronizing configuration manifests, and uploading workers in the correct dependency sequence: `bash . Execute full sequenced deployment hoox deploy all --auto . Deploy a single specific worker (e.g. after a trade execution update) hoox deploy worker trade-worker ` Dashboard OpenNext Compilation `bash Build and deploy the Next.js Dashboard via OpenNext hoox deploy dashboard ` This command runs Turbopack, bundles server-side assets into .open-next/worker.js, maps static files to the ASSETS CDN binding, and uploads the dashboard to Cloudflare. --- . Custom Domain & Routing Mapping By default, deployed workers are assigned subdomains under Cloudflare's shared domain (e.g., https://hoox.alpha-trading.workers.dev). For production, it is highly recommended to map your public gateway and dashboard to a custom domain under your own Cloudflare zone. This reduces DNS lookup latencies and enables custom SSL and WAF configurations. To map custom routes, add the routes array inside your worker's wrangler.jsonc file: `jsonc // In workers/hoox/wrangler.jsonc { "routes": [ { "pattern": "api.my-trading-empire.com/webhook", "custom_domain": true, }, ], } ` Deploying this configuration automatically updates your Cloudflare DNS zone records, maps the domain to your V isolate, and registers a universal SSL certificate near-instantaneously. --- ️ . Edge Isolate Hardening Strategies To protect your live production deployments from attacks and latency spikes: A. Enable Smart Placement Verify that every execution worker contains the smart placement var inside its wrangler.jsonc. This shifts the CPU isolate geographically close to exchange servers (e.g. Frankfurt for Bybit, Tokyo for Binance): `json "placement": { "mode": "smart" } ` B. Restrict CORS Origin Policies The public /webhook route inside the hoox gateway must only accept POST requests from authorized endpoints. Disable all CORS headers to prevent cross-origin script injections from browsers. C. Deploy WAF Rate Limit Traps Use the Hoox CLI to provisionZone-level rate limiters on Cloudflare’s global edge network, dropping packet floods before they load the V isolates: `bash Provision a strict rate-limit rule (e.g., max requests/minute to /webhook) hoox waf configure --limit-requests ` --- Tip: Made an emergency change? You don't need a full rebuild. If the change was a configuration setting or a trade symbol routing change, simply update the KV store: hoox config kv set `. The update will propagate globally in under seconds! Next Steps CI/CD Pipelines Reference — Automate edge deployments using GitHub Actions. Observability & Time-Series Monitoring — Stream console logs and check analytics datasets. FILE: docs/devops/deployment/cicd.md CI/CD Pipeline Automation Automating your deployment pipeline ensures that every commit pushed to your repository is systematically vetted for code style, type safety, syntax regressions, and unit test coverage before being deployed to your live production trading nodes. This guide provides the complete specification and production-grade YAML workflow for implementing GitHub Actions integration pipelines. --- ️ The Continuous Integration & Deployment Pipeline Flow --- Complete GitHub Actions Workflow (deploy.yml) Create a YAML workflow file inside your repository at .github/workflows/deploy.yml: ``yaml name: "Hoox Production CI/CD Pipeline" on: push: branches: main pullrequest: branches: main concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: verify-and-deploy: name: "Verify & Deploy Stack" runs-on: "ubuntu-latest" timeout-minutes: steps: . Checkout repository with all worker submodules recursively name: "Checkout Codebase" uses: "actions/checkout@v" with: submodules: "recursive" fetch-depth: . Install Bun JavaScript runtime environment name: "Setup Bun Runtime" uses: "oven-sh/setup-bun@v" with: bun-version: "latest" . Cache Bun dependency modules to optimize pipeline speeds name: "Cache Workspace Dependencies" uses: "actions/cache@v" with: path: "~/.bun/install/cache" key: "${{ runner.os }}-bun-${{ hashFiles('/bun.lockb') }}" restore-keys: | ${{ runner.os }}-bun- . Install all monorepo dependencies name: "Install Dependencies" run: "bun install" . Check formatting and ESLint rules name: "Run Lint Checks" run: "bun run lint" . Verify TypeScript compile-time type-safety (tsc --noEmit) name: "Run Type Checks" run: "bun run typecheck" . Execute all unit and integration test assertions (excluding live tests) name: "Run Bun Test Suite" run: "bun test" . Deploy all database schemas and workers in correct sequence name: "Deploy Entire Edge Stack" if: "github.ref == 'refs/heads/main' && github.eventname == 'push'" env: CLOUDFLAREAPITOKEN: "${{ secrets.CLOUDFLAREAPITOKEN }}" CLOUDFLAREACCOUNTID: "${{ secrets.CLOUDFLAREACCOUNTID }}" SUBDOMAINPREFIX: "${{ secrets.SUBDOMAINPREFIX }}" run: | Bootstrap local path binaries bun run build:cli Deploy D SQL schemas to production npx wrangler d execute trade-data-db --file=workers/trade-worker/schema.sql --remote --yes Sequentially upload all enabled workers ./packages/cli/bin/hoox.js deploy all --auto --quiet Post-deployment: update service bindings URLs globally ./packages/cli/bin/hoox.js deploy update-internal-urls --quiet Post-deployment: apply KV manifest configurations ./packages/cli/bin/hoox.js deploy kv-config --quiet Post-deployment: update Telegram bot webhook routing path ./packages/cli/bin/hoox.js deploy telegram-webhook --quiet ` --- Managing Secrets & Variable Scopes To authorize GitHub to interact with your Cloudflare account, navigate to your repository’s Settings > Secrets and variables > Actions and register three Action Secrets: . CLOUDFLAREAPITOKEN: A secure, scoped token with Workers, D, KV, and DNS write permissions. . CLOUDFLAREACCOUNTID: Your unique -character Cloudflare dashboard hash. . SUBDOMAIN_PREFIX: The subdomain namespace chosen for your deployments. Note: You never need to store worker-specific secrets (like Bybit API keys or Telegram Bot tokens) in GitHub Secrets. These are stored directly in Cloudflare's secured key vaults. The CI pipeline only deploys the code logic; the running edge isolates pull their credentials locally from Cloudflare’s hardware-level Secret Store at runtime. --- Pipeline Caching & Concurrency Controls Concurrency Lock: The concurrency` block configured in the YAML ensures that if you push a new commit while a previous deployment pipeline is running, GitHub Actions will automatically cancel the older, redundant run to avoid race conditions or double-deploying. Bun Cache: Caching dependency directories reduces build-time installation overhead from minutes to under seconds. Next Steps Production Deployment Manual — Audit DNS zones and custom domain routing options. System Observability & Monitoring — Stream console logs and check analytics datasets. FILE: docs/devops/deployment/monitoring.md Observability & Telemetry Operating a globally distributed algorithmic trading network demands extreme observability. A silent failure in an order loop or a transient API throttling event can lead to missed targets and unhedged exposures. This guide outlines our telemetry architecture, covering Cloudflare Workers % request sampling, time-series SQL database queries, R logging, and automated alarm systems. --- . % Request Head Sampling To monitor traffic at Cloudflare's edge compiler level, every worker in the Hoox monorepo enables native observability tracing inside its wrangler.jsonc: ``jsonc { "observability": { "enabled": true, "headsamplingrate": , // Captures and logs % of all incoming requests }, } ` Metrics Tracked Automatically Once enabled, Cloudflare captures and graphs these metrics near-instantaneously: Requests velocity: Total hits and requests/second rates. CPU execution duration (ms): The exact CPU time consumed by the isolate thread. Uncaught Exceptions: Crashes or code errors that bypass middlewares. Subrequest Counts: Outbound HTTP calls made to exchange APIs or other workers. --- . Cloudflare Analytics Engine (SQL Telemetry) While Cloudflare collects basic HTTP metrics, Hoox uses Cloudflare Analytics Engine inside analytics-worker to track trading-specific variables (e.g. execution slippage, exchange response delays, fee sums). Under-the-Hood SQL Queries The analytics-worker exposes a SQL interface to query the metrics dataset directly from your Next.js Dashboard: `sql / Query : Calculate the th percentile latency of Bybit API order fills / SELECT quantiles(.)(double) as platencyms, count() as totalexecutions FROM hooxtelemetry WHERE blob = 'trade-worker' AND blob = 'bybit' AND timestamp >= now() - INTERVAL '' HOUR / Query : Aggregate error velocities across all edge isolates / SELECT blob as workername, count() as errorcount FROM hooxtelemetry WHERE blob = '' -- Success = false AND timestamp >= now() - INTERVAL '' HOUR GROUP BY workername ` --- . Logging & R Storage Offloading Because transactional databases like SQLite D have write limits, Hoox implements a dual-tier logging policy: High-Value Data: Transaction statuses and fills are written to your D trades table. Verbose Telemetry: Full, verbose JSON payload exchanges, network headers, and WebSocket stream records are serialized and saved to R Storage using date-based key paths: logs/bybit/BTCUSDT/--/order-.json This offloading reduces database write volumes by up to %, keeping your database compact, fast, and fully within free-tier limits. --- . Standardized Alarm Systems If a critical error or execution failure occurs (e.g., an order is rejected due to insufficient margin, or the kill switch is flipped due to drawdown limits): . The executing worker intercepts the exception using the shared error handler. . Direct V Service Binding pings telegram-worker instantly. . You receive an emergency alert on your phone. `typescript // Standard alarm notification trigger if (orderResponse.status === "Rejected") { await env.TELEGRAMSERVICE.fetch("https://telegram-worker/alert", { method: "POST", headers: { "Content-Type": "application/json", "X-Internal-Auth-Key": env.INTERNALKEYBINDING, }, body: JSON.stringify({ chatId: env.TELEGRAMCHATIDDEFAULT, message: Emergency Order Reject!\nExchange: Bybit\nSymbol: BTCUSDT\nReason: Insufficient Margin, }), }); } ` --- Tip: Need to tail live worker logs to debug a custom strategy? Run hoox logs tail trade-worker` in your terminal to open a real-time WebSocket connection to Cloudflare’s global edge logging console! Next Steps Debugging Runbook — Diagnose local and remote V exceptions using diagnostic profiles. Self-Healing & Repair — Recover from degraded workers and provision missing bindings. FILE: docs/devops/deployment/zero-trust.md Zero Trust & Security Hardening While the Hoox dashboard features a highly secure, custom cookie-based authentication middleware, wrapping your dashboard and API endpoints inside Cloudflare Zero Trust (Access) provides an enterprise-grade security perimeter. By placing your deployment behind Cloudflare Access, you can enforce Multi-Factor Authentication (MFA), restrict access to specific GitHub/Google SSO identities, evaluate device posture, and drop malicious scanner payloads at the DNS level before they ever hit your workers. --- ️ The Zero Trust Protective Boundary Zero Public Exposure: The dashboard isolate does not evaluate public logins directly. MFA Gate: Users are intercepted by a secure Cloudflare authentication card at the nearest edge PoP. Zero Cost: Cloudflare's Zero Trust free tier includes up to users, which is more than enough for a personal algorithmic trading desk. --- . Step-by-Step Dashboard Access Setup Step : Enable Zero Trust on Your Account . Log in to the Cloudflare Dashboard and click Zero Trust on the sidebar. . If this is your first time, follow the onboarding prompts to register a unique Team Name (e.g. alpha-trading.cloudflareaccess.com). --- Step : Create a Self-Hosted Application . In the Zero Trust dashboard, navigate to Access > Applications and click Add an application. . Select Self-hosted. . Application Name: Hoox Dashboard Cockpit. . Session Duration: Select your preference (e.g. Hours to prevent constant login prompts). . Application Domain: Enter the custom domain mapped to your dashboard worker (e.g., hoox.my-trading-empire.com). --- Step : Configure Authorization Policies . Click Next to proceed to the Policies tab. . Policy Name: Allow Admin Only. . Action: Allow. . Configure Rules: Include: Select Emails and enter your personal email address (enables Email OTP). Include (SSO): Alternatively, select GitHub Org/Teams or Google Workspace to enable SSO integrations. . In the Require block, you can optionally require a valid security key (MFA) or device posture check (e.g. verifying that your laptop runs a specific OS version). --- Step : Map Identity Providers & Save . In Settings > Authentication, link your desired login providers (Google Workspace, GitHub OAuth, or Email OTP). . Save the application. . Open your browser and navigate to your custom domain (https://hoox.my-trading-empire.com). You will be intercepted by your Cloudflare Access card. Once authorized, you are passed cleanly to your Next.js dashboard. --- . Strict WAF Webhook IP Allow-listing To ensure that only TradingView's official servers can fire signals to your /webhook entryway: . Under your Cloudflare DNS zone dashboard, navigate to Security > WAF > Custom Rules. . Click Create Rule. . Rule Name: Restrict /webhook to TradingView IPs. . Field: URI Path | Operator: equals | Value: /webhook. . And: IP Source Address | Operator: is not in | Value: (Paste TradingView's official IP ranges here, which are automatically synced by running the hoox waf configure --TradingView-only command). . Action: Block (or Challenge). . Save. All unauthorized traffic hitting /webhook is dropped instantly at the DNS edge, preventing any V compute load. ``bash Automated WAF setup via CLI hoox waf configure --TradingView-only ` --- ️ . Optional: Bypassing Local Dashboard Auth Once your custom domain is wrapped inside Cloudflare Access, the dashboard's built-in login form (DASHBOARDUSER, DASHBOARDPASS) becomes redundant. To streamline access: . Edit the Next.js middleware.ts file inside workers/dashboard/src/. . Toggle the authentication checker to leverage Cloudflare's Access headers: `typescript // Next.js Edge Middleware export function middleware(request: Request) { // Verify the JWT payload injected in headers by Cloudflare Access const cfAccessJwt = request.headers.get("Cf-Access-Jwt-Assertion"); if (cfAccessJwt) { // Cloudflare has already authenticated the session. Bypass local login. return NextResponse.next(); } // Fallback to local cookie checks... } `` Next Steps Next.js Dashboard worker Profile — Review OpenNext compilation and asset bindings. System Observability & Metrics — Setup time-series logging and Analytics Engine tables. FILE: docs/devops/development/local-dev.md Local Development Setup Hoox provides a comprehensive local development workspace designed to emulate your production Cloudflare edge environment. Developers can choose between running microservices natively on local Wrangler V isolates or inside completely isolated, containerized Docker stacks, with real-time log tailing and TUI diagnostics. --- . Dev Runtime Selection: Native vs. Docker The hoox dev start command orchestrates the boot sequence for all enabled workers and supports two execution runtimes: | Runtime Mode | Boot Command | Latency / Hot-Reload | Isolation Level | Ideal Use Case | | :----------- | :------------------ | :------------------: | :------------------------------: | :--------------------------------------------------------------- | | Native | wrangler dev | > workers/hoox/.dev.vars `` Warning: .dev.vars files contain local plaintext keys and are excluded from git index tracking via .gitignore. Never remove these files from .gitignore or check them into your repository. --- Tip: If local tests fail with Time-Stamp Expired errors when calling exchange APIs, check that your local machine's NTP system clock is synchronized: sudo ntpdate pool.ntp.org` (or check date/time settings on macOS/Windows)! Next Steps Testing Standards — Run unit and integration tests using Bun's native test runner. Debugging Runbook — Debug local and remote isolates, tail logs, and trace queries. FILE: docs/devops/development/testing.md Testing Framework & QA Standards To protect live capital and ensure robust order routing, Hoox mandates a rigorous testing pipeline. With money on the line, we verify every contract calculation, rate-limiting gate, and database query. Our test suite is powered natively by Bun's high-speed test runner, comprising test files and , individual test assertions split into four distinct diagnostic layers. --- ️ The QA Testing Layers --- Running Tests: CLI Commands A. Core Platform Verification (Excluding Live) ``bash . Run all unit, integration, and EE smoke tests in parallel bun test . Run the suite and output a detailed V coverage report bun test --coverage ` B. Workspace-Specific Targeted Runs To optimize developer feedback loops, you can target specific workspaces or workers: `bash Run CLI commands tests only (packages/cli/) bun run test:cli Run Terminal UI tests only (packages/tui/) bun run test:tui Run shared helper tests only (packages/shared/) bun run test:shared Run all edge workers unit tests (workers/) bun run test:workers Run a single specific test file with hot-reload watch mode bun test workers/agent-worker/src/index.test.ts --watch ` C. Advanced Integration & Live Runs `bash Run Miniflare gateway integration tests bun run test:integration Run EE CLI lifecycle smoke tests bun run test:ee Run live Cloudflare API integration tests (requires tests/live/.env credentials) bun run test:live --jobs ` --- Type-Safe Mocking Specifications (No as any) To enforce strict TypeScript compiler safety, test files must never utilize as any to bypass types when mock-binding resources. Always cast stubs using as unknown as Env: `typescript import { describe, it, expect } from "bun:test"; import type { Env } from "../src/index"; describe("trade-worker Gateway Router Mocking", () => { it("should securely mock internal service binding fetchers", async () => { // . Construct a type-safe mock environment structure const mockEnv = { INTERNALKEYBINDING: "localsecrettoken", TELEGRAMSERVICE: { fetch: async (url: string, init?: RequestInit) => { // Verify auth headers exist const headers = init?.headers as Record; if (headers["X-Internal-Auth-Key"] !== "localsecrettoken") { return new Response(JSON.stringify({ success: false }), { status: , }); } return new Response( JSON.stringify({ success: true, messageId: , }), { status: } ); }, } as Fetcher, } as unknown as Env; // . Execute assertions const res = await mockEnv.TELEGRAMSERVICE.fetch( "https://telegram-worker/alert", { method: "POST", headers: { "X-Internal-Auth-Key": "localsecrettoken_", }, } ); const data = await res.json(); expect(res.status).toBe(); expect(data.success).toBe(true); expect(data.messageId).toBe(); }); }); ` --- Continuous Integration Gates & Coverage Targets Our GitHub Actions workflow enforces two strict quality gates before any code is approved for production deployment: . TypeScript Type Safety: All workspaces must compile without errors using tsc --noEmit. . Coverage Thresholds: The monorepo enforces a minimum % coverage threshold across all core execution paths (packages/cli, packages/shared, workers/hoox, workers/trade-worker). `bash Check your local workspace coverage statistics bun test packages/shared/ --coverage `` Next Steps Debugging Telemetry Runbook — Learn how to trace active V memory, tail logs, and audit SQL execution. Local Development Setup — Configure Wrangler and Docker compose to run testbeds. FILE: docs/devops/development/debugging.md Edge Debugging & Telemetry Debugging globally distributed serverless microservices presents unique operational challenges. Because code runs on Cloudflare's edge V isolates without a persistent server host, traditional step-through debugging is replaced by structured logging, real-time edge telemetry tailing, and distributed tracing. This document is your engineering runbook for debugging and resolving runtime anomalies in the Hoox monorepo. --- . Real-Time Telemetry: Tailing Production Logs Cloudflare’s wrangler tail engine establishes an active, secure WebSocket stream straight from Cloudflare's global edge nodes to your terminal, printing every console.log, exception trace, and HTTP status code in real-time. You can trigger this streaming telemetry via the Hoox CLI or Wrangler: ``bash A. Recommended: Stream live console logs for a specific worker via Hoox CLI hoox logs tail trade-worker B. Stream gateway traffic in real-time hoox logs tail hoox C. Alternatively, invoke Wrangler directly for custom configurations npx wrangler tail hoox --config workers/hoox/wrangler.jsonc ` --- . Distributed Tracing: The requestId Standard Because a single TradingView alert flows through multiple workers (Gateway → trade-worker → d-worker → telegram-worker), locating a specific transaction log in a sea of concurrent entries is impossible without a unified trace parameter. The RequestId Protocol . Generation: The hoox gateway generates a unique, cryptographically secure UUIDv immediately upon receiving a webhook payload. This is set as the requestId in the transaction context. . Propagation: Every internal service binding call transmits this UUID as the X-Request-Id HTTP header. . Structured Ingestion: When logging error telemetry or writing trade fills to R and D databases, workers attach the requestId as a dedicated index column. . Unified Auditing: You can audit an entire transaction's lifecycle across all workers by running a single database query filtering by the trace ID: `sql SELECT createdat, worker, message, severity FROM systemlogs WHERE requestid = 'bdebd-bd-bad-bdd-bdbdcbd' ORDER BY createdat ASC ` --- ️ . Operational Runbooks for Common Edge Failures A. Symptom: Unauthorized on Internal Worker Calls Diagnostics: The calling worker gets a Unauthorized response when querying internal services like d-worker or trade-worker. Primary Root Cause: The INTERNALKEYBINDING secret does not match between the calling worker and the target worker. Resolution: . Inspect the secret existence on both workers: hoox secrets check. . If mismatched, re-inject the secret globally using one command: `bash hoox secrets set INTERNALKEYBINDING "yoursecuresharedinternalkey" ` --- B. Symptom: Bad Gateway on Webhook Routes Diagnostics: An incoming signal returns a error instantly. Primary Root Cause: A Service Binding target declared in the gateway's wrangler.jsonc has not been deployed yet. Resolution: . Run the dependency check: hoox check health. . Redeploy the entire stack in the correct dependency order: `bash hoox deploy all --auto ` --- C. Symptom: DERROR: no such table Diagnostics: Worker database transactions fail with table missing errors. Primary Root Cause: Relational SQLite schemas were never initialized on your production D instance. Resolution: . Initialize database tables and run pending drizzle migrations: `bash hoox db apply --remote hoox db migrate --remote ` --- D. Symptom: KV Configuration Propagation Delays Diagnostics: You toggled a KV configuration (e.g. turned trade:killswitch = false`), but some incoming signals are still being rejected. Primary Root Cause: Cloudflare KV is eventually consistent. Updates can take up to seconds to propagate to all global edge locations. Resolution: Wait - seconds for cache validation to settle globally. Do not trigger rapid test webhooks immediately after modifying configuration keys. Next Steps Testing Framework & QA Standards — Run local unit and integration tests using Bun's native test runner. Self-Healing & System Repair — Run diagnostics, targeted component repairs, and full system rebuilds. FILE: docs/devops/api/endpoints.md API Endpoint Directory This directory provides the complete HTTP REST API specification for all public and internal endpoints exposed across the Hoox edge microservices stack. --- Security & Authorization Headers All internal calls between workers (via V Service Bindings) must provide the standard internal authentication header: ``http X-Internal-Auth-Key: ` Public webhook and dashboard endpoints use cookie authorization or custom API keys: Webhook Ingestion: Authenticated using the apiKey property inside the JSON payload. Telegram webhook: Authenticated via the secure token path: /telegram/. --- Ingress Webhook Endpoints (workers/hoox) The public gateway acts as the primary firewall and entry entryway for all external trade signals. A. Ingest Signal Webhook Receives TradingView alerts or automated cURL signals. Path: /webhook Method: POST JSON Payload: `json { "apiKey": "securewebhookkey", "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": , "idempotencyKey": "uuid-bdebd-bd" } ` Success Response ( OK): `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "exchange": "bybit", "symbol": "BTCUSDT", "action": "LONG", "result": { "orderId": "", "status": "Filled", "price": . } } ` --- B. Proactive Health Diagnostics Path: /health Method: GET Success Response ( OK): `json { "status": "ok", "timestamp": , "bindings": { "d": "connected", "kv": "connected", "queue": "active" } } ` --- ️ Database Service Endpoints (workers/d-worker) The d-worker serves as a private, internal SQL proxy database. A. Execute Single SQL Statement Path: /query Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "query": "SELECT FROM trades WHERE symbol = ? LIMIT ?", "params": ["BTCUSDT", ] } ` Success Response ( OK): `json { "success": true, "results": [{ "id": "trade-", "symbol": "BTCUSDT", "price": }], "meta": { "rowsread": , "duration": . } } ` --- B. Execute Transactional Batch Statements Path: /batch Method: POST JSON Payload: `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "queries": [ { "query": "INSERT INTO trades (id, symbol) VALUES (?, ?)", "params": ["t-", "ETHUSDT"] }, { "query": "UPDATE positions SET size = size + . WHERE symbol = 'ETHUSDT'", "params": [] } ] } ` Success Response ( OK): `json { "success": true, "results": [{ "meta": { "changes": } }, { "meta": { "changes": } }] } ` --- AI Risk & Chat Endpoints (workers/agent-worker) Bridges background risk audits and multi-provider AI chat streams. A. Conversational Chat Stream (Server-Sent Events) Path: /agent/chat Method: POST Headers: Accept: text/event-stream JSON Payload: `json { "prompt": "Summarize my trade history and average win rate today.", "stream": true, "provider": "anthropic" } ` Success Response: Emits standard text/event-stream updates, terminating with data: [DONE]. --- B. Multimodal AI Vision Audit Path: /agent/vision Method: POST JSON Payload: `json { "imageBase": "iVBORwKGgoAAAANSUhEUgAA...", "prompt": "Evaluate this trading chart image for support and resistance levels." } ` Success Response ( OK): `json { "success": true, "analysis": "Based on the provided chart screenshot, there is strong horizontal support at $,..." } `` Next Steps Request Payload Schemas — Analyze the complete JSON request schemas and type rules. Standard Response Schemas — Check error factories and normal JSON envelopes. FILE: docs/devops/api/payloads.md Request Payload Schemas To maintain robust data routing and prevent runtime failures, Hoox enforces a strict payload contract across all internal and public service boundaries. All incoming requests are validated by active JSON Schema or Zod middleware before entering V execution loops. This document details the exact JSON schemas, TypeScript interfaces, and validation rules for all primary request payloads. --- ️ . Standard Request Envelope Every service-to-service invocation (via Service Bindings) wraps its business parameters inside a standardized Request Envelope containing distributed tracing indices: ``typescript export interface RequestEnvelope { requestId: string; // Unique UUIDv distributed trace ID payload: T; // Service-specific payload } ` `json { "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "payload": { "symbol": "BTCUSDT", "quantity": . } } ` --- . Trade Execution Payloads (trade-worker) The execution engine processes two primary types of order payloads: A. Centralized Exchange Order Payload (/webhook & /process) `typescript export interface CexOrderPayload { exchange: "binance" | "bybit" | "mexc"; // Target exchange action: "LONG" | "SHORT" | "CLOSE"; // Margin position action symbol: string; // Standardized asset ticker (e.g. "BTCUSDT") quantity: number; // Order size in contracts or tokens leverage?: number; // Optional margin leverage multiplier price?: number; // Optional execution limit price orderType?: "MARKET" | "LIMIT"; // Default: MARKET } ` `json { "exchange": "bybit", "action": "LONG", "symbol": "BTCUSDT", "quantity": ., "leverage": , "orderType": "MARKET" } ` --- B. On-Chain DeFi Swap Payload (/dex) `typescript export interface DexSwapPayload { chain: "ethereum" | "arbitrum" | "polygon"; // EVM target network to: string; // Recipient address or Uniswap Router value: string; // Transaction value in Wei (as string) data: string; // Encoded contract call data bytes gasLimit?: number; // Optional transaction gas limit } ` `json { "chain": "arbitrum", "to": "xbecdabeedeacdf", "value": "", "data": "xacbb..." } ` --- ️ . Database SQL Query Payloads (d-worker) The SQLite database proxy accepts parameterized SQL statements to protect against SQL injections: A. Execute Single SQL Statement `typescript export interface SqlQueryPayload { query: string; // Parameterized SQL statement params: Array; // Binding values } ` `json { "query": "SELECT FROM trades WHERE symbol = ? AND status = ?", "params": ["BTCUSDT", "Filled"] } ` --- . Telegram Notification Payloads (telegram-worker) Used to push structured alerts and charts to your mobile device: `typescript export interface TelegramAlertPayload { chatId: string; // Target Telegram Chat ID message: string; // Formatted message content parseMode?: "HTML" | "MarkdownV"; // Default: HTML } ` `json { "chatId": "", "message": "Alert: Position filled at ,.", "parseMode": "HTML" } ` --- Tip: Adding new fields to a payload schema? Remember to update the corresponding type interfaces in @jango-blockchained/hoox-shared/types` to ensure complete type safety across all workers! Next Steps API Endpoint Directory — Analyze REST routes, headers, and endpoints mappings. Standard Response Schemas — Check success envelopes and error models. FILE: docs/devops/api/responses.md Standard Response Schemas To ensure predictable error handling and parsing across all microservices, Hoox enforces a strict response contract. Every worker responds with a standardized JSON envelope containing tracing details, operation status, results payload, and detailed error models. This document details the exact JSON templates, types, and error factories utilized in the monorepo. --- ️ . Standard Response Envelope Every HTTP response returned by an edge worker is encapsulated within a unified JSON envelope: ``typescript export interface ResponseEnvelope { success: boolean; // Absolute state of the operation requestId: string; // UUIDv trace ID mapped from request result?: T; // Operation success metadata payload error?: { // Detail model present only if success = false code: string; // Unique machine-parseable error token message: string; // Human-readable error description details?: any; // Optional specific array of field issues }; } ` --- . Success Response Templates A. Trade Execution Fill Success (trade-worker - OK) `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "result": { "orderId": "", "status": "Filled", "executedQty": ., "price": ., "timestamp": }, "error": null } ` --- B. Telegram Push Success (telegram-worker - OK) `json { "success": true, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "result": { "messageId": , "delivered": true }, "error": null } ` --- . Error Models & Edge Error Codes When a worker operation fails, the success flag is set to false, the result field is omitted or set to null, and the error model is fully populated: A. Bad Request (JSON Validation Error) `json { "success": false, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "error": { "code": "VALIDATIONERROR", "message": "Invalid JSON payload structure.", "details": [{ "field": "quantity", "issue": "Must be greater than zero." }] } } ` --- B. Conflict (Idempotency Mutex Intercept) `json { "success": false, "requestId": "bdebd-bd-bad-bdd-bdbdcbd", "error": { "code": "DUPLICATEREQUEST", "message": "Order rejected. Durable Object locked: trace ID already processed in the last hours." } } ` --- ️ . Shared Errors Factory Middleware To enforce this response contract without writing redundant JSON wrappers in every worker, we use the standardized Errors factory from the shared monorepo package @jango-blockchained/hoox-shared/errors: `typescript import { Errors } from "@jango-blockchained/hoox-shared/errors"; // . Validation Failures ( Bad Request) if (!payload.symbol) { return Errors.badRequest("Symbol is a required parameter."); } // . Secret Key Mismatch ( Unauthorized) if (requestHeaderKey !== env.INTERNALKEYBINDING) { return Errors.unauthorized("Access Denied: Invalid X-Internal-Auth-Key."); } // . System Exceptions ( Internal Server Error) try { await database.write(data); } catch (err: any) { return Errors.internal(Database write exception: ${err.message}); } ` These factory methods automatically serialize the exception, attach the active requestId from the context, set the correct HTTP status code, and return a compliant Response` object. Next Steps API Endpoint Directory — Analyze REST routes, headers, and endpoints mappings. Request Payload Schemas — Check JSON request payload specifications and typescript interfaces. FILE: docs/devops/cli_features.md ️ CLI Architecture & Features The hoox CLI (packages/cli) is the unified lifecycle engine of the trading platform monorepo. It governs local sandboxes, compiles TypeScript structures, coordinates Cloudflare infrastructure resources, deploys edge isolates, manages encrypted secrets, and executes self-healing diagnostics. --- ️ Monorepo Workspace Design The CLI is integrated into our monorepo using Bun Workspaces, which link local packages together. This design ensures that the CLI binary can resolve and load local shared types (@jango-blockchained/hoox-shared) and TUI components (packages/tui) instantly without network downloads or pre-compilation overhead: `` hoox-setup/ (Monorepo Root) ├── packages/ │ ├── cli/ CLI Source code (entry binary: bin/hoox.js) │ ├── tui/ OpenTUI dashboard source code │ └── shared/ Common libraries (auth, router, error models) ├── workers/ │ └── ... Edge V isolates └── package.json Root workspace manager ` --- . Command-Line Core Architectures The CLI binary parses terminal instructions using the following architectural layers: A. Command Dispatcher (packages/cli/src/index.ts) Intercepts all incoming arguments (e.g. hoox infra provision), evaluates global flags (--json, --quiet), validates configuration integrity, and delegates execution to target command modules under src/commands/. B. Cloudflare API Adapters (src/adapters/) Translates command intentions (like hoox infra d create) into parameterized Cloudflare API REST payloads, bypassing wrangler wrappers when high-performance execution is needed. C. State Engine (src/core/) Tracks active project profiles, enabled worker matrices, and workspace configuration formats (wrangler.jsonc vs. wrangler.toml). --- . Declarative Config Mapping & Validation To prevent configuration drift, the CLI enforces strict type validation on wrangler.jsonc files: . Config Interfaces: Built-in parsers validate configuration files against type-safe TypeScript interfaces (Config and WorkerConfig) defined in src/core/types.ts. . Setup Verification (hoox check setup): Compares active workspace profiles against example files, audits environment variables keys, and scans for missing bindings, outputting formatted terminal reports. --- . Self-Healing & Diagnostics Engine One of the CLI's most powerful features is its guided repair framework (hoox repair command groups): Diagnostic Probes: The hoox repair check command runs a -step checklist (verifying submodule checkouts, NPM/Bun package resolutions, TypeScript variables, Cloudflare zone links, and encrypted credentials). Automated Recovery: If a missing resource is identified (e.g. a D database ID is bound in wrangler.jsonc but the database doesn't exist on your Cloudflare account), the repair engine prompts you and provisions it automatically: `bash Provision missing Cloudflare bindings and repair system states hoox repair infra ` --- Tip: Every single command supports the --json global flag. This outputs machine-parseable JSON payloads (e.g. hoox monitor status --json`), allowing you to integrate the CLI with external telemetry dashboards or alert scripts effortlessly! Next Steps CLI Reference Manual — Review the complete command tree, positional arguments, and flags. Wrangler Setup & Tooling — Configure Wrangler to bind local D and KV instances for dev testing.