Răsfoiți Sursa

Reorganize documentation - Create clean docs/ structure, remove overlap, update references to current project state

Carles Sentis 6 zile în urmă
părinte
comite
238c0531ce
8 a modificat fișierele cu 602 adăugiri și 883 ștergeri
  1. 0 338
      DEPLOYMENT_GUIDE.md
  2. 0 188
      PROJECT_STRUCTURE.md
  3. 0 141
      QUICK_START.md
  4. 6 27
      README.md
  5. 0 189
      SETUP_GUIDE.md
  6. 296 0
      docs/deployment.md
  7. 189 0
      docs/project-structure.md
  8. 111 0
      docs/setup.md

+ 0 - 338
DEPLOYMENT_GUIDE.md

@@ -1,338 +0,0 @@
-# 🚀 Deployment Guide - How to Run Your Trading Bot
-
-This guide explains the different ways to run your Hyperliquid trading bot and best practices for each approach.
-
-## 📋 Overview
-
-You have **three different bot types**:
-
-| Bot Type | File | Purpose | Running Time |
-|----------|------|---------|--------------|
-| **Telegram Bot** | `telegram_bot.py` | Remote control interface | Continuous |
-| **Strategy Bot** | `strategy_bot.py` | Automated trading strategies | Continuous |
-| **Terminal Bot** | `simple_bot.py` | Interactive terminal interface | On-demand |
-
-## 🎯 **Different Use Cases**
-
-### **Use Case 1: Manual Trading with Remote Control**
-**Goal**: Monitor and control manually via Telegram
-```bash
-# Run only the Telegram bot
-source venv/bin/activate
-python telegram_bot.py
-```
-- ✅ Control via Telegram from anywhere
-- ✅ Manual decision making
-- ✅ Safe for beginners
-
-### **Use Case 2: Automated Trading**
-**Goal**: Fully automated trading with monitoring
-```bash
-# Terminal 1: Run strategy bot
-source venv/bin/activate
-python strategy_bot.py
-
-# Terminal 2: Run Telegram bot for monitoring
-source venv/bin/activate
-python telegram_bot.py
-```
-- ✅ Automated trading strategies
-- ✅ Remote monitoring via Telegram
-- ✅ Professional setup
-
-### **Use Case 3: Development and Testing**
-**Goal**: Test strategies and debug
-```bash
-# Use terminal bot for quick testing
-source venv/bin/activate
-python simple_bot.py
-```
-- ✅ Interactive testing
-- ✅ Quick market data checks
-- ✅ Debug configuration
-
-## 🔄 **Long-Running vs. Cron Jobs**
-
-### ❌ **DON'T Use Cron Jobs For:**
-- Telegram bot (needs to stay connected)
-- Strategy bot (needs continuous monitoring)
-- Any interactive functionality
-
-### ✅ **DO Use Long-Running Processes:**
-```bash
-# These run forever until you stop them
-python telegram_bot.py     # Listens for Telegram commands 24/7
-python strategy_bot.py     # Executes strategies every 60 seconds
-```
-
-### ✅ **Optional: Use Cron for Maintenance:**
-```bash
-# Example: Daily log rotation (optional)
-0 0 * * * /path/to/your/log_rotation_script.sh
-```
-
-## 🖥️ **Production Deployment Options**
-
-### **Option 1: Screen/Tmux Sessions**
-```bash
-# Start a screen session
-screen -S trading_bot
-
-# Run your bot
-source venv/bin/activate
-python telegram_bot.py
-
-# Detach: Ctrl+A, then D
-# Reattach: screen -r trading_bot
-```
-
-### **Option 2: Systemd Service (Linux)**
-Create `/etc/systemd/system/trading-bot.service`:
-```ini
-[Unit]
-Description=Hyperliquid Trading Bot
-After=network.target
-
-[Service]
-Type=simple
-User=your_username
-WorkingDirectory=/path/to/trader_hyperliquid
-Environment=PATH=/path/to/trader_hyperliquid/venv/bin
-ExecStart=/path/to/trader_hyperliquid/venv/bin/python telegram_bot.py
-Restart=always
-RestartSec=10
-
-[Install]
-WantedBy=multi-user.target
-```
-
-```bash
-sudo systemctl enable trading-bot
-sudo systemctl start trading-bot
-sudo systemctl status trading-bot
-```
-
-### **Option 3: Docker (Advanced)**
-```dockerfile
-FROM python:3.11-slim
-
-WORKDIR /app
-COPY requirements.txt .
-RUN pip install -r requirements.txt
-
-COPY . .
-CMD ["python", "telegram_bot.py"]
-```
-
-### **Option 4: Process Manager (PM2)**
-```bash
-npm install -g pm2
-pm2 start telegram_bot.py --interpreter python3
-pm2 startup
-pm2 save
-```
-
-## 📊 **Recommended Deployment Strategy**
-
-### **For Beginners:**
-1. **Start with manual control:**
-   ```bash
-   python telegram_bot.py
-   ```
-2. **Test strategies separately:**
-   ```bash
-   python strategy_bot.py  # Watch logs, don't let it trade yet
-   ```
-
-### **For Production:**
-1. **Run both bots in separate processes:**
-   ```bash
-   # Terminal 1 (or systemd service)
-   python telegram_bot.py
-   
-   # Terminal 2 (or systemd service)  
-   python strategy_bot.py
-   ```
-
-2. **Use process monitoring:**
-   ```bash
-   # Check if bots are running
-   ps aux | grep python
-   
-   # Check logs
-   tail -f ~/.local/share/hyperliquid-bot/logs/
-   ```
-
-## 🔧 **Bot Intervals and Timing**
-
-### **Strategy Bot Timing:**
-```python
-# In strategy_bot.py
-self.loop_interval = 60  # Run every 60 seconds
-```
-
-**Why 60 seconds?**
-- ✅ Balances responsiveness with API limits
-- ✅ Prevents overtrading
-- ✅ Allows time for proper analysis
-
-**Adjust based on strategy:**
-```python
-# Scalping: More frequent (careful of API limits)
-self.loop_interval = 30  # 30 seconds
-
-# Swing trading: Less frequent
-self.loop_interval = 300  # 5 minutes
-
-# Long-term: Much less frequent
-self.loop_interval = 3600  # 1 hour
-```
-
-### **Telegram Bot:**
-- Runs continuously
-- Responds instantly to commands
-- No interval needed
-
-## 🛡️ **Safety and Monitoring**
-
-### **1. Always Start with Testnet**
-```env
-HYPERLIQUID_TESTNET=true
-```
-
-### **2. Monitor Your Bots**
-```bash
-# Check bot status via Telegram
-/status
-
-# Check logs
-tail -f logs/trading_bot.log
-
-# Check system resources
-htop
-```
-
-### **3. Set Up Alerts**
-```python
-# Add to your strategy bot
-if large_loss_detected:
-    await send_telegram_alert("⚠️ Large loss detected!")
-```
-
-### **4. Implement Circuit Breakers**
-```python
-# In your strategy
-if daily_loss > max_daily_loss:
-    logger.error("Daily loss limit reached. Stopping trading.")
-    self.trading_enabled = False
-```
-
-## 🔄 **Updating and Maintenance**
-
-### **Safe Update Process:**
-1. **Stop bots gracefully:**
-   ```bash
-   # Ctrl+C or
-   sudo systemctl stop trading-bot
-   ```
-
-2. **Backup configuration:**
-   ```bash
-   cp .env .env.backup
-   ```
-
-3. **Update code:**
-   ```bash
-   git pull  # or download new version
-   ```
-
-4. **Test in terminal:**
-   ```bash
-   python simple_bot.py
-   ```
-
-5. **Restart production bots:**
-   ```bash
-   python telegram_bot.py
-   ```
-
-## 🔍 **Troubleshooting**
-
-### **Bot Won't Start:**
-```bash
-# Check configuration
-python -c "from config import Config; Config.validate()"
-
-# Check dependencies
-pip list | grep hyperliquid
-```
-
-### **Telegram Bot Not Responding:**
-```bash
-# Test token
-curl https://api.telegram.org/bot<YOUR_TOKEN>/getMe
-
-# Check chat ID
-python get_telegram_chat_id.py
-```
-
-### **Strategy Bot Not Trading:**
-```bash
-# Check if trading is enabled in code
-grep -n "Uncomment to enable" strategy_bot.py
-
-# Check balance and positions
-python simple_bot.py
-```
-
-## 📈 **Best Practices**
-
-### **1. Resource Management**
-- Monitor CPU and memory usage
-- Implement proper logging rotation
-- Use rate limiting for API calls
-
-### **2. Security**
-- Keep private keys secure
-- Use environment variables
-- Regularly rotate API keys
-
-### **3. Monitoring**
-- Set up health checks
-- Monitor trading performance
-- Track system metrics
-
-### **4. Testing**
-- Always test on testnet first
-- Use small amounts initially
-- Monitor for several days before scaling
-
-## 🎯 **Quick Commands Reference**
-
-```bash
-# Start manual control bot
-python telegram_bot.py
-
-# Start automated trading bot
-python strategy_bot.py
-
-# Start both (recommended for production)
-python telegram_bot.py &
-python strategy_bot.py
-
-# Test configuration
-python simple_bot.py
-
-# Get Telegram Chat ID
-python get_telegram_chat_id.py
-
-# Check if running
-ps aux | grep "python.*bot"
-
-# Stop all bots
-pkill -f "python.*bot"
-```
-
----
-
-**Remember**: Start simple, test thoroughly, and scale gradually! 🚀 

+ 0 - 188
PROJECT_STRUCTURE.md

@@ -1,188 +0,0 @@
-# 📁 Project Structure
-
-## 🎯 **Single Command Launch**
-```bash
-python trading_bot.py  # THIS IS ALL YOU NEED TO RUN
-```
-
-## 📂 **Organized Folder Structure**
-
-```
-trader_hyperliquid/
-├── 🚀 trading_bot.py              # MAIN LAUNCHER (run this!)
-├── 📊 trading_stats.json          # Your persistent statistics
-├── 📝 .env                        # Your configuration (create from config/env.example)
-├── 📚 requirements.txt            # Dependencies
-├── 
-├── 📖 Documentation/
-│   ├── README.md                  # Complete guide
-│   ├── SETUP_GUIDE.md            # 5-minute setup
-│   ├── DEPLOYMENT_GUIDE.md       # Advanced deployment
-│   └── PROJECT_STRUCTURE.md      # This file
-│
-├── 🔧 src/                        # Core bot modules
-│   ├── __init__.py
-│   ├── config.py                  # Configuration management
-│   ├── hyperliquid_client.py      # Hyperliquid API wrapper
-│   ├── telegram_bot.py            # Telegram interface
-│   └── trading_stats.py           # Statistics engine
-│
-├── 🛠️ utils/                      # Utility scripts
-│   ├── get_telegram_chat_id.py   # Get your Chat ID
-│   ├── demo_stats.py             # See sample statistics
-│   ├── simple_bot.py             # Terminal interface
-│   ├── strategy_bot.py           # Automated strategies
-│   └── manual_trading_bot.py     # Old manual launcher
-│
-├── ⚙️ config/
-│   └── env.example               # Configuration template
-│
-├── 📋 logs/                       # Auto-created logs
-│   ├── trading_bot_YYYYMMDD.log  # Daily logs
-│   └── bot_errors.log            # Error log
-│
-└── 🐍 venv/                      # Python virtual environment
-```
-
-## 🎯 **What Each File Does**
-
-### **🚀 Main Files (What You Use)**
-
-| File | Purpose | When to Use |
-|------|---------|-------------|
-| `trading_bot.py` | **Main launcher** | **Always** - This is your bot |
-| `trading_stats.json` | Your trading data | Auto-created, never delete |
-| `.env` | Your configuration | Create from `config/env.example` |
-
-### **📖 Documentation**
-
-| File | Purpose |
-|------|---------|
-| `README.md` | Complete bot documentation |
-| `SETUP_GUIDE.md` | 5-minute quick setup |
-| `DEPLOYMENT_GUIDE.md` | Advanced deployment options |
-| `PROJECT_STRUCTURE.md` | This file - folder organization |
-
-### **🔧 Core Modules (`src/`)**
-
-| File | Purpose |
-|------|---------|
-| `config.py` | Loads and validates your `.env` settings |
-| `hyperliquid_client.py` | Handles all Hyperliquid API calls |
-| `telegram_bot.py` | Your phone interface and trading commands |
-| `trading_stats.py` | Calculates all your performance metrics |
-
-### **🛠️ Utilities (`utils/`)**
-
-| File | Purpose | When to Use |
-|------|---------|-------------|
-| `get_telegram_chat_id.py` | Find your Chat ID | **Setup only** |
-| `demo_stats.py` | See sample statistics | **Optional demo** |
-| `simple_bot.py` | Terminal interface | Testing/debugging |
-| `strategy_bot.py` | Automated strategies | If you want automation |
-
-### **📋 Auto-Created Files**
-
-| File/Folder | Purpose |
-|-------------|---------|
-| `logs/` | All bot logs and error tracking |
-| `trading_stats.json` | Your persistent trading statistics |
-| `demo_stats.json` | Sample data (can delete) |
-
-## 🚀 **How to Use This Structure**
-
-### **1. Initial Setup**
-```bash
-# 1. Get your Telegram Chat ID
-python utils/get_telegram_chat_id.py
-
-# 2. Configure the bot
-cp config/env.example .env
-nano .env  # Add your keys and Chat ID
-
-# 3. See what stats look like (optional)
-python utils/demo_stats.py
-```
-
-### **2. Daily Usage**
-```bash
-# Start your trading bot (ONLY command you need!)
-python trading_bot.py
-```
-
-### **3. Maintenance**
-```bash
-# Check logs
-tail -f logs/trading_bot_$(date +%Y%m%d).log
-
-# Validate configuration
-python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Config.validate()"
-```
-
-## 🛡️ **Built-in Safety Features**
-
-### **📊 Persistent Statistics**
-- ✅ **Always saved** to `trading_stats.json`
-- ✅ **Survives restarts** - your data is never lost
-- ✅ **Automatic backups** via comprehensive logging
-
-### **🔄 Auto-Restart**
-- ✅ **Up to 10 restart attempts** if bot crashes
-- ✅ **Telegram error notifications** sent to your phone
-- ✅ **Exponential backoff** prevents spam restarts
-- ✅ **Graceful shutdown** on Ctrl+C
-
-### **📝 Comprehensive Logging**
-- ✅ **Daily log files** in `logs/` folder
-- ✅ **Error tracking** with stack traces
-- ✅ **Telegram notifications** for errors
-- ✅ **Startup/shutdown** notifications
-
-### **⚙️ Configuration Validation**
-- ✅ **Checks all required settings** before starting
-- ✅ **Clear error messages** with setup instructions
-- ✅ **Network warnings** (testnet vs mainnet)
-- ✅ **Prevents accidental real trading**
-
-## 📱 **Mobile-First Design**
-
-### **Phone Control**
-- 📱 All trading via Telegram commands
-- 📊 Complete statistics on your phone
-- 🔄 Real-time balance and P&L updates
-- 📈 Professional trading metrics
-
-### **Error Notifications**
-- 🚨 Instant error alerts to your phone
-- 🔄 Restart notifications
-- 🟢 Startup confirmations
-- 📊 Status updates
-
-## 🎯 **Key Benefits of This Structure**
-
-1. **🚀 Single Command**: `python trading_bot.py` - that's it!
-2. **📊 Persistent Data**: Your stats survive forever
-3. **🛡️ Auto-Recovery**: Bot restarts itself on errors
-4. **📱 Phone Alerts**: Get notified of any issues
-5. **📝 Complete Logs**: Full audit trail of everything
-6. **⚙️ Easy Setup**: Organized configuration and setup tools
-7. **🔧 Modular**: Clean separation of concerns
-
-## 💡 **Pro Tips**
-
-### **Keep It Simple**
-- Only use `trading_bot.py` for daily trading
-- Let the bot handle all restarts and errors
-- Check Telegram for status and error notifications
-
-### **Backup Your Data**
-- Your `.env` file (contains your keys)
-- Your `trading_stats.json` file (your performance data)
-- Archive log files periodically
-
-### **Monitor Performance**
-- Use `/stats` command in Telegram regularly
-- Check daily logs for any issues
-- Monitor error notifications
-
-**This structure gives you professional-grade trading infrastructure with simple phone control! 🚀📱** 

+ 0 - 141
QUICK_START.md

@@ -1,141 +0,0 @@
-# 🚀 Quick Start - Your Questions Answered
-
-## ✅ **Stats Persistence**: YES, Forever Saved!
-Your trading statistics are **permanently saved** to `trading_stats.json` and automatically loaded every time you restart the bot. Your complete trading history, P&L, win rates, and all performance metrics survive forever between launches.
-
-## 📁 **Organized Structure**: Clean & Simple
-```
-trader_hyperliquid/
-├── 🚀 trading_bot.py              # ONE COMMAND TO RUN EVERYTHING
-├── 📊 trading_stats.json          # Your persistent data
-├── 📝 .env                        # Your config
-├── 
-├── 🔧 src/                        # Core modules (don't touch)
-├── 🛠️ utils/                      # Setup helpers
-├── ⚙️ config/                     # Configuration template
-└── 📋 logs/                       # Auto-created logs & errors
-```
-
-## 🎯 **Single Command Launch**: Super Simple
-```bash
-python trading_bot.py    # THIS IS ALL YOU NEED!
-```
-- ✅ Launches Telegram bot automatically
-- ✅ Handles all errors and restarts
-- ✅ Sends notifications to your phone
-- ✅ Manages all logging and persistence
-
-## 🛡️ **Built-in Safeguards**: Bulletproof
-- **🔄 Auto-restart**: Up to 10 attempts if crashes
-- **📱 Error notifications**: Instant alerts to your Telegram
-- **📝 Complete logging**: All errors saved to files
-- **⚙️ Graceful shutdown**: Ctrl+C stops cleanly
-- **📊 Data protection**: Stats never lost
-
-## 🚀 **Setup in 3 Minutes**
-
-### **1. Get Telegram Chat ID**
-```bash
-python utils/get_telegram_chat_id.py
-```
-
-### **2. Configure Bot**
-```bash
-cp config/env.example .env
-nano .env  # Add your keys and Chat ID
-```
-
-### **3. Start Trading!**
-```bash
-python trading_bot.py
-```
-
-## 📱 **What Happens When You Start**
-
-1. **🔍 Validates** all your configuration
-2. **📊 Loads** your existing trading statistics (if any)
-3. **🚀 Starts** Telegram bot for phone control
-4. **📱 Sends** startup notification to your phone
-5. **🛡️ Monitors** for errors and auto-restarts if needed
-6. **📝 Logs** everything to daily log files
-
-## 🆘 **Error Handling Examples**
-
-### **If Bot Crashes:**
-- 🔄 **Auto-restarts** in 5 seconds
-- 📱 **Sends error alert** to your Telegram
-- 📝 **Logs details** to `logs/bot_errors.log`
-- ⏰ **Increases delay** for repeated failures
-
-### **If Internet Disconnects:**
-- 🔄 **Keeps trying** to reconnect
-- 📱 **Notifies you** when back online
-- 📊 **Preserves** all your trading data
-
-### **If Configuration Missing:**
-- ❌ **Stops safely** before starting
-- 💡 **Shows clear instructions** for setup
-- 📝 **Tells you exactly** what's missing
-
-## 📊 **Your Trading Data is Safe**
-
-### **Persistent Between Launches:**
-- ✅ Starting balance remembered
-- ✅ All trade history preserved
-- ✅ Performance metrics calculated
-- ✅ Risk analytics maintained
-- ✅ Win/loss streaks tracked
-
-### **Automatic Backups:**
-- 📝 Every trade logged to files
-- 📊 Statistics saved after each trade
-- 🔄 Daily log files created
-- 📱 Critical events sent to phone
-
-## 🎯 **Daily Usage**
-
-### **Start Bot:**
-```bash
-python trading_bot.py
-```
-
-### **Trade via Phone:**
-- Open Telegram → Find your bot
-- Send `/start` for quick buttons
-- Use `/buy 0.001 50000` to trade
-- Check `/stats` for performance
-
-### **Monitor:**
-- Bot sends error notifications automatically
-- Check `/stats` for trading performance
-- View logs: `tail -f logs/trading_bot_$(date +%Y%m%d).log`
-
-## 🔧 **Troubleshooting**
-
-### **"Configuration validation failed"**
-```bash
-cp config/env.example .env
-nano .env  # Add your keys
-```
-
-### **"Import error"**
-```bash
-source venv/bin/activate
-pip install -r requirements.txt
-```
-
-### **"Telegram not responding"**
-```bash
-python utils/get_telegram_chat_id.py  # Get correct Chat ID
-```
-
-## 💡 **Key Benefits**
-
-1. **🚀 One Command**: `python trading_bot.py` does everything
-2. **📊 Never Lose Data**: Statistics persist forever
-3. **🛡️ Self-Healing**: Auto-restarts on errors
-4. **📱 Phone Alerts**: Know about issues instantly
-5. **📝 Complete Audit**: Full logging of everything
-6. **⚙️ Foolproof Setup**: Clear validation and instructions
-
-**Your trading bot is now professional-grade with phone control and bulletproof reliability! 🚀📱** 

+ 6 - 27
README.md

@@ -102,7 +102,7 @@ ManualTrader/
 ├── ⚙️ config/                     # Configuration templates
 ├── 📋 logs/                       # Auto-created logs & errors
-└── 📖 Documentation/
+└── 📖 docs/                       # Organized documentation
 ```
 
 ## 📱 **Mobile Trading Interface**
@@ -224,34 +224,13 @@ python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Con
 python utils/simple_chat_id.py
 ```
 
-## 🔧 **Key Features**
-
-### **Mobile-First Design**
-- 📱 **Complete phone control** via Telegram
-- 🔘 **One-tap buttons** for quick actions
-- 📊 **HTML-formatted** messages with emojis
-- 📱 **Instant notifications** for errors and updates
-
-### **Professional Analytics**
-- 📈 **Institutional-grade metrics** (Sharpe, Sortino, VaR)
-- 💰 **FIFO P&L calculation** for accurate tracking
-- 📊 **Real-time balance** monitoring
-- 🎯 **Complete trade history** with audit trails
-
-### **Robust Architecture**
-- 🔄 **Auto-restart capability** with error notifications
-- 💾 **Persistent data storage** that survives restarts
-- 🛡️ **Comprehensive error handling** and logging
-- ⚙️ **CCXT-compatible** configuration and parameters
-
 ## 📖 **Documentation**
 
-| Guide | Purpose |
-|-------|---------|
-| [SETUP_GUIDE.md](SETUP_GUIDE.md) | **5-minute setup** with step-by-step instructions |
-| [QUICK_START.md](QUICK_START.md) | **Your questions answered** - persistence, structure, safety |
-| [PROJECT_STRUCTURE.md](PROJECT_STRUCTURE.md) | **Folder organization** and file purposes |
-| [DEPLOYMENT_GUIDE.md](DEPLOYMENT_GUIDE.md) | **Production deployment** options and best practices |
+| Guide | Purpose | Quick Link |
+|-------|---------|------------|
+| **[Setup Guide](docs/setup.md)** | **5-minute installation** | [📖 docs/setup.md](docs/setup.md) |
+| **[Project Structure](docs/project-structure.md)** | **Codebase organization** | [📖 docs/project-structure.md](docs/project-structure.md) |
+| **[Deployment Guide](docs/deployment.md)** | **Production deployment** | [📖 docs/deployment.md](docs/deployment.md) |
 
 ## 🚨 **Important Notes**
 

+ 0 - 189
SETUP_GUIDE.md

@@ -1,189 +0,0 @@
-# 📱 Quick Setup Guide - Manual Trading Bot
-
-## 🎯 What You're Getting
-
-**Complete manual control of your Hyperliquid account from your phone with professional trading statistics.**
-
-✅ **Phone Trading**: Buy/sell from anywhere via Telegram  
-✅ **Full Statistics**: Win rate, Sharpe ratio, Sortino, P&L, drawdown, etc.  
-✅ **Balance Tracking**: Starting balance vs current with % returns  
-✅ **Trade History**: Every trade logged with automatic P&L calculation  
-✅ **Risk Metrics**: Professional-grade performance analytics  
-✅ **Safe Default**: Starts in testnet mode  
-
-## 🚀 5-Minute Setup
-
-### Step 1: Create Telegram Bot (2 minutes)
-
-1. **Open Telegram** → Search **@BotFather**
-2. Send: `/newbot`
-3. **Name your bot**: "My Trading Bot" 
-4. **Username**: something like `mytradingbot_123_bot`
-5. **Save the token** (looks like: `123456789:ABCdefGHIjklMNOPqrs`)
-
-### Step 2: Get Your Chat ID (1 minute)
-
-```bash
-# In your terminal
-python get_telegram_chat_id.py
-```
-
-- **Message your bot** anything in Telegram
-- **Copy the Chat ID** from terminal output
-
-### Step 3: Configure Bot (2 minutes)
-
-```bash
-# Copy example config
-cp env.example .env
-
-# Edit with your info (use any text editor)
-nano .env
-```
-
-**Set these 4 things in `.env`:**
-```env
-HYPERLIQUID_PRIVATE_KEY=your_private_key_here
-TELEGRAM_BOT_TOKEN=your_token_from_botfather
-TELEGRAM_CHAT_ID=your_chat_id_from_script
-TELEGRAM_ENABLED=true
-```
-
-### Step 4: Start Trading! 
-
-```bash
-python manual_trading_bot.py
-```
-
-**That's it!** 🎉 Open Telegram and send `/start` to your bot.
-
-## 📱 What You Can Do
-
-### Instant Commands
-- `/balance` - Check balance + P&L
-- `/stats` - Complete trading statistics  
-- `/buy 0.001 50000` - Buy 0.001 BTC at $50,000
-- `/sell 0.001 55000` - Sell 0.001 BTC at $55,000
-- `/positions` - Open positions
-- `/orders` - Pending orders
-
-### Quick Buttons
-Send `/start` to see instant action buttons for one-tap:
-- 💰 Balance, 📊 Stats, 📈 Positions, 📋 Orders, 💵 Price
-
-## 📊 Statistics You Get
-
-**From the moment you first launch, the bot tracks:**
-
-```
-📊 Trading Statistics
-
-💰 Balance Overview
-• Initial: $1,000.00        ← Your starting balance
-• Current: $1,150.00        ← Real-time balance  
-• Total P&L: $150.00        ← Profit/Loss
-• Total Return: 15.00%      ← % return
-
-📈 Trading Activity  
-• Total Trades: 25          ← Complete count
-• Buy Orders: 13            ← Trade breakdown
-• Sell Orders: 12
-• Days Active: 30           ← Time since first launch
-
-🏆 Performance Metrics
-• Win Rate: 68.0%           ← % profitable trades
-• Profit Factor: 2.15       ← Gains ÷ Losses  
-• Avg Win: $45.50           ← Average profitable trade
-• Avg Loss: $28.75          ← Average losing trade
-• Expectancy: $6.25         ← Expected $ per trade
-
-📊 Risk Metrics
-• Sharpe Ratio: 1.85        ← Risk-adjusted returns
-• Sortino Ratio: 2.41       ← Downside risk metric
-• Max Drawdown: 8.5%        ← Worst decline from peak
-• Volatility: 12.3%         ← Price volatility  
-• VaR (95%): 3.2%          ← Value at Risk
-
-🎯 Best/Worst
-• Largest Win: $125.00      ← Best single trade
-• Largest Loss: $75.00      ← Worst single trade
-• Max Consecutive Wins: 5   ← Winning streaks
-• Max Consecutive Losses: 2 ← Losing streaks
-```
-
-## 🛡️ Safety Features
-
-### ✅ Testnet First
-- **Starts in testnet by default** (fake money)
-- Test everything before real trading
-- Switch to mainnet when ready
-
-### ✅ Order Confirmations  
-- **Every trade needs confirmation**
-- Clear order details shown
-- Easy cancel button
-
-### ✅ Complete Logging
-- All trades automatically recorded
-- Statistics saved between restarts
-- Full audit trail with order IDs
-
-## 🔧 Where Are Your Keys?
-
-### Hyperliquid Private Key
-**Testnet** (for learning): 
-1. Go to [Hyperliquid Testnet](https://app.hyperliquid-testnet.xyz/)
-2. Create/connect wallet → Export private key
-
-**Mainnet** (real money):
-1. Go to [Hyperliquid](https://app.hyperliquid.xyz/) 
-2. Connect wallet → Export private key
-
-⚠️ **Keep private keys secure** - never share them!
-
-## 🎮 Try the Demo
-
-See what your statistics will look like:
-```bash
-python demo_stats.py
-```
-
-This creates sample trading data so you can see all the metrics the bot tracks.
-
-## 🔍 Troubleshooting
-
-### "Configuration validation failed"
-- Check your `.env` file has all 4 required fields
-- Make sure `TELEGRAM_ENABLED=true`
-
-### "Telegram bot not responding"  
-- Verify bot token from @BotFather
-- Check Chat ID from `get_telegram_chat_id.py`
-- Make sure you messaged your bot first
-
-### "Private key not set"
-- Get private key from Hyperliquid (see above)
-- Add to `.env` file
-
-## 🎯 Quick Commands Reference
-
-```bash
-# Setup
-python get_telegram_chat_id.py    # Get Chat ID
-python demo_stats.py              # See sample statistics  
-python manual_trading_bot.py      # Start trading bot
-
-# Test configuration  
-python -c "from config import Config; Config.validate()"
-```
-
-## 📈 What Makes This Special
-
-- **No coding required** - Just use Telegram commands
-- **Professional analytics** - Same metrics as trading platforms  
-- **Phone optimized** - Trade from anywhere
-- **Comprehensive tracking** - Every stat you need
-- **Persistent data** - Statistics saved between sessions
-- **Safe by default** - Testnet mode prevents accidents
-
-**You get institutional-grade trading analytics with simple phone control! 🚀📱** 

+ 296 - 0
docs/deployment.md

@@ -0,0 +1,296 @@
+# 🚀 Deployment Guide
+
+**Production deployment options for your trading bot**
+
+## 🎯 Quick Production Start
+
+```bash
+python trading_bot.py
+```
+This single command handles everything:
+- ✅ Configuration validation
+- ✅ Auto-restart on errors
+- ✅ Error notifications to your phone
+- ✅ Comprehensive logging
+- ✅ Graceful shutdown
+
+## 🖥️ Deployment Options
+
+### **Option 1: Screen/Tmux (Simplest)**
+```bash
+# Start a detachable session
+screen -S trading-bot
+
+# Run the bot
+source venv/bin/activate
+python trading_bot.py
+
+# Detach: Ctrl+A, then D
+# Reattach: screen -r trading-bot
+# Stop: screen -r trading-bot, then Ctrl+C
+```
+
+### **Option 2: Systemd Service (Linux)**
+Create `/etc/systemd/system/trading-bot.service`:
+```ini
+[Unit]
+Description=Hyperliquid Trading Bot
+After=network.target
+
+[Service]
+Type=simple
+User=your_username
+WorkingDirectory=/path/to/ManualTrader
+Environment=PATH=/path/to/ManualTrader/venv/bin
+ExecStart=/path/to/ManualTrader/venv/bin/python trading_bot.py
+Restart=always
+RestartSec=30
+
+[Install]
+WantedBy=multi-user.target
+```
+
+```bash
+# Enable and start service
+sudo systemctl enable trading-bot
+sudo systemctl start trading-bot
+
+# Check status
+sudo systemctl status trading-bot
+
+# View logs
+sudo journalctl -u trading-bot -f
+```
+
+### **Option 3: Docker**
+```dockerfile
+FROM python:3.11-slim
+
+WORKDIR /app
+COPY requirements.txt .
+RUN pip install -r requirements.txt
+
+COPY . .
+CMD ["python", "trading_bot.py"]
+```
+
+```bash
+# Build and run
+docker build -t trading-bot .
+docker run -d --name trading-bot \
+  --env-file .env \
+  --restart unless-stopped \
+  trading-bot
+```
+
+### **Option 4: PM2 (Node.js Process Manager)**
+```bash
+npm install -g pm2
+
+# Start bot with PM2
+pm2 start trading_bot.py --interpreter python3 --name "trading-bot"
+
+# Save configuration
+pm2 startup
+pm2 save
+
+# Monitor
+pm2 status
+pm2 logs trading-bot
+```
+
+## 🛡️ Production Safety
+
+### **Built-in Safety Features**
+- **Auto-restart** - Up to 10 attempts with exponential backoff
+- **Error notifications** - Sent to your Telegram immediately
+- **Data persistence** - Statistics survive crashes and restarts
+- **Comprehensive logging** - Daily log files with error tracking
+
+### **Additional Monitoring**
+```bash
+# Check if bot is running
+ps aux | grep "python.*trading_bot"
+
+# Monitor logs in real-time
+tail -f logs/trading_bot_$(date +%Y%m%d).log
+
+# Check error log
+tail -f logs/bot_errors.log
+
+# View bot status via Telegram
+# Send /start to your bot, it shows operational status
+```
+
+### **Resource Monitoring**
+```bash
+# Monitor system resources
+htop
+
+# Check disk space (logs can grow)
+df -h
+
+# Monitor bot memory usage
+ps -p $(pgrep -f trading_bot.py) -o pid,vsz,rss,pcpu,pmem,comm
+```
+
+## 🔄 Safe Update Process
+
+### **1. Backup Current State**
+```bash
+# Backup your configuration and data
+cp .env .env.backup
+cp trading_stats.json trading_stats.backup
+```
+
+### **2. Stop Bot Gracefully**
+```bash
+# For screen/tmux: Ctrl+C
+# For systemd:
+sudo systemctl stop trading-bot
+
+# For Docker:
+docker stop trading-bot
+
+# For PM2:
+pm2 stop trading-bot
+```
+
+### **3. Update Code**
+```bash
+git pull origin main
+# or download new version
+```
+
+### **4. Test Before Restart**
+```bash
+# Validate configuration
+python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Config.validate()"
+
+# Quick test (optional)
+python utils/simple_bot.py
+```
+
+### **5. Restart Production**
+```bash
+# Screen/tmux: screen -S trading-bot, then python trading_bot.py
+# Systemd: sudo systemctl start trading-bot
+# Docker: docker start trading-bot
+# PM2: pm2 start trading-bot
+```
+
+## ⚙️ Environment-Specific Configuration
+
+### **Development**
+```env
+HYPERLIQUID_TESTNET=true
+LOG_LEVEL=DEBUG
+```
+
+### **Staging**
+```env
+HYPERLIQUID_TESTNET=true
+LOG_LEVEL=INFO
+```
+
+### **Production**
+```env
+HYPERLIQUID_TESTNET=false  # REAL MONEY!
+LOG_LEVEL=INFO
+```
+
+## 📊 Performance Tuning
+
+### **Log Management**
+```bash
+# Rotate logs (optional - bot creates daily files)
+find logs/ -name "*.log" -mtime +30 -delete
+
+# Compress old logs
+gzip logs/trading_bot_$(date -d '1 day ago' +%Y%m%d).log
+```
+
+### **Resource Limits**
+The bot is lightweight but you can set limits:
+```bash
+# Systemd service limits
+[Service]
+MemoryLimit=512M
+CPUQuota=50%
+```
+
+## 🔍 Troubleshooting Production Issues
+
+### **Bot Not Starting**
+```bash
+# Check configuration
+python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Config.validate()"
+
+# Check dependencies
+pip list | grep -E "hyperliquid|telegram"
+
+# Check permissions
+ls -la trading_bot.py
+```
+
+### **Bot Crashes Repeatedly**
+```bash
+# Check error log
+tail -20 logs/bot_errors.log
+
+# Check system logs (systemd)
+sudo journalctl -u trading-bot --since "1 hour ago"
+
+# Test in foreground
+python trading_bot.py
+```
+
+### **Telegram Not Working**
+```bash
+# Test bot token
+curl "https://api.telegram.org/bot<YOUR_TOKEN>/getMe"
+
+# Re-verify Chat ID
+python utils/get_telegram_chat_id.py
+```
+
+## 📈 Best Practices
+
+### **Security**
+- Keep `.env` file permissions restricted: `chmod 600 .env`
+- Regularly rotate API keys
+- Monitor unusual trading activity
+- Use testnet for development
+
+### **Monitoring**
+- Set up alerts for bot downtime
+- Monitor trading performance via `/stats`
+- Check logs regularly
+- Keep system updated
+
+### **Data Protection**
+- Backup `trading_stats.json` regularly
+- Monitor disk space for logs
+- Keep multiple backups of configuration
+
+## 🎯 Quick Commands
+
+```bash
+# Check bot status
+ps aux | grep trading_bot
+
+# View real-time logs
+tail -f logs/trading_bot_$(date +%Y%m%d).log
+
+# Stop bot safely (screen/tmux)
+screen -r trading-bot
+# Then Ctrl+C
+
+# Restart bot
+python trading_bot.py
+
+# Check bot health via Telegram
+# Send /start to your bot
+```
+
+**Your bot is now production-ready with professional deployment! 🚀🛡️** 

+ 189 - 0
docs/project-structure.md

@@ -0,0 +1,189 @@
+# 📁 Project Structure
+
+**Understanding the ManualTrader codebase organization**
+
+## 🎯 Single Command Operation
+
+```bash
+python trading_bot.py  # Only command you need to run
+```
+
+## 📂 Directory Structure
+
+```
+ManualTrader/
+├── 🚀 trading_bot.py              # MAIN LAUNCHER
+├── 📊 trading_stats.json          # Persistent trading data
+├── 📝 .env                        # Your configuration
+├── 📄 requirements.txt            # Python dependencies
+├── 📄 .gitignore                  # Git ignore rules
+│
+├── 🔧 src/                        # Core application modules
+│   ├── __init__.py
+│   ├── config.py                  # Configuration management
+│   ├── hyperliquid_client.py      # CCXT-style API wrapper
+│   ├── telegram_bot.py            # Telegram interface
+│   └── trading_stats.py           # Statistics engine
+│
+├── 🛠️ utils/                      # Utilities and helpers
+│   ├── get_telegram_chat_id.py   # Chat ID finder (main)
+│   ├── simple_chat_id.py         # Alternative for servers
+│   ├── demo_stats.py             # Statistics demonstration
+│   ├── simple_bot.py             # Terminal interface
+│   ├── strategy_bot.py           # Automated strategies
+│   └── manual_trading_bot.py     # Legacy launcher
+│
+├── ⚙️ config/                     # Configuration templates
+│   └── env.example               # Environment template
+│
+├── 📋 logs/                       # Auto-created logging
+│   ├── trading_bot_YYYYMMDD.log  # Daily bot logs
+│   └── bot_errors.log            # Error log
+│
+├── 📖 docs/                       # Documentation
+│   ├── setup.md                  # Setup instructions
+│   ├── project-structure.md      # This file
+│   └── deployment.md             # Deployment guide
+│
+└── 🐍 venv/                      # Python virtual environment
+```
+
+## 🎯 Core Files
+
+### **Main Launcher**
+- **`trading_bot.py`** - The only file you run
+  - Auto-restart capability
+  - Error handling and notifications
+  - Configuration validation
+  - Comprehensive logging
+
+### **Core Modules (`src/`)**
+- **`config.py`** - CCXT-style configuration management
+- **`hyperliquid_client.py`** - Enhanced API wrapper with error handling
+- **`telegram_bot.py`** - Mobile-optimized trading interface
+- **`trading_stats.py`** - Professional analytics engine
+
+### **Data Files**
+- **`trading_stats.json`** - Your persistent trading statistics
+- **`.env`** - Your sensitive configuration (not in git)
+
+## 🛠️ Utility Scripts
+
+| Script | Purpose | When to Use |
+|--------|---------|-------------|
+| `get_telegram_chat_id.py` | Find your Telegram Chat ID | **Setup only** |
+| `simple_chat_id.py` | Alternative Chat ID finder | If main script fails |
+| `demo_stats.py` | Show sample statistics | See what bot tracks |
+| `simple_bot.py` | Terminal interface | Quick testing |
+| `strategy_bot.py` | Automated trading | If you want automation |
+
+## 📊 Data Flow
+
+```
+1. trading_bot.py (launcher)
+   ↓
+2. src/config.py (load configuration)
+   ↓
+3. src/hyperliquid_client.py (connect to exchange)
+   ↓
+4. src/telegram_bot.py (start interface)
+   ↓
+5. src/trading_stats.py (track performance)
+   ↓
+6. trading_stats.json (persist data)
+```
+
+## 🔧 Module Details
+
+### **Config Management (`src/config.py`)**
+```python
+# CCXT-style configuration
+config = {
+    'apiKey': 'your_private_key',
+    'secret': 'your_secret_key',
+    'testnet': True,
+    'sandbox': True
+}
+```
+
+### **API Client (`src/hyperliquid_client.py`)**
+- CCXT-compatible initialization
+- Enhanced error handling
+- Connection testing
+- Safe parameter logging
+
+### **Telegram Interface (`src/telegram_bot.py`)**
+- Mobile-optimized UI
+- Inline keyboards
+- Order confirmations
+- Real-time notifications
+
+### **Statistics Engine (`src/trading_stats.py`)**
+- FIFO P&L calculation
+- Professional risk metrics
+- Persistent data storage
+- Performance analytics
+
+## 🛡️ Security Features
+
+### **Sensitive Data Protection**
+- `.env` files excluded from git
+- API keys masked in logs
+- Trading data locally stored
+
+### **Error Recovery**
+- Auto-restart on crashes
+- Comprehensive error logging
+- Telegram error notifications
+
+## 📝 Configuration Files
+
+### **Environment Variables (`.env`)**
+```env
+# Authentication
+HYPERLIQUID_PRIVATE_KEY=your_private_key_here
+HYPERLIQUID_SECRET_KEY=your_secret_key_here
+
+# Network
+HYPERLIQUID_TESTNET=true
+
+# Telegram
+TELEGRAM_BOT_TOKEN=your_token_here
+TELEGRAM_CHAT_ID=your_chat_id_here
+TELEGRAM_ENABLED=true
+```
+
+### **Dependencies (`requirements.txt`)**
+- `hyperliquid==0.4.66` - Exchange library
+- `python-telegram-bot[webhooks]==20.7` - Telegram interface
+- `python-dotenv==1.1.0` - Environment management
+- `pandas==2.2.3` - Data analysis
+- `numpy==2.2.6` - Numerical computing
+
+## 🔄 Development Workflow
+
+### **Testing Changes**
+```bash
+# Test configuration
+python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Config.validate()"
+
+# Test terminal interface
+python utils/simple_bot.py
+
+# Test statistics
+python utils/demo_stats.py
+```
+
+### **Production Deployment**
+```bash
+# Single command for production
+python trading_bot.py
+```
+
+## 📖 Related Documentation
+
+- **[Setup Guide](setup.md)** - Installation and configuration
+- **[Deployment Guide](deployment.md)** - Production deployment options
+- **[Main README](../README.md)** - Overview and features
+
+**This architecture provides professional-grade reliability with simple operation! 🚀** 

+ 111 - 0
docs/setup.md

@@ -0,0 +1,111 @@
+# ⚡ Setup Guide
+
+**5-minute setup for your Hyperliquid trading bot**
+
+## 📋 Prerequisites
+
+- Python 3.11+ installed
+- Hyperliquid account (testnet or mainnet)
+- Telegram account
+
+## 🚀 Installation
+
+### 1. Clone & Install
+```bash
+git clone git@repo.codeskraps.com:codeskraps/ManualTrader.git
+cd ManualTrader
+
+python3 -m venv venv
+source venv/bin/activate  # Windows: venv\Scripts\activate
+pip install -r requirements.txt
+```
+
+### 2. Create Telegram Bot
+1. **Message @BotFather** on Telegram
+2. Send: `/newbot`
+3. **Choose name**: "My Trading Bot"
+4. **Choose username**: `mytradingbot_123_bot`
+5. **Save the token** (format: `123456789:ABCdefGHIjklMNOPqrs`)
+
+### 3. Get Your Chat ID
+```bash
+python utils/get_telegram_chat_id.py
+```
+- Enter your bot token
+- **Message your bot** in Telegram (send "hello")
+- **Copy the Chat ID** displayed in terminal
+
+### 4. Configure Environment
+```bash
+cp config/env.example .env
+nano .env  # Or use your preferred editor
+```
+
+**Required settings:**
+```env
+# Get from Hyperliquid account settings
+HYPERLIQUID_PRIVATE_KEY=your_private_key_here
+HYPERLIQUID_SECRET_KEY=your_secret_key_here
+HYPERLIQUID_TESTNET=true
+
+# From steps above
+TELEGRAM_BOT_TOKEN=your_bot_token_here
+TELEGRAM_CHAT_ID=your_chat_id_here
+TELEGRAM_ENABLED=true
+```
+
+### 5. Start Trading
+```bash
+python trading_bot.py
+```
+
+**📱 Open Telegram → Send `/start` to your bot**
+
+## 🔑 Getting Hyperliquid Keys
+
+### Testnet (Recommended First)
+1. Go to [Hyperliquid Testnet](https://app.hyperliquid-testnet.xyz/)
+2. Connect/create wallet
+3. Export private key from wallet settings
+
+### Mainnet (Real Money)
+1. Go to [Hyperliquid](https://app.hyperliquid.xyz/)
+2. Connect wallet
+3. Export private key from wallet settings
+
+⚠️ **Never share your private keys!**
+
+## ✅ Verify Setup
+
+```bash
+# Test configuration
+python -c "import sys; sys.path.insert(0, 'src'); from config import Config; Config.validate()"
+
+# See sample statistics
+python utils/demo_stats.py
+```
+
+## 🔧 Common Issues
+
+### "Configuration validation failed"
+- Check all required fields in `.env`
+- Ensure `TELEGRAM_ENABLED=true`
+
+### "Telegram bot not responding"
+- Verify bot token with @BotFather
+- Confirm Chat ID from script output
+- Message your bot first before running script
+
+### "Import error"
+- Activate virtual environment: `source venv/bin/activate`
+- Install dependencies: `pip install -r requirements.txt`
+
+## 🎯 Next Steps
+
+Once setup is complete:
+- **Test with small amounts** on testnet first
+- **Read the main README** for usage instructions
+- **Check [Project Structure](project-structure.md)** to understand the codebase
+- **Review [Deployment](deployment.md)** for production use
+
+**Setup complete! Your bot is ready for phone trading 🚀📱**