{"id":50766134,"url":"https://github.com/kenken64/7monthindicator","last_synced_at":"2026-06-11T14:01:23.381Z","repository":{"id":311573802,"uuid":"1043840224","full_name":"kenken64/7monthIndicator","owner":"kenken64","description":"A sophisticated, AI-powered trading system that combines traditional technical analysis with   modern machine learning, multi-agent AI systems, and intelligent risk management - all wrapped in a   beautiful, mobile-friendly dashboard! 🚀","archived":false,"fork":false,"pushed_at":"2025-10-16T04:00:58.000Z","size":7098,"stargazers_count":1,"open_issues_count":1,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-16T20:58:29.793Z","etag":null,"topics":["binance-api","chartjs","coingecko-api","crewai","digitalocean","flask","openai","python","tailwindcss","talib"],"latest_commit_sha":null,"homepage":"http://178.128.57.58:5000/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kenken64.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-08-24T18:17:56.000Z","updated_at":"2025-10-15T19:58:35.000Z","dependencies_parsed_at":"2025-08-25T10:52:07.212Z","dependency_job_id":"21b91e72-238b-457e-a165-e0a06ab49b1f","html_url":"https://github.com/kenken64/7monthIndicator","commit_stats":null,"previous_names":["kenken64/7monthindicator"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/kenken64/7monthIndicator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenken64%2F7monthIndicator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenken64%2F7monthIndicator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenken64%2F7monthIndicator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenken64%2F7monthIndicator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kenken64","download_url":"https://codeload.github.com/kenken64/7monthIndicator/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kenken64%2F7monthIndicator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34201842,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-11T02:00:06.485Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["binance-api","chartjs","coingecko-api","crewai","digitalocean","flask","openai","python","tailwindcss","talib"],"created_at":"2026-06-11T14:01:11.005Z","updated_at":"2026-06-11T14:01:23.356Z","avatar_url":"https://github.com/kenken64.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CryptoCurrency AI Trading Bot Dashboard (Experimental) 🤖\n\n## The Super Smart Trading Robot - Explained for Kids! 🎮\n\nHey! Imagine you have a robot friend that helps you trade digital money (like game coins, but real!). Here's what makes it super cool:\n\n### 🎮 The Robot's Special Powers\n\n**Smart Decision Making**: Your robot looks at lots of clues before deciding to buy or sell - like checking the weather, your friend's mood, AND the calendar before planning a playdate. It needs at least 3 good clues to say \"yes, let's do this!\"\n\n**Safety First**: The robot watches your money closely and tells you if you're winning or losing, like keeping score in a video game. It even warns you if things are getting risky!\n\n### 🧠 The Robot's Super Brain\n\n**Learning from Big Coins**: Your robot watches Bitcoin and Ethereum (the most popular digital coins) to understand what ALL the other coins might do - like watching the popular kids to predict what might become cool at school!\n\n**Memory System**: It remembers everything it learns and stores it like saving your video game progress. Even if you turn it off and on again, it remembers!\n\n**Smart About Money**: Instead of asking expensive helpers for advice every time, it saves their answers and reuses them (like photocopying homework answers instead of doing it over and over 😄)\n\n### 📊 Picture Helper\n\n**Drawing Robot**: Another robot takes pictures of how prices go up and down (like a heart monitor but for money) and an AI teacher looks at these pictures to give advice - \"Should we buy? Sell? Or wait?\"\n\n### 🌐 Your Control Center (The Dashboard)\n\nThink of this like a video game menu where you can see:\n\n- 📈 Colorful charts showing if you're winning\n- 🌍 Market mood meter - Is everyone happy or scared? (Like checking if kids are excited or nervous at school)\n- 📰 News section - What's happening in the crypto world?\n- ⏸️ Pause button - Stop the robot when you want (protected by a secret PIN code!)\n- 📱 Works on your phone or computer - Check it anywhere!\n\n### 🎯 Why All These Features?\n\nIt's like having a super-organized assistant who:\n\n- Never sleeps 😴\n- Watches 10 different things at once 👀\n- Remembers every detail 🧠\n- Learns from mistakes 📚\n- Saves you money by being clever 💰\n\n**Bottom line**: Instead of you staring at screens all day trying to figure out when to buy or sell digital coins, this smart robot does it for you - and it's always learning to get better! 🚀\n\n---\n\n## It's Like a Point-Scoring Game! 🎯\n\nImagine you're trying to decide whether to buy or sell something (like trading cards), but you don't want to make a bad choice. So you have a special rule: you need to collect at least 3 points before you can make a trade.\n\n### How You Get Points:\n\n**MACD Signals (±1 point each) 📈**\n- Think of this like watching how fast a race car is speeding up or slowing down\n- If the car is speeding up = +1 point (good to buy)\n- If it's slowing down = -1 point (maybe sell)\n\n**VWAP Signal (±1 point) ⚖️**\n- This is like seeing who's winning in a tug-of-war between buyers and sellers\n- If buyers are stronger = +1 point\n- If sellers are stronger = -1 point\n\n**EMA Signals (Different point values) 📊**\n- These are like looking at different time periods to see which way things are moving:\n  - Short-term trend (9 days): ±1 point\n  - Medium-term crossover (9 vs 21 days): ±2 points\n  - Longer trends (50 and 200 days): ±1 point each\n  - Big trend change: ±3 points (this is like a really important signal!)\n\n**RSI Signal (±1 point) 🌡️**\n- This is like a thermometer that tells you if something is \"too hot\" (expensive) or \"too cold\" (cheap)\n- If it's too expensive = -1 point\n- If it's too cheap = +1 point\n\n### The Rule:\nYou can only make a trade when you collect at least 3 points in the same direction. It's like needing enough friends to agree with you before making a big decision!\n\nThis way, you don't make trades based on just one signal - you wait until multiple \"friends\" (indicators) agree with you first! 🤝\n\n---\n\nA sophisticated trading bot that uses multi-indicator strategy (MACD, VWAP, EMAs, RSI) enhanced with Reinforcement Learning (RL) to generate intelligent trading signals for Binance Futures markets with advanced position management and PnL-based decision making.\n\n## 🎉 Latest Updates (October 2025)\n\n### Enhanced Dashboard UI \u0026 Performance\n- **Modern Gradient Themes**: All dashboard sections now feature beautiful gradient color schemes with improved visual hierarchy\n- **API Rate Limit Protection**: Cross-asset correlation caching increased from 5 minutes to 4 hours (8x reduction in API calls)\n- **Reliable Market Data**: Smart fallback system ensures Market Context displays properly even during API rate limits\n- **Enhanced Error Handling**: Proper HTTP 429 handling for CoinGecko API with automatic cache fallback\n- **Professional Styling**: Enhanced CSS with section-specific themes:\n  - Chart Analysis (blue/purple), Market Context (green/teal), Signal Aggregation (indigo/purple)\n  - CrewAI Agents (orange/red), HyperDash Monitoring (cyan/blue), Spike Detections (red/pink)\n  - AI Logs (light theme), RL Status (purple/indigo), Performance Metrics (emerald/teal)\n\n## 🚨 IMPORTANT SAFETY WARNINGS\n\n- **Start with Testnet**: Always test thoroughly on testnet first\n- **Use Small Risk %**: Start with 1-2% risk per trade maximum\n- **Monitor Closely**: Never leave the bot completely unattended\n- **Set Stop Losses**: Consider manual stop losses for major positions\n- **Check Market Hours**: Crypto markets are 24/7, plan accordingly\n\n## Features\n\n### 🚀 Core Trading Features\n- **Multi-Indicator Strategy**: MACD + VWAP + EMAs (9,21,50,200) + RSI\n- **Advanced Position Management**: Cross margin with position percentage slider  \n- **Weighted Signal System**: Minimum signal strength of 3 required for execution\n- **Real-time Monitoring**: Live PnL, liquidation prices, and position tracking\n- **Enhanced Logging**: Emoji-rich console output with detailed market analysis\n\n### 🧠 Advanced AI Enhancement Features\n- **Cross-Asset Correlation Analysis**: Enhanced market awareness using BTC/ETH trends and market context\n  - **Optimized API Usage**: 4-hour caching system (8x reduction in API calls) to prevent rate limiting\n  - **Robust Error Handling**: Automatic fallback to cached data during API rate limits (HTTP 429)\n  - **Smart Cache Management**: Persistent cache across service restarts for reliable data availability\n- **Reinforcement Learning Integration**: Q-Learning agent with enhanced state representation\n- **Market Context Intelligence**:\n  - BTC dominance analysis and correlation patterns\n  - Fear \u0026 Greed Index integration for market sentiment\n  - Volatility regime detection (high/medium/low)\n  - Market trend classification (bullish/bearish/neutral)\n- **Smart Position Management**: PnL-based decision making with cross-asset confirmation\n- **Enhanced Risk Management**:\n  - Only closes positions on HOLD signals if PnL is negative (keeps profitable positions)\n  - Cross-asset momentum confirmation before position changes\n  - Market regime-based risk adjustment\n  - BTC correlation-based position sizing\n- **Database-Driven Learning**: SQLite database with market context storage and correlation analysis\n- **Cost-Optimized AI**: Local sentiment analysis alternative to reduce OpenAI costs by 95%\n\n### 📊 Chart Analysis Bot (NEW!)\n- **AI-Powered Chart Analysis**: OpenAI GPT-4o analyzes professional candlestick charts\n- **Real-time SUI/USDC Analysis**: 15-minute interval data with 24-hour history\n- **Automated Analysis Cycle**: Runs every 15 minutes for continuous market insights\n- **Technical Indicators**: EMA 9/21, SMA 50, RSI, MACD, Bollinger Bands, Volume analysis\n- **Professional Charts**: High-quality mplfinance candlestick charts with technical overlays\n- **Trading Recommendations**: BUY/SELL/HOLD signals with confidence levels and reasoning\n- **Risk Assessment**: Key observations and risk factors for informed decision-making\n\n### 🌐 Enhanced Web Dashboard\n- **Real-time Dashboard**: \"CryptoCurrency AI Trading Bot Dashboard (Experimental)\" at http://your-ip:5000\n- **🎨 Modern UI Design**: Beautifully styled sections with gradient themes and enhanced visual hierarchy\n  - **Chart Analysis**: Blue/purple gradient theme with professional candlestick charts\n  - **Market Context**: Green/teal gradient theme for cross-asset correlation data\n  - **Unified Signal Aggregation**: Indigo/purple gradient with multi-layer signal display\n  - **CrewAI Multi-Agent System**: Orange/red gradient for AI agent insights\n  - **HyperDash Trader Monitoring**: Cyan/blue gradient for agent performance tracking\n  - **Spike Detections**: Red/pink gradient for critical market events\n  - **AI Agent Logs**: Light theme with enhanced readability and black text\n  - **RL Bot Status**: Purple/indigo gradient for reinforcement learning metrics\n  - **Performance Metrics**: Emerald/teal gradient for trading statistics\n- **🌍 Market Context Section**: Real-time cross-asset correlation display\n  - Live BTC/ETH prices with 24h changes and color-coded indicators\n  - BTC Dominance percentage tracking\n  - Fear \u0026 Greed Index with color-coded sentiment levels\n  - Market trend indicators (Bullish/Bearish/Neutral)\n  - Cross-asset signal states (BTC Trend, Market Regime, Breadth)\n  - **4-hour API caching** to prevent rate limiting and ensure reliable data display\n- **Chart Visualization**: Live SUI/USDC chart display with analysis results\n- **Mobile Responsive**: Optimized for desktop, tablet, and mobile devices\n- **Live Analysis Display**: OpenAI recommendations, confidence levels, and market insights\n- **Performance Metrics**: PnL tracking, win rates, trade history, and system statistics\n- **Bot Control**: PIN-protected pause/resume functionality for secure remote control\n- **Live Log Streaming**: Real-time logs from all bots (RL, Trading, Chart Analysis)\n- **Multi-Bot Monitoring**: Unified view of all system components and their status\n- **📰 Smart Market News**: Enhanced cryptocurrency news with cost-optimized AI sentiment analysis\n  - Paginated news display (10 articles per page)\n  - Dual-mode sentiment analysis: OpenAI GPT-4o-mini OR local keyword-based (FREE)\n  - Aggressive caching system (1h-24h) to reduce API costs by 90%\n  - Real-time market sentiment indicators with confidence levels\n  - Bearish/Bullish sentiment badges in news header\n\n### 📊 Enhanced Database \u0026 Analytics\n- **SQLite Database**: Stores signals, trades, market data, performance metrics, and cross-asset correlation data\n- **Market Context Storage**: NEW! Dedicated table for BTC/ETH data, Fear \u0026 Greed Index, market trends\n- **Cross-Asset Correlation Analysis**: Historical correlation patterns and regime detection\n- **Performance Tracking**: Win rate, PnL analysis, trade history with market context correlation\n- **Data-Driven Decisions**: Enhanced RL model learns from actual trading outcomes plus market context\n- **Chart Analysis Storage**: AI recommendations and market analysis history\n- **Cost Optimization Analytics**: Track API usage and cost savings from local vs OpenAI sentiment analysis\n\n## Installation\n\n1. **Clone or download this repository**\n\n2. **Install Python dependencies:**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n3. **Install TA-Lib (if needed - bot now uses pandas-based indicators):**\n\n   **Windows:**\n   ```bash\n   # Download TA-Lib wheel from: https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib\n   pip install TA_Lib‑0.4.28‑cp311‑cp311‑win_amd64.whl\n   ```\n\n   **macOS:**\n   ```bash\n   brew install ta-lib\n   pip install ta-lib\n   ```\n\n   **Linux:**\n   ```bash\n   sudo apt-get install build-essential\n   wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz\n   tar -xzf ta-lib-0.4.0-src.tar.gz\n   cd ta-lib/\n   ./configure --prefix=/usr\n   make\n   sudo make install\n   pip install ta-lib\n   ```\n\n## Docker Installation (Recommended)\n\nFor easier deployment and management, you can use Docker to run the entire trading system in containers.\n\n### Prerequisites\n- Docker (version 20.10+)\n- Docker Compose (version 2.0+)\n\n### Quick Start with Docker\n\n1. **Clone the repository:**\n   ```bash\n   git clone \u003cyour-repo-url\u003e\n   cd 7monthIndicator\n   ```\n\n2. **Create your .env file:**\n   ```bash\n   cp .env.example .env\n   ```\n\n3. **Configure your API credentials in .env:**\n   Edit the `.env` file and add your:\n   - Binance API keys\n   - OpenAI API key\n   - NewsAPI key\n   - Bot control PIN\n\n4. **Start all services with Docker:**\n   ```bash\n   ./docker-restart.sh\n   ```\n\n   Or manually:\n   ```bash\n   docker-compose up -d --build\n   ```\n\n### Docker Services\n\nThe docker-compose setup creates three containerized services mirroring the `scripts/restart_both.sh` script:\n\n1. **rl-bot**: RL Trading Bot (rl_bot_ready.py)\n2. **chart-bot**: Chart Analysis Bot (chart_analysis_bot.py)\n3. **web-dashboard**: Web Dashboard (web_dashboard.py)\n\n### Docker Management Commands\n\n```bash\n# Start all services\n./docker-restart.sh\n# or\ndocker-compose up -d\n\n# Stop all services\ndocker-compose down\n\n# View logs (all services)\ndocker-compose logs -f\n\n# View logs (specific service)\ndocker-compose logs -f rl-bot\ndocker-compose logs -f chart-bot\ndocker-compose logs -f web-dashboard\n\n# Check service status\ndocker-compose ps\n\n# Restart a specific service\ndocker-compose restart rl-bot\n\n# View resource usage\ndocker stats\n```\n\n### Data Persistence\n\nThe following directories and files are mounted as volumes for data persistence:\n- `./logs` - Application logs\n- `./data` - Trading data\n- `./shared` - Shared resources between services\n- `*.db` - SQLite database files\n- `*.pkl` - ML model files\n\n### Health Checks\n\nEach service includes health checks to ensure they're running properly:\n- **RL Bot**: Checks if process is running every 30s\n- **Chart Bot**: Checks if process is running every 30s\n- **Web Dashboard**: HTTP health check on port 5000 every 30s\n\n### Troubleshooting Docker\n\n**Service won't start:**\n```bash\n# Check logs for errors\ndocker-compose logs \u003cservice-name\u003e\n\n# Rebuild containers\ndocker-compose up -d --build --force-recreate\n```\n\n**Permission issues:**\n```bash\n# Fix ownership of mounted volumes\nsudo chown -R $USER:$USER logs/ data/ shared/\n```\n\n**Out of disk space:**\n```bash\n# Clean up unused Docker resources\ndocker system prune -a\n```\n\n## Configuration\n\n1. **Create your .env file:**\n   ```bash\n   cp .env.example .env\n   ```\n\n2. **Add your API credentials to .env:**\n   ```\n   BINANCE_API_KEY=your_binance_api_key_here\n   BINANCE_SECRET_KEY=your_binance_secret_key_here\n   OPENAI_API_KEY=your_openai_api_key_here\n   BOT_CONTROL_PIN=your_6_digit_pin_here\n   NEWS_API_KEY=your_newsapi_key_here\n   USE_LOCAL_SENTIMENT=true  # Enable cost-saving mode (optional)\n   ```\n\n3. **Get Required API Keys:**\n\n   **Binance API Keys:**\n   - Go to [Binance API Management](https://www.binance.com/en/my/settings/api-management)\n   - Create a new API key\n   - Enable \"Enable Futures\" permission\n   - Restrict API access to your IP address (recommended)\n   - **Never share your secret key!**\n\n   **OpenAI API Key:**\n   - Go to [OpenAI API Keys](https://platform.openai.com/api-keys)\n   - Create a new API key for GPT-4 access\n   - Required for chart analysis and market sentiment analysis\n   - **Keep your API key secure!**\n\n   **NewsAPI Key:**\n   - Go to [NewsAPI](https://newsapi.org/)\n   - Sign up for a free account to get your API key\n   - Required for cryptocurrency market news and sentiment analysis\n   - Free tier includes 1000 requests per day\n\n## 💰 Cost Optimization Features\n\n### **AI Sentiment Analysis Cost Reduction**\nThe system now includes advanced cost optimization to reduce OpenAI API expenses by up to **95%**:\n\n#### **Dual-Mode Sentiment Analysis**\n- **Premium Mode**: OpenAI GPT-4o-mini (60x cheaper than GPT-4)\n- **Cost-Saving Mode**: Local keyword-based analysis (100% FREE)\n\n#### **Smart Caching System**\n- **1-hour caching**: Premium mode with minimal API calls\n- **24-hour caching**: Cost-saving mode for maximum savings\n- **File-based caching**: Persistent across restarts\n\n#### **Cost Configuration**\n```bash\n# Switch to cost-saving mode (FREE sentiment analysis)\npython3 configure_costs.py cost-saving\n\n# Switch to premium mode (GPT-4o-mini sentiment analysis)\npython3 configure_costs.py premium\n\n# Check current cost settings\npython3 configure_costs.py status\n```\n\n#### **OpenAI API Pricing (2025)**\n\n**Input Costs:**\n- **GPT-4o**: $2.50 per 1M tokens\n- **GPT-4o-mini**: $0.150 per 1M tokens (17x cheaper than GPT-4o)\n\n**Output Costs:**\n- **GPT-4o**: $10.00 per 1M tokens\n- **GPT-4o-mini**: $0.600 per 1M tokens (17x cheaper than GPT-4o)\n\n**Typical Usage per Month:**\n- **Chart Analysis**: ~50K input tokens, ~10K output tokens per day\n- **News Sentiment**: ~30K input tokens, ~5K output tokens per day (with caching)\n- **Total Monthly**: ~2.4M input tokens, ~450K output tokens\n\n#### **Monthly Cost Comparison**\n| Mode | Sentiment Analysis | Chart Analysis | Monthly Cost | Est. Tokens |\n|------|-------------------|----------------|--------------|-------------|\n| **GPT-4o** | GPT-4o | GPT-4o | $10-15/month | 2.4M in + 450K out |\n| **Premium (Mixed)** | GPT-4o-mini | GPT-4o | $5-8/month | Sentiment: GPT-4o-mini, Charts: GPT-4o |\n| **Cost-Saving** | Local keywords | GPT-4o | $3-5/month | Chart analysis only |\n| **Ultra-Saving** | Local keywords | Disabled | $0/month | No AI calls |\n\n**Cost Breakdown (Premium Mode):**\n- Chart Analysis (GPT-4o): ~$3.75/month (1.5M in + 300K out)\n- News Sentiment (GPT-4o-mini): ~$0.40/month (900K in + 150K out)\n- **Total**: ~$4.15/month with aggressive caching\n\n**Savings Tips:**\n- Enable local sentiment analysis: Save ~$0.40-1.00/month\n- Increase cache duration: Reduce API calls by 50-80%\n- Disable chart analysis during low-activity periods\n- Use testnet mode for development (no real trading)\n\n### **Additional Cost Optimizations**\n- **CoinGecko API**: FREE (rate limited)\n- **Fear \u0026 Greed Index**: FREE\n- **NewsAPI**: FREE tier available (1000 requests/day)\n- **Cross-asset data**: FREE from public APIs\n- **Binance API**: FREE (rate limited)\n\n## Bot Configuration\n\nKey settings in `main()` function:\n\n```python\nSYMBOL = 'SUIUSDC'         # Trading pair (as shown in screenshot)\nLEVERAGE = 50              # Cross 50x leverage (as shown in screenshot)  \nPOSITION_PERCENT = 51.0    # Percentage of balance to use per trade (like screenshot slider)\nRISK_PERCENT = 2.0         # Risk management percentage for stop loss\nINTERVAL = 300             # Check interval in seconds (5 minutes)\n```\n\n### Testnet Mode\n\nFor testing, change this line in `__init__`:\n```python\nself.client = Client(api_key, secret_key, testnet=True)  # Enable testnet\n```\n\n### Position Management\n- **Cross Margin**: Uses CROSS margin type with configurable leverage\n- **Position Slider**: Mimics the percentage slider (51% of available balance)\n- **Auto Position Sizing**: Calculates position size based on balance and leverage\n\n## Signal Strength System\n\nThe bot uses an advanced weighted scoring system:\n\n- **Minimum Signal Strength**: 3 (required to execute trades)\n- **Signal Weights**:\n  - **MACD Signals**: ±1 point each\n    - MACD line crossovers (bullish/bearish)\n    - Histogram momentum expansion\n  - **VWAP Signals**: ±1 point (bulls vs bears control)\n  - **EMA Signals**: Multiple weightings\n    - Price vs 9 EMA: ±1 point (short-term trend)\n    - 9/21 EMA crossover: ±2 points (momentum shift)\n    - Price vs 50 EMA: ±1 point (trend confirmation) \n    - Price vs 200 EMA: ±1 point (market direction)\n    - Golden/Death Cross: ±3 points (major trend change)\n  - **RSI Signals**: ±1 point (overbought/oversold conditions)\n\n## Running the Bot\n\n### Standard Bot\n1. **Start the bot:**\n   ```bash\n   python trading_bot.py\n   ```\n\n### RL-Enhanced Bot with Full System (Recommended)\n1. **Start all bots (RL, Web Dashboard, Chart Analysis):**\n   ```bash\n   ./restart_both.sh\n   ```\n\n### 🔄 Multi-Claude Code Development Setup\nFor parallel development on different services using multiple Claude Code instances:\n\n1. **Setup modular services (one-time setup):**\n   ```bash\n   ./scripts/setup_worktrees.sh   # Initialize git worktrees\n   ./scripts/restart_all.sh       # Start all 4 services\n   ```\n\n2. **Launch 4 Claude Code instances:**\n   ```bash\n   # Terminal 1: claude code /root/7monthIndicator/services/trading\n   # Terminal 2: claude code /root/7monthIndicator/services/web-dashboard  \n   # Terminal 3: claude code /root/7monthIndicator/services/chart-analysis\n   # Terminal 4: claude code /root/7monthIndicator/services/mcp-server\n   ```\n\n3. **Service assignments:**\n   - **Instance 1** (Trading): RL algorithms, trading logic, position management\n   - **Instance 2** (Web Dashboard): UI/UX, Flask routes, mobile responsiveness\n   - **Instance 3** (Chart Analysis): AI analysis, chart generation, visualization\n   - **Instance 4** (MCP Server): Database APIs, query optimization, data management\n\n2. **Individual bot commands:**\n   ```bash\n   # RL Bot\n   ./start_rl_bot.sh start     # Start RL trading bot\n   ./start_rl_bot.sh status    # Check bot status and positions\n   ./start_rl_bot.sh logs      # View live logs  \n   ./start_rl_bot.sh stop      # Stop the bot\n   ./start_rl_bot.sh restart   # Restart the bot\n\n   # Chart Analysis Bot  \n   ./start_chart_bot.sh start    # Start chart analysis bot\n   ./start_chart_bot.sh status   # Check chart bot status\n   ./start_chart_bot.sh stop     # Stop chart bot\n   ./start_chart_bot.sh restart  # Restart chart bot\n\n   # Web Dashboard\n   ./start_web_dashboard.sh start    # Start web dashboard\n   ./start_web_dashboard.sh stop     # Stop web dashboard\n   ./start_web_dashboard.sh restart  # Restart web dashboard\n   ```\n\n3. **Access Web Dashboard:**\n   - **Local**: http://localhost:5000\n   - **Remote**: http://your-server-ip:5000\n   - Features live charts, AI analysis, bot control, and monitoring\n\n4. **Monitor logs:**\n   - Console output shows real-time analysis with RL decisions\n   - `logs/rl_bot_main.log` - RL bot history\n   - `trading_bot.log` - Standard bot history  \n   - `chart_analysis_bot.log` - Chart analysis and OpenAI results\n   - `web_dashboard.log` - Web server logs\n   - **Web Interface**: Access logs via dashboard at /logs\n\n## Sample Output\n\n```\n2024-01-15 10:30:15 - INFO - 🚀 Starting Binance Futures Bot for SUIUSDC\n2024-01-15 10:30:15 - INFO - ⚡ Mode: CROSS 50x | Position Size: 51%\n2024-01-15 10:30:15 - INFO - 🎯 Risk Management: 2% | Strategy: MACD + VWAP + EMAs + RSI\n2024-01-15 10:30:20 - INFO - 💲 SUIUSDC: $4.2150 | RSI: 65.2 (⚖️ Neutral)\n2024-01-15 10:30:20 - INFO - 📈 VWAP: $4.1980 (🔵 Bulls) | Signal: 1 | Strength: 4\n2024-01-15 10:30:20 - INFO - 🔍 Analysis: MACD bullish crossover, Price above VWAP, 9 EMA crossed above 21 EMA\n2024-01-15 10:30:25 - INFO - 🚀 Strong signal detected! Executing trade...\n2024-01-15 10:30:25 - INFO - ✅ BUY Order Executed: 2400.5 SUIUSDC\n2024-01-15 10:30:25 - INFO - 📊 Entry Price: $4.2150\n2024-01-15 10:30:25 - INFO - ⚠️ Liquidation Price: $4.1200\n```\n\n## 🤖 RL Model Retraining\n\nThe bot includes an advanced RL model retraining system that learns from your actual trading data to improve decision-making over time.\n\n### 🔧 How It Works\n\n1. **Data Collection**: The bot continuously stores signals, trades, and outcomes in a SQLite database\n2. **Outcome Analysis**: Real trade results are categorized (good_profit, small_profit, small_loss, bad_loss)\n3. **Enhanced Reward System**: The RL agent learns with rewards/penalties based on actual P\u0026L\n4. **Continuous Learning**: Model improves its decision-making based on historical patterns\n\n### 📊 Retraining Process\n\n#### Automatic Backup\nBefore retraining, your current model is automatically backed up:\n```bash\n# Backup is created with timestamp\nrl_trading_model_backup_YYYYMMDD_HHMMSS.pkl\n```\n\n#### Manual Retraining\nTo retrain your RL model with fresh data:\n\n```bash\n# Activate virtual environment\nsource venv/bin/activate\n\n# Run retraining (requires sufficient data)\npython3 retrain_rl_model.py\n```\n\n#### What Happens During Retraining:\n1. **Data Preparation**: Loads signals and trade outcomes from database (last 30 days)\n2. **Enhanced Learning**: Uses improved reward system:\n   - **Big rewards** for profitable trades (\u003e2% profit)\n   - **Heavy penalties** for large losses (\u003e2% loss)\n   - **Streak bonuses/penalties** for consecutive wins/losses\n   - **Smart HOLD rewards** for avoiding bad trades\n3. **Training Episodes**: Runs 150 training episodes with real market scenarios\n4. **Model Updates**: Saves improved model with enhanced decision-making\n5. **Backup Creation**: Creates episodic backups every 50 episodes\n\n### 📈 Retraining Requirements\n\n- **Minimum Data**: 50+ signals with indicators (usually 1-2 hours of bot runtime)\n- **Optimal Data**: 2000+ signals with trade outcomes (24-48 hours of runtime)\n- **Best Results**: 30+ days of trading data with varied market conditions\n\n### 🎯 Enhanced Logic After Retraining\n\nThe retrained model implements intelligent position management:\n\n#### HOLD Signal Logic\n```\nCurrent Position: LONG +$50 PnL → HOLD Signal\nResult: ✅ Position kept open (positive PnL)\nLog: \"HOLD signal detected - keeping LONG position open (positive PnL: $50.00)\"\n\nCurrent Position: LONG -$30 PnL → HOLD Signal  \nResult: ❌ Position closed (negative PnL)\nLog: \"HOLD signal detected - closing LONG position (negative PnL: $-30.00)\"\n```\n\n#### Signal Flip Logic\n```\nCurrent Position: LONG +$50 PnL → SELL Signal\nResult: ✅ Keep LONG position (profitable)\nLog: \"SELL signal detected with open LONG position - keeping position open (positive PnL: $50.00)\"\n\nCurrent Position: LONG -$30 PnL → SELL Signal\nResult: ❌ Close LONG, Open SHORT (cutting losses)\nLog: \"SELL signal detected with open LONG position - closing due to negative PnL: $-30.00\"\nLog: \"📈 Executing new trade after closing opposite position based on SELL signal...\"\n```\n\n### 📋 Retraining Results Analysis\n\nAfter retraining, the system provides detailed analysis:\n\n```\n🎉 Retraining complete! Best performance: 0.2%\n📊 Recent Performance (last 50 episodes):\n   Average win rate: 49.1%\n   Average return: -0.0%\n   Average trades per episode: 34.4\n   Total states learned: 13\n   Total episodes: 155\n📈 Learning Progress:\n   Early episodes avg return: 0.0%\n   Recent episodes avg return: -0.0%\n   Improvement: -0.0%\n```\n\n### 🔄 When to Retrain\n\n- **After significant market changes** (new volatility patterns)\n- **Weekly/bi-weekly** for optimal performance\n- **After 100+ closed trades** for maximum learning benefit\n- **When win rate drops** below acceptable levels\n\n### 💾 Model Files\n\n- `rl_trading_model.pkl` - Current active model\n- `rl_trading_model_backup_*.pkl` - Timestamped backups\n- `rl_trading_model_episode_*.pkl` - Training checkpoint backups\n\n### 🧪 Testing Retrained Models\n\nAfter retraining, test the model's recommendations:\n```bash\npython3 -c \"\nfrom lightweight_rl import LightweightRLSystem\nrl = LightweightRLSystem()\nrecommendation = rl.get_trading_recommendation({\n    'rsi': 45, 'macd': -0.01, 'price': 3.68,\n    'vwap': 3.70, 'ema_9': 3.65, 'ema_21': 3.67\n})\nprint(f'Action: {recommendation[\\\"action\\\"]}, Confidence: {recommendation[\\\"confidence\\\"]:.1%}')\n\"\n```\n\n## Customization Options\n\n### Indicator Parameters\nModify in `TechnicalIndicators` class:\n- EMA periods (default: 9, 21, 50, 200)\n- MACD settings (default: 12, 26, 9) \n- RSI period (default: 14)\n- VWAP calculation methods\n\n### Signal Logic\nModify in `generate_signals()`:\n- Signal strengths and weights\n- Add additional indicators as needed\n- Adjust minimum signal threshold (default: 3)\n\n### Trading Intervals\nSupported intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d\n\n### Position Management\n- **Position Percentage**: Adjust the slider percentage (default: 51%)\n- **Leverage**: Modify leverage multiplier (1-125x)\n- **Risk Percentage**: Change risk management percentage\n\n## Risk Management Features\n\n- **Position Sizing**: Based on position percentage slider and available balance\n- **Cross Margin**: Uses CROSS margin type with automatic leverage setting\n- **Opposite Position Closing**: Automatically closes conflicting positions\n- **Signal Filtering**: Only executes on strong, confirmed signals (strength ≥ 3)\n- **Real-time Monitoring**: Live PnL tracking and liquidation price alerts\n- **Safe Shutdown**: Closes all positions when bot is stopped\n\n## Troubleshooting\n\n### Common Issues:\n\n#### Trading Bot Issues\n- **API Permission Error**: Enable Futures trading in API settings\n- **Insufficient Balance**: Ensure adequate USDC balance for SUIUSDC trading\n- **Symbol Not Found**: Check symbol formatting (e.g., 'SUIUSDC')\n- **Margin Type Error**: May be already set to CROSS (this is normal)\n- **Rate Limiting**: Reduce check frequency if needed\n- **Position Size Error**: Check symbol precision and minimum order size\n\n#### RL Model Issues\n- **\"No module named 'numpy'\"**: Activate virtual environment: `source venv/bin/activate`\n- **\"Insufficient data for training\"**: Let bot run for at least 2-3 hours before retraining\n- **\"Model file not found\"**: First time setup - model will be created automatically\n- **Poor RL performance**: Need more diverse trading data; run bot through different market conditions\n- **Retraining takes too long**: Reduce episodes in `retrain_rl_model.py` (default: 150)\n\n#### Chart Analysis Bot Issues\n- **\"Missing OpenAI API key\"**: Add `OPENAI_API_KEY` to your `.env` file\n- **\"Model not found\" errors**: OpenAI deprecated older models, bot uses `gpt-4o`\n- **\"Chart generation failed\"**: Check if `mplfinance` is installed: `pip install mplfinance`\n- **\"No chart analysis data\"**: Bot runs every 15 minutes, wait for first cycle\n- **Chart not displaying**: Check web dashboard at `/api/chart-image` endpoint\n\n#### Web Dashboard Issues\n- **Dashboard not accessible**: Check if port 5000 is open and not blocked by firewall\n- **Chart image not loading**: Verify chart analysis bot is running: `./start_chart_bot.sh status`\n- **PIN protection not working**: Ensure `BOT_CONTROL_PIN` is set in `.env` file\n- **Mobile display issues**: Dashboard is responsive, try refreshing or clearing cache\n- **Market news not showing**: Verify `NEWS_API_KEY` is set in `.env` file\n- **Sentiment analysis not working**: Check OpenAI API key and ensure sufficient credits\n- **News pagination errors**: Restart web dashboard: `./start_web_dashboard.sh restart`\n- **Market Context showing N/A values**: CoinGecko API rate limited (429 error)\n  - Wait for rate limit to reset (24 hours from first exceeding limit)\n  - System uses 4-hour caching to minimize API calls\n  - Cached data persists even after restarts\n  - Check logs: `tail -f logs/web_dashboard.log` for API status\n\n#### Database Issues  \n- **\"Database locked\"**: Stop bot before running retraining: `./start_rl_bot.sh stop`\n- **\"No signals in database\"**: Let bot run and collect data first\n- **Database corruption**: Backup and delete `trading_bot.db`, bot will recreate it\n\n### Error Logs:\n- **Standard Bot**: Check `trading_bot.log` \n- **RL Bot**: Check `logs/rl_bot_main.log` and `logs/rl_bot_error.log`\n- **Chart Analysis Bot**: Check `chart_analysis_bot.log`\n- **Web Dashboard**: Check `web_dashboard.log`\n- **Retraining**: Check `rl_retraining.log`\n- **Web Interface**: Access all logs via dashboard at `/logs`\n\n### Debugging Tips:\n- Start with testnet mode first\n- Use smaller position percentages initially (2% instead of 51%)\n- Monitor liquidation prices closely\n- Check Binance API status if experiencing connection issues\n- For RL issues, check if database contains enough data: `ls -la *.db`\n- Monitor all bot statuses: \n  - `./start_rl_bot.sh status`\n  - `./start_chart_bot.sh status`  \n  - `./start_web_dashboard.sh status`\n- Access web dashboard for real-time monitoring and chart analysis\n\n### RL Model Recovery:\nIf RL model becomes corrupted:\n```bash\n# Restore from backup\ncp rl_trading_model_backup_YYYYMMDD_HHMMSS.pkl rl_trading_model.pkl\n\n# Or start fresh (will retrain automatically)\nrm rl_trading_model.pkl\n./start_rl_bot.sh restart\n```\n\n## 🚀 Complete System Overview\n\nThis trading bot system now includes three integrated components:\n\n### **1. RL-Enhanced Trading Bot**\n- Multi-indicator strategy with reinforcement learning\n- Smart position management and PnL-based decisions  \n- Continuous learning from trading outcomes\n- Automated trading with risk management\n\n### **2. Chart Analysis Bot** \n- AI-powered chart analysis using OpenAI GPT-4o\n- Professional candlestick charts with technical indicators\n- Automated analysis every 15 minutes\n- Trading recommendations with detailed reasoning\n\n### **3. Web Dashboard**\n- Real-time monitoring and control interface\n- Live chart display with AI analysis results\n- Performance metrics and bot status monitoring\n- PIN-protected remote control capabilities\n\n### **Quick Start Commands**\n```bash\n# Start everything at once\n./restart_both.sh\n\n# Individual control\n./start_rl_bot.sh start           # Start RL trading bot\n./start_chart_bot.sh start        # Start chart analysis bot  \n./start_web_dashboard.sh start    # Start web dashboard\n\n# Access dashboard\n# Local: http://localhost:5000\n# Remote: http://your-ip:5000\n```\n\n### **System Features**\n- **📊 Live Charts**: Real-time SUI/USDC charts with AI analysis\n- **🎨 Modern UI**: Beautifully designed dashboard with gradient themes and enhanced visual hierarchy\n- **🤖 Multi-Bot Management**: Unified control of all components\n- **📱 Mobile Responsive**: Works on all devices\n- **🔒 Secure Access**: PIN-protected controls\n- **📝 Live Logging**: Real-time log streaming from all bots\n- **⏰ Automated Analysis**: Chart analysis every 15 minutes\n- **🧠 AI Integration**: OpenAI GPT-4o powered recommendations\n- **📰 Smart News**: Paginated cryptocurrency news with AI sentiment analysis\n- **📈 Market Sentiment**: Real-time bullish/bearish indicators with confidence ratings\n- **🌍 Cross-Asset Intelligence**: BTC/ETH correlation analysis with optimized 4-hour caching\n- **⚡ Rate Limit Protection**: Smart caching system prevents API rate limiting issues\n\n## 🚀 **Quick Reference: Multi-Claude Code Launch**\n\nReady to develop with multiple Claude Code instances? Here's your quick launch guide:\n\n```bash\n# Launch 4 Claude Code instances for parallel development:\n# Terminal 1: claude code /root/7monthIndicator/services/trading\n# Terminal 2: claude code /root/7monthIndicator/services/web-dashboard  \n# Terminal 3: claude code /root/7monthIndicator/services/chart-analysis\n# Terminal 4: claude code /root/7monthIndicator/services/mcp-server\n\n# Master control:\n./scripts/restart_all.sh                 # Control all services\n./scripts/setup_worktrees.sh             # Initialize git worktrees (one-time)\n./scripts/validate_migration.sh          # Validate system integrity\n\n# Access points:\n# Web Dashboard: http://localhost:5000\n# MCP Server API: http://localhost:3000\n```\n\n**Each Claude Code instance works on its own service branch with isolated development, independent testing, and seamless integration capabilities!** 🎯\n\n## Disclaimer\n\nThis trading bot is for educational purposes only. Trading cryptocurrencies involves substantial risk and may not be suitable for all investors. Past performance is not indicative of future results. Always do your own research and consider your financial situation before trading.\n\n**Use at your own risk. The authors are not responsible for any financial losses.**","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenken64%2F7monthindicator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkenken64%2F7monthindicator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkenken64%2F7monthindicator/lists"}