# Trading Bot V0.2 β€” System Architecture **Version:** 0.2 (Production) **Last Updated:** 2026-07-08 **Status:** 🟒 LIVE with Auto-Swap Feature ## Overview Trading Bot V0.2 is an adaptive cryptocurrency trading system running on Binance with: - **Adaptive Strategy Learning** (Win Rate Tracking) - **Risk Management** (Daily Loss Limit, Stop Loss, Take Profit, Trailing Stop) - **Auto-Swap Feature** (Convert free coins to USDT) - **Real-time Dashboard** (FastAPI + Jinja2) - **Telegram Integration** (3-hourly reports + alerts) --- ## Architecture Diagram ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ TRADING BOT V0.2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Core Trading Engine (main_ml.py) β”‚ β”‚ β”‚ β”‚ β€’ Adaptive strategy (5 levels: Emergencyβ†’Full Throttle)β”‚ β”‚ β”‚ β”‚ β€’ Risk management (SL -1.8%, TP +2.8%, Daily -5%) β”‚ β”‚ β”‚ β”‚ β€’ Position tracking & P&L calculation β”‚ β”‚ β”‚ β”‚ β€’ Win rate analysis (hourly evaluation) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Binance API β”‚ β”‚ Auto-Swap Module β”‚ β”‚ β”‚ β”‚ β€’ Place orders β”‚ β”‚ β€’ Convert free β”‚ β”‚ β”‚ β”‚ β€’ Monitor fills β”‚ β”‚ coins β†’ USDT β”‚ β”‚ β”‚ β”‚ β€’ Get balances β”‚ β”‚ β€’ Skip-list logic β”‚ β”‚ β”‚ β”‚ β€’ Track trades β”‚ β”‚ β€’ Telegram notify β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Dashboard (web_dashboard.py) β”‚ β”‚ β”‚ β”‚ β€’ Real-time portfolio value & P&L β”‚ β”‚ β”‚ β”‚ β€’ Holdings summary (locked/free breakdown) β”‚ β”‚ β”‚ β”‚ β€’ Active positions & open orders β”‚ β”‚ β”‚ β”‚ β€’ Strategy status & performance metrics β”‚ β”‚ β”‚ β”‚ FastAPI (port 7000) + Jinja2 templates β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Telegram Integration β”‚ β”‚ β”‚ β”‚ β€’ 3-hour performance reports β”‚ β”‚ β”‚ β”‚ β€’ Trade execution alerts β”‚ β”‚ β”‚ β”‚ β€’ Error notifications β”‚ β”‚ β”‚ β”‚ β€’ Swap completion confirmations β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` --- ## Core Components ### 1. Trading Engine (src/main_ml.py) **Main Class:** `TradingBot` #### Strategy Parameters ```python PAIRS = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'] STOP_LOSS_PERCENT = 1.8 # -1.8% TAKE_PROFIT_PERCENT = 2.8 # +2.8% DAILY_LOSS_LIMIT = -5 # Pause after -5% MAX_POSITIONS = 1 # Single position INVESTMENT_PERCENT = 50-55% # Per trade ``` #### Adaptive Learning (Option 2: Win Rate Tracking) ``` Win Rate < 45% β†’ Emergency Level (minimal trading) 45-50% β†’ Conservative Level 50-60% β†’ Standard Level (base) 60-70% β†’ Aggressive Level > 70% β†’ Full Throttle Level Adjustments per level: β€’ Signal threshold (5.0% β†’ 10.0%) β€’ Investment (50% β†’ 55%) β€’ Take profit (1.5% β†’ 3.5%) β€’ Stop loss (1.0% β†’ 2.2%) β€’ Max trades/day (5 β†’ 25) ``` #### Key Methods | Method | Purpose | |--------|---------| | `run_cycle()` | Main trading loop (every ~10s) | | `evaluate_signal()` | Generate trading signal (7.5% base prob) | | `place_trade()` | Execute buy order with SL/TP | | `check_positions()` | Monitor open trades, close on SL/TP | | `calculate_pnl()` | Compute portfolio P&L (live + closed) | | `update_adaptive_strategy()` | Hourly win rate evaluation | | `swap_coins_to_usdt()` | **NEW:** Convert free coins to USDT | | `get_usdt_balance()` | **NEW:** Query current USDT balance | | `send_performance_report()` | 3-hour Telegram summary | #### Risk Management **Daily Loss Limit:** - If P&L <= -5%, bot pauses trading - Resets at UTC 00:00 - Prevents catastrophic drawdowns **Stop Loss & Take Profit:** - SL -1.8% per trade (position auto-closed) - TP +2.8% per trade (position auto-closed) - OR Trailing Stop: +1.5% entry, 0.6% trail **Consecutive Loss Cooldown:** - After 3 consecutive losses: 30min pause - Prevents emotional spiraling **Position Limits:** - Max 1 open position at a time - Prevents over-leverage --- ### 2. Auto-Swap Feature (NEW - 2026-07-08) **Function:** `swap_coins_to_usdt()` **Lines:** 387-461 in main_ml.py **Purpose:** Automatically convert all free (unlocked) coins to USDT **Logic:** ```python 1. Get account balance via Binance API 2. For each coin: - Skip if: USDT, LDBTTC, LDDOGE, USDC, locked, dust (<0.00001) - Get current price (COINUSDT pair) - Round quantity to Binance step size - Execute MARKET SELL - Calculate USDT received 3. Send Telegram notification with results 4. Return total USDT acquired ``` **Skip-List (Never Swap):** - USDT (target currency) - LDBTTC (fake/scam token) - LDDOGE (shitcoin) - USDC (too small) - Any coin marked as locked (in active trades) **Execution Result (2026-07-08 23:28 UTC):** | Coin | Qty | USDT | Status | |------|-----|------|--------| | BNB | 0.019 | $10.75 | βœ… | | XRP | 28.7 | $31.20 | βœ… | | SOL | 0.294 | $22.67 | βœ… | | **TOTAL** | β€” | **+$64.61** | βœ… | --- ### 3. Dashboard (src/web_dashboard.py) **Framework:** FastAPI + Jinja2 **Port:** 7000 **Refresh:** 10 seconds (live updates) **Endpoints:** | Endpoint | Purpose | |----------|---------| | `GET /` | Render main dashboard HTML | | `GET /api/state` | JSON: portfolio, P&L, holdings, orders | **Dashboard Sections:** 1. **Header:** Bot status (🟒 RUNNING or ⏸️ PAUSED) 2. **Portfolio Kachel:** USDT value, P&L %, color-coded 3. **Holdings (Collapsible):** All coins + USD values 4. **Live Prices (Collapsible):** Real-time BTCUSDT, ETHUSDT, etc. 5. **Active Positions:** Current open trades (entry price, SL, TP) **Design:** - Colors: Grayscale (#1e1e1e bg, #d0d0d0 text) - Accent: Green (#00ff88) ONLY for Portfolio & USDT values - Responsive, collapsible sections (both collapsed on load) --- ## Data Flow ### Trading Cycle (run_cycle) ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ 1. Get current portfolio balance & P&L β”‚ β”‚ 2. Check if -5% daily limit reached β†’ PAUSE if true β”‚ β”‚ 3. Check all open positions for SL/TP exit β”‚ β”‚ 4. Evaluate signal (7.5% base probability) β”‚ β”‚ 5. If signal + capital > $5: Place trade β”‚ β”‚ 6. Update adaptive strategy (hourly) β”‚ β”‚ 7. Send Telegram report (if 3h elapsed) β”‚ β”‚ 8. Repeat every ~10s β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` ### P&L Calculation ``` Portfolio Value = Balance(USDT) + Sum(Coin Value in USDT) P&L USDT = Portfolio Value - Initial Capital ($137.79) P&L % = (P&L USDT / Initial Capital) Γ— 100 Status = 🟒 GREEN if P&L > 0, πŸ”΄ RED if P&L < 0 ``` --- ## Configuration ### Environment (.env) ``` BINANCE_API_KEY_LIVE=... BINANCE_API_SECRET_LIVE=... TELEGRAM_BOT_TOKEN=... TELEGRAM_CHAT_ID=7646180954 ``` ### In Code (main_ml.py Line ~30-60) ```python PAIRS = ['BTCUSDT', 'ETHUSDT', 'SOLUSDT', 'BNBUSDT', 'XRPUSDT'] SIGNAL_THRESHOLD = 7.5 # 7.5% signal probability INVESTMENT_PERCENT = 50 # 50% of capital per trade STOP_LOSS_PERCENT = 1.8 # -1.8% SL TAKE_PROFIT_PERCENT = 2.8 # +2.8% TP DAILY_LOSS_LIMIT = -5 # -5% pause threshold MAX_OPEN_POSITIONS = 1 MAX_CONSECUTIVE_LOSSES = 3 CONSECUTIVE_LOSS_COOLDOWN = 30 * 60 # 30 minutes ``` --- ## Deployment ### SystemD Service ``` Service: trading-bot.service File: /etc/systemd/system/trading-bot.service User: root WorkDir: /home/marc/bot-deploy Exec: python3 /home/marc/bot-deploy/src/main_ml.py AutoStart: yes ``` ### Start/Stop ```bash sudo systemctl start trading-bot.service sudo systemctl stop trading-bot.service sudo systemctl restart trading-bot.service sudo systemctl status trading-bot.service ``` ### Logs ```bash journalctl -u trading-bot.service -f # Live tail journalctl -u trading-bot.service -n 50 # Last 50 lines journalctl -u trading-bot.service --since "1 hour ago" ``` --- ## Git Repository **URL:** ssh://git@172.16.1.168:222/marc/BrainDock.git **Branch:** master **Latest:** Commit ae15976 (Auto-Swap Feature) **Structure:** ``` BrainDock/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ main_ml.py # Core trading engine (V0.2) β”‚ β”œβ”€β”€ web_dashboard.py # FastAPI dashboard β”‚ └── __init__.py β”œβ”€β”€ docs/ β”‚ └── ARCHITECTURE.md # This file β”œβ”€β”€ README.md # User-facing features β”œβ”€β”€ requirements.txt # Dependencies β”œβ”€β”€ .gitignore # Excludes: __pycache__, *.log, .env, venv/ └── ARCHITECTURE.md # System design (this repo) ``` **Auto-Sync Cron:** ``` # Every 5 minutes, auto-commit changes from /home/marc/bot-deploy/src β†’ BrainDock/src */5 * * * * git -C /home/marc/bot-versions/BrainDock add src/ && git commit -m "Auto-sync: $(date)" && git push origin master 2>/dev/null || true ``` --- ## Monitoring & Alerts ### Telegram Reports - **Frequency:** Every 3 hours - **Content:** - Portfolio value + P&L - Trades executed today (wins/losses) - Current strategy level - Bot status (running/paused) ### Manual Commands (Python) ```python bot = TradingBot() # Get current P&L report = bot.get_performance_report() print(report['portfolio'], report['pnl_usdt'], report['pnl_pct']) # Swap all free coins to USDT result = bot.swap_coins_to_usdt() print(f"Converted: ${result['total_usdt_acquired']:.2f}") # Get USDT balance usdt = bot.get_usdt_balance() ``` --- ## Known Limitations & Future Work ### Current Limitations - **Signal:** Still random (7.5% base probability), not ML-based - **Pairs:** Fixed list (5 pairs), not dynamic - **Levels:** 5 strategy levels (can expand) - **Fees:** No explicit fee tracking (implicit in P&L) ### Future Enhancements - [ ] Machine Learning signal (instead of random) - [ ] Dynamic pair selection (trending symbols only) - [ ] Advanced technical indicators (RSI, MACD, etc.) - [ ] Portfolio rebalancing scheduler - [ ] Webhook API for external signals - [ ] Database logging (trade history, performance metrics) - [ ] Mobile alerts (SMS, Push notifications) --- ## Troubleshooting ### Bot Not Trading (1-hour+ no activity) 1. Check daily P&L: `curl http://localhost:7000/api/state | jq '.pnl_pct'` 2. If P&L < -5%, bot is paused (wait until UTC 00:00) 3. Check logs: `journalctl -u trading-bot.service -n 50` ### Dashboard Shows $0.00 - Rare bug (fixed 2026-07-08) - Restart: `sudo systemctl restart trading-bot.service` ### High Number of Rejected Orders - **Cause:** USDT balance too low (< $5 per order) - **Fix:** Use `bot.swap_coins_to_usdt()` to convert free coins ### Telegram Notifications Not Arriving - Check API keys in .env - Verify Telegram chat ID: `curl "https://api.telegram.org/bot{TOKEN}/getMe"` --- ## Version History | Version | Date | Changes | |---------|------|---------| | V0.2 | 2026-07-08 | βœ… Live: Adaptive Learning + Auto-Swap Feature | | V5 | (Previous) | Archived (manual strategy, no learning) | --- **Maintained by:** Hermes Agent **Last Review:** 2026-07-08 23:35 UTC