[AI Risk Manager & AI Gateway]
How the agent-worker runs 5-minute cron checks to calculate trailing stops, evaluate max daily drawdowns, and govern a multi-provider fallback AI gateway.
The agent-worker is the autonomous central nervous system of the Hoox trading platform. Operating on a continuous 5-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.
1. Automated Risk Protection Engine
Every 5 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 V8 compiler level:
- The Formula:
Trailing Stop Price (Long) = Peak Price × (1 − Trailing Deviation %) - If a LONG trade entry is at $$100$ and has a $2%$ trailing deviation, the initial stop-loss is placed at $$98$.
- If the market price rallies to a peak of $$120$, the stop-loss is automatically adjusted up to $$117.60$.
- If the price declines from $$120$ down to $$117.60$, the stop is triggered at the exchange level, locking in a $$17.60$ 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 1 ($3%$ Profit): Automatically flattens $25%$ of open position size.
- Target 2 ($5%$ Profit): Flattens another $25%$ and moves the stop-loss of the remaining $50%$ 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:
Daily Drawdown % = ((Starting Daily Balance − Current Balance) / Starting Daily Balance) × 100 - If the drawdown exceeds your KV threshold (e.g.
trade:max_daily_drawdown_percentis5), the agent-worker immediately triggers the Global Kill Switch by writingtrade:kill_switch = truetoCONFIG_KV. - Calls the
trade-workerservice binding to submit immediate market close orders, flattening all active positions across all exchanges near-instantaneously.
# 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
2. Multi-Provider AI Gateway & Reasoning
Behind the scenes, agent-worker governs a Multi-Provider AI Gateway (supporting 5 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]
│
▼
[1. Cloudflare Workers AI] (Zero cost, native LLaMA 3) ──► Fail? ──┐
│
▼
[2. Anthropic API] (Claude 3.5 Sonnet) ◄───────────────────────────┘
│
Fail? ──► [3. Google AI] (Gemini 1.5 Pro) ──► Fail? ──► [4. OpenAI] (GPT-4o)
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 Base64 images.POST /agent/reasoning— Extended thinking queries with reasoning models (o1, DeepSeek). Respectsthinking_effortlevels.GET /agent/usage— Detailed token usage and cost metrics across all 5 providers, including per-provider input/output tokens and cumulative USD cost.GET /agent/health— Health check for all AI providers — returns latency and status for each provider in the fallback chain.
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.