Skip to content

ILIV007/TradeAgentIV

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

78 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ TradeAgent IV HYBRID

AI-Powered Cryptocurrency Market Intelligence System Serverless β€’ Multi-Model AI β€’ Real-Time Telegram Automation

Cloudflare Workers Telegram Bot AI Models License Version


πŸ“– Overview

TradeAgent IV HYBRID is an advanced, serverless cryptocurrency intelligence system built on Cloudflare Workers. It automates Telegram channel posting with real-time market analysis, powered by a proprietary Emotion Engine that gauges market psychology.

The system operates on a 100% free AI tier architecture, using multi-tier API failovers to guarantee maximum uptime with zero infrastructure cost.


✨ Key Features

🧠 Advanced AI Intelligence

  • Multi-Model Failover: Cascades through Gemini 3.5 Flash β†’ 3.1 Flash-Lite β†’ 2.5 Flash β†’ OpenRouter FREE models automatically.
  • Bilingual Output: Full English analysis followed by a dense Persian (Farsi) summary.
  • Custom Prompts: Admins can inject custom focus areas into the AI analysis.

πŸ“Š 3-Tier Coin Tracking

  • Tier 1 (Blue Chips): BTC, ETH, SOL, XRP, BNB, XAUT
  • Tier 2 (Utility & L2s): ADA, LINK, AVAX, SUI, HBAR, POL, INJ, ARB, OP, ATOM, TON, DOT, LTC, NEAR, APT, UNI, TRX, HYPE
  • Tier 3 (Meme & AI): SHIB, DOGE, PEPE, WIF, BONK, TAO, FET, RENDER

🎭 Proprietary Emotion Engine

Calculates real-time market psychology using BTC/ETH price action, Fear & Greed Index, and BTC Dominance.

Emotion States:

  • πŸ’€ PANIC β€” Extreme market crash detected
  • 😰 FEAR β€” Conservative accumulation opportunities
  • 😐 NEUTRAL β€” Sideways market, balanced analysis
  • πŸ”₯ MOMENTUM β€” Upside building, optimistic tone
  • πŸš€ BREAKOUT β€” Confirmed breakout, pullback warnings
  • 🧨 FOMO β€” Extreme greed, risk emphasis

πŸ”„ Bulletproof Architecture

  • Multi-API Failover: CoinGecko β†’ CoinMarketCap β†’ Binance
  • Smart Deduplication (v3): 10-min gap + 5-min lock + race-proof
  • Circuit Breakers: Auto-trips failing AI models to prevent quota exhaustion
  • Serverless: Runs entirely on Cloudflare Workers with KV storage

πŸ› οΈ Tech Stack

  • Runtime: Cloudflare Workers (JavaScript ES Modules)
  • Storage: Cloudflare KV (Snapshots, Dedup locks, AI Cache, User States)
  • Data Providers: CoinGecko, CoinMarketCap, Binance, Alternative.me
  • AI Providers: Google Gemini, OpenRouter
  • Messaging: Telegram Bot API (HTML Parse Mode, Inline Keyboards, Webhooks)

βš™οΈ Environment Variables

Secrets & API Keys

  • TELEGRAM_BOT_TOKEN β€” Your Telegram Bot API token
  • TELEGRAM_CHANNEL_ID β€” Target Telegram channel ID (e.g., @mychannel or -100...)
  • ADMIN_ID β€” Your Telegram User ID (admin panel access)
  • ADMIN_SECRET β€” Secure string for /admin HTTP authentication
  • COINGECKO_API_KEY β€” CoinGecko Demo/Pro API key
  • CMC_API_KEY β€” CoinMarketCap Pro API key
  • GEMINI_API_KEY β€” Google AI Studio API key
  • OPENROUTER_API_KEY β€” OpenRouter API key for fallback models

KV Namespace Binding

  • ALERTS_KV β€” Cloudflare KV Namespace for caching, deduplication, and state storage

πŸ€– Bot Commands

πŸ‘€ User Commands

  • /start β€” Open the main interactive menu
  • /price β€” Live 3-Tier market snapshot
  • /volume β€” Top 10 coins by 24h trading volume
  • /daily β€” Comprehensive daily market report
  • /trending β€” Currently trending coins
  • /fng β€” Fear & Greed Index with visual bar
  • /alerts β€” Configure custom price alerts
  • /settings β€” View bot configuration and API status
  • /help β€” List all available commands

πŸ›‘οΈ Admin Commands

  • /admin β€” Open the interactive Admin Control Panel
  • /sendprice β€” Manually push price snapshot to channel
  • /sendai β€” Generate and push new AI analysis
  • /sendall β€” Push full bundle (Sticker + AI + F&G + Futures)
  • /sendmovers β€” Push top gainers and losers
  • /sendfutures β€” Push funding rates and open interest
  • /senddaily β€” Push daily market report
  • /sendvolume β€” Push volume leaders
  • /sendtrending β€” Push trending coins
  • /sendfng β€” Push Fear & Greed index
  • /aiprompt β€” Inject custom prompt for next AI analysis

