# Agent Bot User Guide **Version**: 1.0 **Date**: November 21, 2025 **Platform**: Event Trader Prediction Markets ## 📚 Table of Contents 1. [Introduction](#introduction) 2. [Quick Start](#quick-start) 3. [Installation](#installation) 4. [Configuration](#configuration) 5. [Running the Bot](#running-the-bot) 6. [Trading Strategies](#trading-strategies) 7. [Risk Management](#risk-management) 8. [Monitoring & Analytics](#monitoring--analytics) 9. [Examples](#examples) 10. [Troubleshooting](#troubleshooting) 11. [Advanced Topics](#advanced-topics) 12. [API Reference](#api-reference) --- ## Introduction The Event Trader Agent Bot is an autonomous trading system that executes trades on prediction markets using algorithmic strategies, technical analysis, and risk management. ### Key Features - **🤖 Autonomous Trading**: Runs 24/7 without manual intervention - **📊 Multiple Strategies**: Mean reversion, momentum, arbitrage, market making - **🛡️ Risk Management**: Position sizing, stop-loss, portfolio limits - **📈 Real-Time Monitoring**: Track performance, positions, and P&L - **🔔 Alerts**: Get notified of important events and trades - **📝 Comprehensive Logging**: Full audit trail of all decisions ### System Requirements - Python 3.12+ - 4GB RAM minimum - Stable internet connection - Event Trader API v2 access with API key --- ## Quick Start ### 5-Minute Setup ```bash # 1. Navigate to agent bot directory cd event_trader/trading_bot # 2. Install dependencies (if needed) pip install pyyaml aiohttp # 3. Copy config template cp config.yaml my_config.yaml # 4. Edit config with your API key nano my_config.yaml # Add your API key # 5. Run demo bot python demo_bot.py ``` **Expected Output**: ``` 2025-11-21 08:00:00 - __main__ - INFO - 🤖 Starting EventTrader Bot v1 2025-11-21 08:00:00 - __main__ - INFO - 💰 Initial capital: $10,000.00 2025-11-21 08:00:00 - __main__ - INFO - 📊 Mode: paper 2025-11-21 08:00:00 - api_client - INFO - API client started 2025-11-21 08:00:01 - __main__ - INFO - Running trading cycle... 2025-11-21 08:00:01 - __main__ - INFO - 📈 Found 10 active markets ``` --- ## Installation ### Step 1: Prerequisites ```bash # Check Python version (need 3.12+) python3 --version # Install required packages pip install pyyaml aiohttp numpy pandas ta-lib scikit-learn ``` ### Step 2: Get API Key 1. Navigate to Event Trader dashboard 2. Go to API Settings 3. Create new API key with `read` and `write` permissions 4. Copy the key (starts with `evt_`) 5. **⚠️ Important**: Save the key securely - it cannot be retrieved again ### Step 3: Project Structure ``` trading_bot/ ├── config.yaml # Configuration file ├── demo_bot.py # Simple demo bot ├── core/ │ ├── __init__.py │ └── api_client.py # API client with rate limiting ├── strategies/ # Trading strategies │ └── __init__.py ├── utils/ # Utility functions │ └── __init__.py └── tests/ # Test files └── __init__.py ``` --- ## Configuration ### Configuration File (`config.yaml`) ```yaml bot: name: "My Agent Bot" mode: "paper" # Start in paper trading mode initial_capital: 10000.0 update_interval: 60 # Check markets every 60 seconds api: base_url: "http://localhost:8000" api_key: "evt_YOUR_API_KEY_HERE" # ⚠️ Replace with your key rate_limit: 100 # Requests per minute strategies: - name: "mean_reversion" enabled: true weight: 0.5 params: lookback_period: 20 entry_threshold: 2.0 exit_threshold: 0.5 risk: max_position_size: 0.20 # Max 20% 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 execution: order_type: "limit" time_in_force: 300 # 5 minutes min_liquidity: 1000 # Minimum $1000 pool ``` ### Key Configuration Options #### Bot Settings | Setting | Description | Default | Range | |---------|-------------|---------|-------| | `mode` | Trading mode | `paper` | `paper`, `live` | | `initial_capital` | Starting capital | 10000 | >0 | | `update_interval` | Seconds between cycles | 60 | 10-3600 | #### Risk Settings | Setting | Description | Default | Recommended | |---------|-------------|---------|-------------| | `max_position_size` | Max % per position | 0.20 | 0.10-0.25 | | `max_drawdown` | Stop trading threshold | 0.15 | 0.10-0.20 | | `stop_loss_pct` | Position stop loss | 0.05 | 0.03-0.10 | | `take_profit_pct` | Position take profit | 0.10 | 0.05-0.20 | --- ## Running the Bot ### Paper Trading Mode (Safe Testing) **Paper trading uses real market data but simulated trades.** ```bash # Run demo bot in paper mode python demo_bot.py # Output shows: # - Connected markets # - Market analysis # - Open positions # - No real money at risk ``` **When to use**: - ✅ Testing strategies - ✅ Learning the system - ✅ Validating configuration - ✅ Debugging issues ### Live Trading Mode (Real Money) ⚠️ **WARNING**: Live mode uses real capital ```bash # 1. Edit config.yaml bot: mode: "live" # Change from paper to live # 2. Start with small capital bot: initial_capital: 100.0 # Start small! # 3. Run bot python demo_bot.py # 4. Monitor closely for first 24 hours ``` **Pre-flight checklist**: - [ ] Tested in paper mode for at least 1 week - [ ] Reviewed all trades in logs - [ ] Set appropriate risk limits - [ ] Started with small capital - [ ] Set up monitoring alerts - [ ] Have stop-loss enabled ### Running in Background ```bash # Using nohup nohup python demo_bot.py > bot.log 2>&1 & # Check process ps aux | grep demo_bot # View live logs tail -f bot.log # Stop bot pkill -f demo_bot.py ``` ### Using systemd (Production) Create `/etc/systemd/system/trading-bot.service`: ```ini [Unit] Description=Agent Bot After=network.target [Service] Type=simple User=your_user WorkingDirectory=/path/to/event_trader/trading_bot ExecStart=/usr/bin/python3 demo_bot.py Restart=always RestartSec=10 [Install] WantedBy=multi-user.target ``` ```bash # Enable and start 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 ``` --- ## Trading Strategies ### 1. Mean Reversion Strategy **Theory**: Prices that deviate significantly from their average tend to revert back. **Configuration**: ```yaml strategies: - name: "mean_reversion" enabled: true weight: 0.5 params: lookback_period: 20 # Days to calculate average entry_threshold: 2.0 # Z-score for entry exit_threshold: 0.5 # Z-score for exit min_confidence: 0.6 # Minimum signal confidence ``` **When it works**: - ✅ Ranging/sideways markets - ✅ High volatility markets - ✅ Assets with strong mean **When it fails**: - ❌ Strong trending markets - ❌ Fundamental shifts - ❌ Low liquidity **Example**: ``` BTC trading at $50,000 20-day average: $48,000 Standard deviation: $1,000 Z-score = (50,000 - 48,000) / 1,000 = 2.0 Signal: SELL (price 2 std devs above mean) Entry: $50,000 Target: $48,000 (mean) Stop: $51,000 (5% above) ``` ### 2. Momentum Strategy **Theory**: Assets with strong trends continue in that direction. **Configuration**: ```yaml strategies: - name: "momentum" enabled: true weight: 0.5 params: fast_period: 10 slow_period: 30 signal_period: 9 min_confidence: 0.6 ``` **Indicators Used**: - MACD (Moving Average Convergence Divergence) - RSI (Relative Strength Index) - Moving Averages **When it works**: - ✅ Strong trending markets - ✅ Breakout scenarios - ✅ News-driven moves **When it fails**: - ❌ Choppy/ranging markets - ❌ Trend reversals - ❌ False breakouts **Example**: ``` MACD Signal: Fast MA (10-day): $49,500 Slow MA (30-day): $48,000 MACD = 49,500 - 48,000 = +1,500 (bullish) Signal: BUY (momentum positive) Entry: $50,000 Target: $52,000 (4% profit) Stop: $48,500 (3% loss) ``` ### Strategy Combination The bot combines multiple strategies using weighted signals: ```python # Strategy weights mean_reversion: 0.5 (50%) momentum: 0.5 (50%) # Example combined signal mean_reversion_signal = "SELL" (confidence: 0.8) momentum_signal = "BUY" (confidence: 0.6) # Weighted calculation sell_score = 0.5 * 0.8 = 0.4 buy_score = 0.5 * 0.6 = 0.3 # Result: SELL (higher score) ``` --- ## Risk Management ### Position Sizing The bot uses **Kelly Criterion** for optimal position sizing: ``` Kelly% = (Win% * Win/Loss Ratio - Loss%) / Win/Loss Ratio Conservative Kelly = Kelly% / 2 (default) ``` **Example**: ``` Historical Stats: - Win Rate: 60% - Avg Win: $150 - Avg Loss: $100 - Win/Loss Ratio: 1.5 Kelly = (0.6 * 1.5 - 0.4) / 1.5 = 0.333 (33.3%) Conservative = 0.333 / 2 = 0.166 (16.6%) With $10,000 capital: Position Size = $10,000 * 0.166 = $1,660 ``` ### Stop-Loss Management **Types of Stops**: 1. **Fixed Stop-Loss** (default 5%) ``` Entry: $1,000 Stop: $950 (5% below) ``` 2. **Trailing Stop** (moves with price) ``` Entry: $1,000 Current: $1,100 Trail: 5% Stop: $1,045 (5% below current) ``` 3. **Time-Based Stop** (exit after X hours) ``` Entry: 2:00 PM Time limit: 4 hours Exit: 6:00 PM (regardless of P&L) ``` ### Portfolio Limits The bot enforces multiple risk limits: | Limit Type | Default | Description | |------------|---------|-------------| | Max Position Size | 20% | Per position limit | | Max Drawdown | 15% | Stop all trading | | Daily Loss Limit | 5% | Stop for the day | | Max Open Positions | 10 | Total positions | | Max Correlated | 3 | Similar assets | **Example Scenario**: ``` Capital: $10,000 Max Position: 20% = $2,000 Max Drawdown: 15% = $1,500 loss total Position 1: $2,000 BTC (max size) Position 2: $1,500 ETH (under max) Position 3: $500 SOL (correlated with ETH) Can't open: - More BTC (at max size) - More SOL/ETH (3 correlated max) - If total loss reaches $1,500 ``` --- ## Monitoring & Analytics ### Real-Time Monitoring **Key Metrics Dashboard**: ``` === Agent Bot Status === Status: Running Uptime: 4h 32m Last Update: 2025-11-21 12:30:45 Capital: $10,000.00 Current Value: $10,450.00 P&L: +$450.00 (+4.5%) Open Positions: 3 Recent Trades: [12:25] BUY BTC @ 0.68 x 50 - OPEN [12:15] SELL ETH @ 0.55 x 30 - FILLED (+$45) [11:50] BUY SOL @ 0.72 x 40 - FILLED (+$32) ``` ### Performance Metrics **Profitability**: - Total Return: +4.5% - Win Rate: 58% (23 wins / 40 trades) - Profit Factor: 1.8 (wins/losses) - Average Win: $38.50 - Average Loss: $22.30 **Risk Metrics**: - Max Drawdown: -3.2% - Sharpe Ratio: 1.7 - Current Drawdown: -0.5% - VaR (95%): -2.1% **Execution Quality**: - Fill Rate: 94% - Avg Slippage: 0.08% - Avg Fill Time: 45 seconds ### Log Files **Location**: `trading_bot.log` **Log Levels**: - `INFO`: Normal operations - `WARNING`: Non-critical issues - `ERROR`: Errors requiring attention - `DEBUG`: Detailed debugging info **Example Log**: ``` 2025-11-21 12:30:00 - INFO - Running trading cycle... 2025-11-21 12:30:01 - INFO - Found 15 active markets 2025-11-21 12:30:02 - INFO - Analyzing market: BTC vs ETH vs SOL 2025-11-21 12:30:03 - INFO - Signal: BUY BTC (confidence: 0.75) 2025-11-21 12:30:04 - INFO - Risk check: APPROVED 2025-11-21 12:30:05 - INFO - Placing order: BUY BTC @ 0.68 x 50 2025-11-21 12:30:06 - INFO - Order placed: ord_abc123 ``` --- ## Examples ### Example 1: Basic Market Analysis ```python #!/usr/bin/env python3 """Check active markets""" import asyncio from core.api_client import APIClient async def main(): config = { "base_url": "http://localhost:8000", "api_key": "evt_your_key", "rate_limit": 100 } client = APIClient(config) await client.start() # Fetch markets markets = await client.get_markets( limit=5, status="active", asset_type="crypto" ) print(f"Found {len(markets['items'])} markets\n") for market in markets['items']: print(f"📊 {market['name']}") print(f" Pool: ${market['total_pool']:,.2f}") print(f" Assets: {', '.join(market['assets'])}") print() await client.stop() asyncio.run(main()) ``` ### Example 2: Place a Test Order ```python #!/usr/bin/env python3 """Place a limit order""" import asyncio from core.api_client import APIClient async def main(): config = { "base_url": "http://localhost:8000", "api_key": "evt_your_key", "rate_limit": 100 } client = APIClient(config) await client.start() # Place order order = await client.place_order( market_id="0x9e1910040dce96b9998c8012a23d790a6c2d3ffa", asset="BTC", side="buy", price=0.65, # 65% probability quantity=10.0 ) print(f"✅ Order placed!") print(f" ID: {order['id']}") print(f" Side: {order['side']}") print(f" Asset: {order['asset']}") print(f" Price: {order['price']}") print(f" Quantity: {order['quantity']}") await client.stop() asyncio.run(main()) ``` ### Example 3: Monitor Open Positions ```python #!/usr/bin/env python3 """Monitor your open positions""" import asyncio from core.api_client import APIClient async def main(): config = { "base_url": "http://localhost:8000", "api_key": "evt_your_key", "rate_limit": 100 } client = APIClient(config) await client.start() # Get open orders orders = await client.get_orders( limit=20, status="open" ) print(f"📊 Open Positions: {len(orders['items'])}\n") total_value = 0 for order in orders['items']: value = order['quantity'] * order['price'] total_value += value print(f"{order['side'].upper()} {order['asset']}") print(f" Price: {order['price']:.4f}") print(f" Quantity: {order['quantity']:.2f}") print(f" Value: ${value:.2f}") print(f" Filled: {order['filled_quantity']}/{order['quantity']}") print() print(f"Total Value: ${total_value:.2f}") await client.stop() asyncio.run(main()) ``` ### Example 4: Calculate Performance ```python #!/usr/bin/env python3 """Calculate trading performance""" import asyncio from core.api_client import APIClient from datetime import datetime, timedelta async def main(): config = { "base_url": "http://localhost:8000", "api_key": "evt_your_key", "rate_limit": 100 } client = APIClient(config) await client.start() # Get completed orders from last 30 days thirty_days_ago = int((datetime.now() - timedelta(days=30)).timestamp()) orders = await client.get_orders( limit=100, status="filled", created_after=thirty_days_ago ) filled_orders = orders['items'] print(f"📊 Performance (Last 30 Days)\n") print(f"Total Trades: {len(filled_orders)}") # Calculate metrics wins = 0 losses = 0 total_profit = 0 for order in filled_orders: # Simplified P&L calculation pnl = order['filled_quantity'] * (order['price'] - 0.5) # vs 50% baseline total_profit += pnl if pnl > 0: wins += 1 else: losses += 1 win_rate = wins / len(filled_orders) * 100 if filled_orders else 0 print(f"Win Rate: {win_rate:.1f}% ({wins}W / {losses}L)") print(f"Total P&L: ${total_profit:.2f}") print(f"Avg per Trade: ${total_profit/len(filled_orders):.2f}" if filled_orders else "N/A") await client.stop() asyncio.run(main()) ``` --- ## Troubleshooting ### Common Issues #### Issue 1: "API key not found" **Error**: ``` ERROR - API error: 401 UNAUTHORIZED ``` **Solution**: 1. Check API key in `config.yaml` 2. Verify key starts with `evt_` 3. Ensure key has write permissions 4. Regenerate key if needed #### Issue 2: "Rate limit exceeded" **Error**: ``` ERROR - API error: 429 TOO_MANY_REQUESTS ``` **Solution**: 1. Increase `update_interval` in config 2. Reduce `rate_limit` to match your tier 3. Check for multiple bot instances 4. Upgrade API key tier if needed #### Issue 3: "No markets found" **Error**: ``` INFO - Found 0 active markets ``` **Solution**: 1. Check market filters in config 2. Verify markets exist on platform 3. Try broader filters (remove asset_type) 4. Check API connectivity #### Issue 4: "Order placement failed" **Error**: ``` ERROR - Failed to place order: Invalid price ``` **Solution**: 1. Check price is between 0 and 1 2. Verify market has liquidity 3. Ensure order size meets minimum 4. Check balance sufficient ### Debug Mode Enable detailed logging: ```yaml logging: log_level: "DEBUG" # Change from INFO to DEBUG ``` Run with verbose output: ```bash python demo_bot.py 2>&1 | tee debug.log ``` ### Health Checks **Check API connectivity**: ```bash curl -H "X-API-Key: evt_your_key" \ http://localhost:8000/api/v2/markets?limit=1 ``` **Check bot process**: ```bash ps aux | grep demo_bot netstat -tulpn | grep python ``` **Check logs**: ```bash tail -f trading_bot.log grep ERROR trading_bot.log grep "Order placed" trading_bot.log | wc -l ``` --- ## Advanced Topics ### Custom Strategies Create your own strategy: ```python # strategies/my_strategy.py from typing import Dict, Any class MyCustomStrategy: """My custom trading strategy""" def __init__(self, config: Dict[str, Any]): self.config = config self.name = "my_custom" async def generate_signal(self, market_data: Dict) -> Dict: """ Generate trading signal Returns: { "action": "buy" | "sell" | "hold", "confidence": 0.0-1.0, "reasoning": str } """ # Your strategy logic here pass ``` ### Backtesting Test strategies on historical data: ```python # Test strategy performance def backtest_strategy(strategy, historical_data): """Run backtest on historical data""" capital = 10000 positions = [] for data_point in historical_data: signal = strategy.generate_signal(data_point) if signal["action"] == "buy": # Execute buy logic pass elif signal["action"] == "sell": # Execute sell logic pass # Calculate metrics return { "total_return": ..., "sharpe_ratio": ..., "max_drawdown": ... } ``` ### WebHooks & Alerts Send alerts to external services: ```python import aiohttp async def send_alert(message: str): """Send alert to webhook""" webhook_url = "https://hooks.slack.com/services/YOUR/WEBHOOK" async with aiohttp.ClientSession() as session: await session.post(webhook_url, json={"text": message}) # Usage await send_alert("🚨 Stop loss triggered on BTC position!") ``` ### Database Integration Store trades in database: ```python import sqlite3 def save_trade(trade_data): """Save trade to database""" conn = sqlite3.connect('trades.db') cursor = conn.cursor() cursor.execute(""" INSERT INTO trades (timestamp, action, asset, price, quantity, pnl) VALUES (?, ?, ?, ?, ?, ?) """, ( trade_data['timestamp'], trade_data['action'], trade_data['asset'], trade_data['price'], trade_data['quantity'], trade_data['pnl'] )) conn.commit() conn.close() ``` --- ## API Reference ### APIClient Class #### Methods **`get_markets(limit, cursor, **filters)`** - Fetch markets with pagination - Returns: `{"items": [...], "cursor": str, "has_more": bool}` **`get_market(contract_address)`** - Fetch single market - Returns: Market dict **`get_orders(limit, cursor, **filters)`** - Fetch orders with filters - Returns: `{"items": [...], "cursor": str, "has_more": bool}` **`place_order(market_id, asset, side, price, quantity)`** - Place limit order - Returns: Order dict **`cancel_order(order_id)`** - Cancel open order - Returns: Cancelled order dict **`get_current_price(asset)`** - Get current asset price - Returns: float or None ### Configuration Schema **Bot Section**: ```yaml bot: name: string mode: "paper" | "live" initial_capital: float update_interval: int (seconds) ``` **API Section**: ```yaml api: base_url: string (URL) api_key: string (evt_...) rate_limit: int (requests/min) timeout: int (seconds) ``` **Risk Section**: ```yaml risk: max_position_size: float (0-1) max_drawdown: float (0-1) stop_loss_pct: float (0-1) take_profit_pct: float (0-1) ``` --- ## Support & Resources ### Documentation - **Planning Document**: `TRADING-BOT-PLANNING.md` - **Skills Reference**: `TRADING-BOT-SKILLS.md` - **Agent Guide**: `agents/trading-bot-agent.md` - **API Documentation**: `API-V2-IMPLEMENTATION-SUMMARY.md` ### Example Configurations **Conservative (Low Risk)**: ```yaml risk: max_position_size: 0.10 # 10% max max_drawdown: 0.10 # 10% stop stop_loss_pct: 0.03 # 3% stops take_profit_pct: 0.06 # 6% targets ``` **Moderate (Balanced)**: ```yaml risk: max_position_size: 0.20 # 20% max max_drawdown: 0.15 # 15% stop stop_loss_pct: 0.05 # 5% stops take_profit_pct: 0.10 # 10% targets ``` **Aggressive (High Risk)**: ```yaml risk: max_position_size: 0.30 # 30% max max_drawdown: 0.20 # 20% stop stop_loss_pct: 0.08 # 8% stops take_profit_pct: 0.15 # 15% targets ``` ### Best Practices 1. **Always start in paper mode** 2. **Test for at least 1 week before live trading** 3. **Start with small capital** ($100-500) 4. **Monitor daily for first week** 5. **Keep stop-losses enabled** 6. **Don't override risk limits** 7. **Review logs regularly** 8. **Backup configuration files** 9. **Update strategies based on performance** 10. **Never risk more than you can afford to lose** --- ## Glossary **API Key**: Authentication credential for accessing the API **Drawdown**: Peak-to-trough decline in capital **Kelly Criterion**: Mathematical formula for optimal position sizing **Limit Order**: Order to buy/sell at specified price or better **Market Order**: Order to buy/sell immediately at market price **Paper Trading**: Simulated trading with fake money **Position**: Open trade in a market **RSI**: Relative Strength Index (momentum indicator) **MACD**: Moving Average Convergence Divergence (trend indicator) **Sharpe Ratio**: Risk-adjusted return metric **Slippage**: Difference between expected and actual execution price **Stop-Loss**: Automatic exit at loss threshold **Take-Profit**: Automatic exit at profit target **VaR**: Value at Risk (potential loss at confidence level) **Z-Score**: Standard deviations from mean --- **Document Version**: 1.0 **Last Updated**: November 21, 2025 **Status**: Production Ready **Support**: See project documentation --- **⚠️ Risk Disclaimer**: Trading involves risk. Past performance does not guarantee future results. Only trade with capital you can afford to lose. This software is provided as-is without warranties.