# 🚀 AI-Powered Trading Bot Dashboard v3

A professional-grade Next.js trading dashboard with AI-powered chart analysis, dual-session screenshot capture, and multi-timeframe analysis. Built for institutional-quality trading insights with cost-effective OpenAI integration.

![Trading Bot Dashboard](https://img.shields.io/badge/Status-Production%20Ready-brightgreen)
![Next.js](https://img.shields.io/badge/Next.js-15-black)
![TypeScript](https://img.shields.io/badge/TypeScript-5-blue)
![Docker](https://img.shields.io/badge/Docker-Optimized-blue)
![OpenAI](https://img.shields.io/badge/OpenAI-GPT--4o%20mini-orange)

## ✨ Key Features

### 🤖 **AI-Powered Analysis**
- **Professional Trading Assistant** - Behaves like a top proprietary desk trader
- **Multi-Layout Analysis** - AI + DIY TradingView layouts for comprehensive insights
- **Cost-Effective** - Using GPT-4o mini (~$0.006 per analysis)
- **Timeframe Risk Assessment** - Automatic leverage and position sizing recommendations
- **Cross-Layout Consensus** - Compare insights from multiple chart layouts

### 📊 **Multi-Timeframe Analysis**
- **Quick Presets**: Scalping (5m,15m,1h), Day Trading (1h,4h,1d), Swing (4h,1d,1w), Position (1d,1w,1m)
- **1-8 Timeframes** simultaneously for broader market outlook
- **Consensus Detection** - Identify when multiple timeframes agree
- **Individual Analysis** - Detailed breakdown for each timeframe

### 🎯 **Professional Trading Setups**
- **Precise Entry Levels** with ±buffers and technical rationale
- **Smart Stop Losses** with exact reasoning (above VWAP, failed breakout zones)
- **Enhanced Take Profits** with RSI/OBV expectations for TP1/TP2
- **Risk/Reward Ratios** with specific R:R calculations
- **Confirmation Triggers** - Exact signals to wait for before entry

### 🤖 **Automated Trading Features**
- **Multi-Timeframe Automation** - Select 1-8 timeframes for comprehensive strategy coverage
- **Trading Style Presets** - Scalping (5m,15m,1h), Day Trading (1h,4h,1d), Swing (4h,1d)
- **Automatic Position Sizing** - Balance-based calculations with leverage recommendations
- **Real-Time Balance Integration** - Live wallet display with percentage-based position sizing
- **Risk Management** - Timeframe-specific leverage and position size recommendations
- **Clean UI/UX** - Checkbox-based timeframe selection with visual feedback

### 🖼️ **Enhanced Screenshot Service**
- **Dual-Session Capture** - Parallel AI and DIY layout screenshots
- **Docker Optimized** - Full CPU utilization for faster processing
- **Robust Error Handling** - Individual layout failures don't break analysis
- **Production Ready** - Automated browser management and session persistence

### 🎨 **Beautiful UI/UX**
- **Modern Design** - Gradient backgrounds, smooth animations, responsive layouts
- **Quick Analysis** - One-click coin + timeframe combination analysis
- **Visual Indicators** - Clear selection states, progress indicators, success/failure states
- **Professional Display** - Bloomberg terminal-style result presentation

## 🚀 Quick Start

### Option A: Docker (Recommended)

```bash
# Clone the repository
git clone <your-repo-url> trading_bot_v3
cd trading_bot_v3

# Create environment file
cp .env.example .env.local
# Add your OpenAI API key to .env.local

# Start with Docker Compose v2
docker compose up --build

# Access the dashboard
open http://localhost:3000
```

### Option B: Node.js Development

```bash
# Clone and install dependencies
git clone <your-repo-url> trading_bot_v3
cd trading_bot_v3
npm install

# Configure environment
cp .env.example .env.local
# Add your OpenAI API key

# Start development server
npm run dev

# Access the dashboard
open http://localhost:3000
```

## ⚙️ Configuration

### Required Environment Variables

```env
# OpenAI API Key (Required for AI analysis)
OPENAI_API_KEY=your_openai_api_key_here

# TradingView Credentials (Optional - for automation)
TRADINGVIEW_USERNAME=your_username
TRADINGVIEW_PASSWORD=your_password

# Layout Configuration (Optional)
NEXT_PUBLIC_TRADINGVIEW_LAYOUTS=ai,diy
```

### Docker Configuration

The system includes optimized Docker configurations:

- **`Dockerfile`** - Production-optimized build
- **`docker-compose.yml`** - Development setup
- **`docker-compose.prod.yml`** - Production deployment
- **`.dockerignore`** - Optimized build context

## 🎯 Usage Examples

### Quick Multi-Timeframe Analysis

1. **Select Trading Style Preset**:
   - 🕒 Scalping: 5m, 15m, 1h
   - 📊 Day Trading: 1h, 4h, 1d
   - 📈 Swing: 4h, 1d, 1w
   - 🎯 Position: 1d, 1w, 1m

2. **Click Any Coin** for instant analysis across all selected timeframes

3. **View Results** with consensus, divergences, and individual timeframe setups

### Multi-Timeframe Automation (/automation-v2)

1. **Access Automation**: Navigate to `/automation-v2` for the latest automation interface
2. **Select Timeframes**: Use checkboxes to select 1-8 timeframes
   - Individual selection: Click any timeframe checkbox
   - Quick presets: Scalping, Day Trading, Swing Trading buttons
3. **Position Sizing**: 
   - View real-time wallet balance
   - Select position percentage (1%, 5%, 10%, 25%, 50%)
   - Automatic leverage calculations based on timeframe
4. **Execute**: Run automation across all selected timeframes simultaneously

### Docker Development Workflow

```bash
# Start development environment
npm run docker:dev          # Runs on http://localhost:9001

# View logs for debugging
npm run docker:logs

# Access container shell for troubleshooting  
npm run docker:exec

# Test volume mount sync (if files not updating)
echo "test-$(date)" > test-volume-mount.txt
docker compose -f docker-compose.dev.yml exec app cat test-volume-mount.txt

# Full rebuild if issues persist
docker compose -f docker-compose.dev.yml down
docker compose -f docker-compose.dev.yml up --build
```

### API Usage

```bash
# Test the enhanced screenshot API
curl -X POST http://localhost:3000/api/enhanced-screenshot \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "BTCUSD",
    "timeframe": "240", 
    "layouts": ["ai", "diy"],
    "analyze": true
  }'

# Run included test script
node test-enhanced-screenshot.js
```

### Professional Trading Analysis Output

```
💰 TRADING SETUP:
   📍 Entry: $162.5 ±0.25
      💡 Rejection from 15 EMA + VWAP confluence near intraday supply

   🛑 Stop Loss: $160
      💡 Above VWAP + failed breakout zone

🎯 TAKE PROFIT TARGETS:
   🥉 TP1: $164
      📋 Target based on resistance level observed in both layouts
      📊 RSI: Should reach 60-65 zone
      📈 OBV: Confirming upward momentum

   🥈 TP2: $166
      📋 Target aligns with upper resistance in AI layout
      📊 RSI: Approaching 70+ overbought
      📈 OBV: Making new highs with price

⚖️ Risk/Reward: 1:2.5

⏰ TIMEFRAME RISK ASSESSMENT:
   📊 Risk Level: Medium (4H timeframe)
   💼 Position Size: Larger position appropriate for swing trade
   🎚️ Leverage: 3-5x recommended for 4H timeframe
```

## 🛠️ Tech Stack

- **Frontend**: Next.js 15, TypeScript, Tailwind CSS
- **AI**: OpenAI GPT-4o mini (cost-optimized)
- **Automation**: Puppeteer, Playwright
- **Database**: Prisma (optional)
- **Deployment**: Docker, Docker Compose
- **Testing**: Custom API test suites

## 📂 Project Structure

```
trading_bot_v3/
├── app/                          # Next.js app router
│   ├── analysis/                 # Multi-timeframe analysis page
│   ├── automation/               # Trading automation pages
│   │   ├── page.js              # Original automation (legacy)
│   │   └── page-v2.js           # Clean automation implementation
│   ├── automation-v2/           # NEW: Multi-timeframe automation
│   │   └── page.js              # Full automation with timeframe support
│   ├── api/enhanced-screenshot/ # Screenshot & AI analysis API
│   ├── globals.css              # Global styles
│   ├── layout.tsx               # Root layout
│   └── page.tsx                 # Main dashboard
├── components/                   # React components
│   ├── AIAnalysisPanel.tsx      # Multi-timeframe analysis UI
│   ├── Dashboard.tsx            # Main dashboard
│   └── ...                      # Other trading components
├── lib/                         # Core services
│   ├── ai-analysis.ts           # OpenAI integration
│   ├── enhanced-screenshot-simple.ts # Dual-session capture
│   ├── auto-trading.ts          # Trading automation
│   └── ...                      # Other services
├── docker-compose.yml           # Development setup
├── docker-compose.prod.yml      # Production setup
├── Dockerfile                   # Optimized container
└── test-enhanced-screenshot.js  # API testing
```

## 🧪 Testing

### Run Test Suite

```bash
# Test enhanced screenshot service
node test-enhanced-screenshot.js

# Test with curl
./test-simple-screenshot.js

# Test Docker setup
docker compose up --build

# Test automation features
curl -X POST http://localhost:9001/api/automation \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "BTCUSD",
    "timeframes": ["1h", "4h", "1d"],
    "positionSize": 10
  }'
```

### Expected Test Output

```
🚀 Testing Enhanced Screenshot Service with Dual Sessions (API)
✅ API endpoint available
🎯 SUCCESS: Both AI and DIY layouts captured successfully!
📊 Test Summary: 100% success rate

🤖 Testing Multi-Timeframe Automation
✅ Timeframe selection working
✅ Position sizing calculations correct
✅ Balance integration successful
```

## 🎯 Features in Detail

### AI Analysis Capabilities

- **Market Sentiment Analysis** - BULLISH/BEARISH/NEUTRAL with confidence scores
- **Technical Indicator Analysis** - RSI, VWAP, OBV, MACD with specific action triggers
- **Entry/Exit Strategy** - Precise levels with technical rationale
- **Risk Management** - Position sizing based on timeframe and volatility
- **Alternative Scenarios** - Backup plans and invalidation levels

### Screenshot Service Features

- **Dual-Session Architecture** - Parallel AI and DIY layout capture
- **Smart Navigation** - Automatic symbol/timeframe selection
- **Error Recovery** - Robust handling of navigation failures
- **Performance Optimized** - Full CPU utilization, optimized for i7-4790K
- **Session Persistence** - Avoid repeated logins and captchas

### Multi-Timeframe Analysis

- **Cross-Timeframe Consensus** - Identify alignment across timeframes
- **Divergence Detection** - Spot conflicts between timeframes
- **Risk-Adjusted Positioning** - Different strategies for different timeframes
- **Comprehensive Outlook** - From scalping to position trading

## 📊 Performance & Costs

- **Analysis Speed**: ~30-60 seconds for dual-layout capture + AI analysis
- **AI Cost**: ~$0.006 per analysis (GPT-4o mini)
- **Screenshot Performance**: Optimized for multi-core CPUs
- **Memory Efficient**: Docker optimizations for production deployment

## 🔒 Security & Best Practices

- **Environment Variables** - Secure API key management
- **Input Validation** - Sanitized user inputs
- **Error Handling** - Graceful degradation
- **Rate Limiting** - Built-in delays between requests
- **Production Ready** - Docker security best practices

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Commit changes: `git commit -m 'Add amazing feature'`
4. Push to branch: `git push origin feature/amazing-feature`
5. Open a Pull Request

## � Technical Analysis Documentation

This project includes comprehensive Technical Analysis (TA) documentation:

- **`TECHNICAL_ANALYSIS_BASICS.md`** - Complete guide to all indicators used
- **`TA_QUICK_REFERENCE.md`** - Quick reference for indicator interpretation
- **AI Analysis Integration** - TA fundamentals built into AI analysis prompts

### Indicators Covered:
- **RSI & Stochastic RSI** - Momentum oscillators
- **MACD** - Trend and momentum indicator
- **EMAs** - Exponential Moving Averages (9, 20, 50, 200)
- **VWAP** - Volume Weighted Average Price
- **OBV** - On-Balance Volume
- **Smart Money Concepts** - Institutional flow analysis

The AI analysis system uses established TA principles to provide accurate, educational trading insights based on proven technical analysis methodologies.

## �📜 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- OpenAI for providing cost-effective GPT-4o mini API
- TradingView for comprehensive charting platform
- Next.js team for excellent React framework
- Docker for containerization capabilities

## 📞 Support

For support, please open an issue in the GitHub repository or contact the development team.

---

**Built with ❤️ for professional traders who demand institutional-quality analysis at startup costs.**

🚀 **Ready to deploy and start trading with AI-powered insights!**
