show me code implementation for cloudflare
- User
show me code implementation for cloudflare
Assistant
Here's a practical implementation of a trading bot on Cloudflare Workers with TypeScript, leveraging Durable Objects for state management and KV for secrets:
1. Project Structure
cloudflare-trading-bot/ ├── src/ │ ├── index.ts # Main Worker (scheduled trigger) │ ├── DurableBot.ts # Durable Object for state ├── wrangler.toml # Configuration
2.
wrangler.toml(Configuration)name = "trading-bot" main = "src/index.ts" workers_dev = true compatibility_date = "2023-10-10" [vars] KV_SECRETS_NAMESPACE = "your_kv_namespace_id" # Replace with your KV namespace ID [durable_objects] bindings = [ { name = "DURABLE_BOT", class_name = "TradingBot" } ] [cron_triggers] # Run every minute (minimum interval) crons = ["*/1 * * * *"]
3.
src/DurableBot.ts(Durable Object for State)export class TradingBot { constructor(private state: DurableObjectState, private env: Env) {} // Handle incoming requests async fetch(request: Request) { const url = new URL(request.url); // Example: Handle a "check-price" command if (url.pathname === "/check-price") { return this.checkPrice(); } return new Response("Unknown command", { status: 400 }); } // Core trading logic async checkPrice() { try { // Fetch API key from KV (encrypted for security) const apiKey = await this.env.KV_SECRETS.get("BINANCE_API_KEY"); if (!apiKey) { return new Response("API key not found", { status: 500 }); } // Fetch BTC/USDT price from Binance (example) const response = await fetch( "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT" ); const data = await response.json(); const price = parseFloat(data.price); // Store price in Durable Object state await this.state.storage.put("lastPrice", price); // Simple strategy: Buy if price < $30,000 if (price < 30000) { await this.placeOrder(price); } return new Response(`Current BTC price: $${price}`); } catch (error) { console.error("Error:", error); return new Response("Internal error", { status: 500 }); } } // Place a test order (replace with real logic) async placeOrder(price: number) { console.log(`Placing buy order at $${price}`); // Implement exchange API integration here } }
4.
src/index.ts(Scheduled Worker)export interface Env { KV_SECRETS: KVNamespace; DURABLE_BOT: DurableObjectNamespace; } export default { async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) { // Get or create a Durable Object instance const id = env.DURABLE_BOT.idFromName("bot-instance"); const stub = env.DURABLE_BOT.get(id); // Send request to Durable Object const response = await stub.fetch("https://example.com/check-price"); console.log("Bot response:", await response.text()); }, };
5. Deployment Steps
1. Install Wrangler CLI
npm install -g @cloudflare/wrangler2. Create KV Namespace
wrangler kv:namespace create "KV_SECRETS" # Update wrangler.toml with the generated namespace ID3. Store API Keys Securely
wrangler kv:key put --namespace-id=<your_kv_id> BINANCE_API_KEY "your_api_key_here"4. Deploy
wrangler publish
6. Key Security Practices
- Encrypt Secrets: Use libraries like
crypto-jsto encrypt/decrypt keys in KV. - Rate Limiting: Add rate limiting to prevent abuse.
- Test Mode: Use paper trading accounts before going live.
7. Limitations & Workarounds
- Execution Timeout: Workers timeout after 50 seconds. Split logic into smaller chunks.
- State Size: Durable Object storage has size limits (use R2 for large datasets).
- WebSocket Support: Not available in Workers. Use exchange REST APIs instead.
8. Monitoring
- Cloudflare Logs: Use
wrangler tailto stream logs. - Third-Party Tools: Integrate with Sentry or Datadog for alerts.
This implementation provides a minimal viable trading bot that:
- Runs on a schedule via Cloudflare Cron Triggers
- Stores state in Durable Objects
- Secures secrets in KV
- Uses a simple price-checking strategy
For production, add:
- Exchange-specific order placement logic
- Backtesting framework
- Comprehensive error handling
- Alerting system for trades
Always test with a paper trading account before deploying real funds!
- Encrypt Secrets: Use libraries like
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.