⏱️ Automated Cron Schedule

The system uses Cloudflare Cron Triggers for fully autonomous operation:

Every 30 Minutes (*/30 * * * *)

  • Fetches prices
  • Checks custom user alerts
  • Posts Market Snapshot

Every 8 Hours (0 */8 * * *)

  • Posts the "Bundle"
  • Starts with custom Sticker
  • Followed by AI Analysis, Fear & Greed, and Futures Funding Rates

3 Times Daily (0 9,15,21 * * *)

  • Posts Top Movers (Gainers & Losers)
  • Based on Binance 24h ticker data

πŸš€ Deployment

Step 1: Install Wrangler CLI

npm install -g wrangler

Step 2: Login to Cloudflare

wrangler login

Step 3: Create KV Namespace

wrangler kv:namespace create ALERTS_KV

Add the output to your wrangler.toml:

[[kv_namespaces]]
binding = "ALERTS_KV"
id = "your-namespace-id"

Step 4: Deploy the Worker

wrangler deploy

Step 5: Set Telegram Webhook

curl -F "url=https://your-worker.subdomain.workers.dev/webhook" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook

πŸ“‘ HTTP Endpoints

POST /webhook

Receives Telegram updates. No authentication required (secured by Telegram's secret token mechanism).

POST /admin

Manual trigger endpoint. Requires x-admin-secret header.

Example:

curl -X POST \
  -H "x-admin-secret: YOUR_SECRET" \
  "https://your-worker.workers.dev/admin?type=ai"

Available types: price, volume, daily, ai, trending, fng, futures, movers, all, alert, sticker

GET /debug

System health check and API diagnostics. Requires x-admin-secret header.

Example:

curl -H "x-admin-secret: YOUR_SECRET" https://your-worker.workers.dev/debug

πŸ”§ Configuration

AI Modes

  • Normal β€” Standard professional analysis
  • Deep β€” Institutional-grade analysis with trend structure and sector rotation
  • Short β€” Only trend direction, risk level, and 1 actionable insight
  • Emotion β€” Analysis matches current market emotion state

Scenarios

  • Bullish β€” Emphasize breakout potential and altseason signals
  • Bearish β€” Emphasize capital flight to safety and support levels
  • Neutral β€” Balanced view, no directional bias
  • Volatile β€” High volatility expected, emphasize risk management

πŸ“Š Data Sources

Primary: CoinGecko API

  • Full market data
  • 7d/30d price changes
  • Trending coins
  • Categories

Fallback 1: CoinMarketCap API

  • Latest quotes
  • Global metrics
  • Trending coins

Fallback 2: Binance API

  • 24h ticker data
  • Top gainers/losers
  • Futures data (funding rates, open interest, long/short ratio)

Sentiment: Alternative.me

  • Fear & Greed Index

🎨 UI Features

  • Modern HTML Formatting: Clean Telegram HTML with blockquotes
  • Visual Progress Bars: For Fear & Greed index
  • Color-Coded Changes: 🟒 Green for gains, πŸ”΄ Red for losses
  • Tiered Display: Organized coin listings by market cap tier
  • Sticker Integration: Auto-sends custom sticker before bundle posts
  • Inline Keyboards: Interactive admin control panel

πŸ›‘οΈ Security Features

  • Admin Authentication: Secret header for HTTP endpoints
  • User ID Verification: Admin-only commands protected
  • Rate Limiting: Circuit breakers prevent API quota exhaustion
  • Input Sanitization: HTML escaping for user-generated content
  • Deduplication: Prevents spam and race conditions

πŸ“ˆ Performance Optimizations

  • Timeout Protection: All fetches capped at 15-25 seconds
  • Parallel Requests: Uses Promise.all() for concurrent API calls
  • Caching: AI responses cached for 1 hour
  • Sticker Caching: File IDs cached for 30 days
  • Smart Retry Logic: Exponential backoff for failed requests

πŸ› Troubleshooting

AI Analysis Fails

  • Check Gemini API key is valid and has quota
  • Verify OpenRouter API key if using fallback models
  • Check /debug endpoint for detailed error messages

Messages Not Posting

  • Ensure bot is admin in the channel with "Post Messages" permission
  • Verify TELEGRAM_CHANNEL_ID is correct
  • Check /debug for channel access status

Price Data Missing

  • Verify at least one API key is configured (CoinGecko, CMC, or Binance)
  • Check API rate limits
  • Review worker logs for specific error messages

πŸ“œ License

Distributed under the MIT License. See LICENSE for more information.


πŸ™ Acknowledgments


TradeAgent IV Β· AI Crypto Intelligence Β· Built for the decentralized future

Report Bug Β· Request Feature

```

About

No description, website, or topics provided.

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors