# Agent Bot - Quick Start Guide **Get your automated agent bot running in 5 minutes!** --- ## 🚀 Installation ### Prerequisites - Python 3.8+ - Event Trader API access - API key with read/write permissions ### Install Dependencies ```bash pip install pyyaml aiohttp numpy ``` --- ## ⚡ Quick Start (3 Steps) ### Step 1: Copy the Bot Code All agent bot code is located in: ``` /root/lib/prod3/event_trader/trading_bot/ ``` To copy to your local machine: ```bash # On the server cd /root/lib/prod3/event_trader tar -czf trading_bot.tar.gz trading_bot/ # Download to your machine scp user@server:/root/lib/prod3/event_trader/trading_bot.tar.gz . tar -xzf trading_bot.tar.gz cd trading_bot ``` **Or access via website:** Visit: `http://localhost:8000/trading-bot` to download the complete bot package. ### Step 2: Configure Your Bot Edit `config.yaml`: ```yaml api: api_key: "evt_YOUR_KEY_HERE" # ← CHANGE THIS base_url: "http://localhost:8000" bot: mode: "paper" # Start with paper trading initial_capital: 10000.0 strategies: mean_reversion: enabled: true momentum: enabled: true ``` ### Step 3: Run the Bot ```bash # Run risk-managed bot (recommended) python3 risk_managed_bot.py # Or run strategy bot python3 strategy_bot.py # Or run simple demo python3 demo_bot.py ``` --- ## 📊 What You'll See ### Paper Trading Mode Output ``` 🤖 Starting EventTrader Bot v1 💰 Initial capital: $10,000.00 📊 Mode: paper 🎯 Active strategies: 2 📋 Risk Limits: Max Position Size: 20.0% Max Drawdown: 15.0% Stop Loss: 5.0% ============================================================ Running trading cycle... ============================================================ 📈 Analyzing 20 active markets 🔔 Signal received: BUY GRT Confidence: 81.7% Entry: $0.4264 ✅ Approved by risk manager Position Size: 1596.10 (6.8% of capital) Target: $0.5394 Stop: $0.3699 📝 Paper: Position opened 💼 Managing 1 open positions... GRT: $0.4312, P&L: $+76.61 (+1.80%) 📊 Portfolio Summary: Capital: $10,076.61 Return: $+76.61 (+0.77%) Drawdown: 0.00% Open Positions: 1 Total Trades: 0 ``` --- ## 🎯 Usage Examples ### Example 1: Paper Trading (Safe Testing) ```bash # Run in paper mode (simulated) python3 risk_managed_bot.py ``` **Features:** - ✅ Real market data - ✅ Simulated trades - ✅ No risk to capital - ✅ Full risk management active ### Example 2: Live Trading (Real Money) 1. **Test paper mode for 1 week minimum** 2. **Edit config.yaml:** ```yaml bot: mode: "live" # Switch to live initial_capital: 500.0 # Start small! ``` 3. **Run with monitoring:** ```bash python3 risk_managed_bot.py 2>&1 | tee trading.log ``` ### Example 3: Backtesting Strategies ```bash # Simple backtest python3 backtest_example.py # Advanced backtest (4 market conditions) python3 backtest_risk_managed.py ``` **Sample Output:** ``` ============================================================ BACKTEST RESULTS ============================================================ Capital: Initial: $10,000.00 Final: $10,665.69 Return: $665.69 (+6.66%) Trades: Total: 3 Wins: 2 Losses: 1 Win Rate: 66.7% Risk Metrics: Sharpe Ratio: 0.86 Max Drawdown: 3.71% Profit Factor: 0.42 ``` --- ## 🔧 Configuration Guide ### Essential Settings ```yaml # Bot Behavior bot: mode: "paper" # "paper" or "live" initial_capital: 10000.0 # Starting capital update_interval: 60 # Seconds between cycles # API Connection api: api_key: "evt_YOUR_KEY" # Your API key base_url: "http://localhost:8000" rate_limit: 100 # Requests per minute # Risk Controls risk: max_position_size: 0.20 # 20% max per position max_drawdown: 0.15 # Stop at 15% loss stop_loss_pct: 0.05 # 5% stop loss take_profit_pct: 0.10 # 10% take profit # Strategy Selection strategies: mean_reversion: enabled: true # Enable/disable min_confidence: 0.6 # Minimum signal confidence momentum: enabled: true min_confidence: 0.6 # Execution Settings execution: order_type: "limit" # "limit" or "market" max_slippage: 0.01 # 1% maximum slippage retry_attempts: 3 # Retry failed orders ``` --- ## 📁 File Structure ``` trading_bot/ ├── config.yaml # Configuration file │ ├── Core Modules ├── core/ │ ├── api_client.py # API integration │ ├── risk_manager.py # Risk management │ ├── trade_executor.py # Order execution │ └── portfolio_manager.py # Portfolio tracking │ ├── Strategies ├── strategies/ │ ├── base_strategy.py # Base class │ ├── mean_reversion.py # Mean reversion strategy │ └── momentum.py # Momentum strategy │ ├── Utilities ├── utils/ │ ├── indicators.py # Technical indicators │ └── backtester.py # Backtesting framework │ ├── Bots (Choose one to run) ├── demo_bot.py # Simple demo ├── strategy_bot.py # Multi-strategy bot ├── risk_managed_bot.py # Full production bot (recommended) │ └── Backtesting ├── backtest_example.py └── backtest_risk_managed.py ``` --- ## 🎓 How It Works ### Trading Flow ``` 1. Market Analysis └─> Fetch active markets from API └─> Generate price history └─> Calculate technical indicators 2. Signal Generation └─> Mean Reversion: RSI + Bollinger Bands └─> Momentum: MACD + EMA + ROC └─> Confidence scoring 3. Risk Management └─> Position sizing (Kelly Criterion) └─> Check portfolio limits └─> Enforce stop-loss/take-profit └─> Validate against constraints 4. Trade Execution └─> Place market or limit orders └─> Track execution quality └─> Monitor slippage └─> Handle errors with retry 5. Portfolio Management └─> Track open positions └─> Calculate P&L (realized/unrealized) └─> Update performance metrics └─> Monitor for rebalancing ``` ### Strategy Details **Mean Reversion Strategy:** - **Entry**: RSI < 30 (oversold) + price below lower Bollinger Band - **Exit**: Price returns to mean (middle BB) - **Stop**: 50% of potential gain - **Best for**: Range-bound markets **Momentum Strategy:** - **Entry**: MACD crosses above signal + price above EMA + positive ROC - **Exit**: MACD crosses down or momentum weakens - **Stop**: Price crosses back below/above EMA - **Best for**: Trending markets --- ## 🛡️ Risk Management ### Automatic Protections ✅ **Position Size Limits** - Maximum 20% of capital per position - Kelly Criterion optimal sizing - Confidence-adjusted allocation ✅ **Portfolio Constraints** - Maximum 15% drawdown limit - Daily loss limit: 5% - Maximum 10 open positions ✅ **Stop-Loss Protection** - Automatic trailing stops (5%) - Take-profit targets (10%) - Real-time monitoring ✅ **Circuit Breaker** - Activates after 5 consecutive failures - Prevents cascading losses - Auto-reset on success --- ## 📈 Performance Monitoring ### Real-Time Metrics The bot displays: - Current capital and returns - Open positions with P&L - Win rate and trade count - Drawdown percentage - Strategy performance ### Advanced Metrics (10+ trades) After sufficient trading history: - **Sharpe Ratio**: Risk-adjusted returns - **Sortino Ratio**: Downside risk measure - **Max Drawdown**: Largest peak-to-trough decline - **VaR (95%)**: Value at Risk - **Profit Factor**: Gross profit / gross loss --- ## 🔍 Troubleshooting ### Common Issues **"API key not found"** ```bash # Check config.yaml has your API key api: api_key: "evt_YOUR_KEY_HERE" # Must start with evt_ ``` **"No markets found"** ```bash # Verify API is running curl http://localhost:8000/api/v2/markets?limit=1 # Check markets exist with your criteria python3 -c "import asyncio; from core.api_client import APIClient; ..." ``` **"Insufficient capital"** - Check initial_capital in config.yaml - Verify position sizing isn't too aggressive - Check max_position_size setting **"Circuit breaker active"** - Bot stopped after multiple failures - Check API connectivity - Review logs for error patterns - Restart bot to reset circuit breaker --- ## 📝 Best Practices ### For Paper Trading 1. **Run for 1+ week** before going live 2. **Monitor daily** to understand behavior 3. **Test different configurations** 4. **Validate strategies** work as expected 5. **Review all trades** in logs ### For Live Trading 1. **Start small** ($100-500) 2. **Monitor constantly** first week 3. **Keep stop-losses enabled** 4. **Scale gradually** (2x per month max) 5. **Never invest** more than you can lose 6. **Daily review** of performance 7. **Weekly adjustment** of parameters --- ## ⚠️ Important Warnings ### Risk Disclaimer - Trading involves **risk of loss** - Past performance ≠ future results - Only trade with capital you **can afford to lose** - **Start with paper trading** - Monitor actively in **live mode** - Use **stop-losses always** - Understand strategies before deploying ### Never Do This ❌ Trade with borrowed money ❌ Skip paper trading phase ❌ Disable risk controls ❌ Ignore stop-losses ❌ Leave unmonitored for days ❌ Trade money you need --- ## 🆘 Support ### Documentation - **Quick Start**: `TRADING-BOT-QUICKSTART.md` (this file) - **Complete Guide**: `TRADING-BOT-USER-GUIDE.md` - **Planning**: `TRADING-BOT-PLANNING.md` - **Final Summary**: `TRADING-BOT-FINAL-SUMMARY.md` ### Examples All bots include working examples in the `trading_bot/` directory. ### Logs Logs are written to console and can be redirected: ```bash python3 risk_managed_bot.py 2>&1 | tee bot.log ``` --- ## 🎯 Next Steps ### 1. Quick Test Run ```bash cd trading_bot python3 demo_bot.py # Watch it fetch markets and positions ``` ### 2. Run Backtest ```bash python3 backtest_risk_managed.py # See how strategies perform ``` ### 3. Paper Trading ```bash # Edit config.yaml, add your API key python3 risk_managed_bot.py # Run for 1+ week ``` ### 4. Go Live (Optional) ```bash # After successful paper trading # Change mode to "live" in config.yaml # Start with minimal capital python3 risk_managed_bot.py ``` --- ## 📊 Performance Expectations ### Realistic Returns Based on backtesting: - **Mean Reversion**: 0-5% in ranging markets - **Momentum**: 1-7% in trending markets - **Combined**: 3-10% with proper risk management **Note**: These are historical backtest results. Live results may vary significantly. ### Time Commitment - **Paper Trading**: 5-10 min/day monitoring - **Live Trading**: 15-30 min/day first week, then 10 min/day --- ## ✅ Pre-Flight Checklist Before running: - [ ] Python 3.8+ installed - [ ] Dependencies installed (`pip install pyyaml aiohttp numpy`) - [ ] API key configured in `config.yaml` - [ ] API server running (`http://localhost:8000`) - [ ] Mode set to "paper" for testing - [ ] Read documentation - [ ] Understand risk disclaimer - [ ] Ready to monitor actively --- ## 🚀 Start Trading Now! ```bash cd trading_bot python3 risk_managed_bot.py ``` **Happy Trading! 🎉** --- **Version**: 1.0 **Last Updated**: November 21, 2025 **Status**: Production Ready ✅