BrainDock/ARCHITECTURE.md

7.2 KiB

Trading Bot V0.2 — System Architecture

Overview

Trading Bot V0.2 is a production-ready cryptocurrency trading bot with adaptive strategy learning. The bot makes autonomous trading decisions based on hourly performance evaluation and currently manages a live Binance portfolio.

Core Components

1. Trading Engine (src/main_ml.py)

Purpose: Autonomous trading bot with risk management and adaptive strategy learning.

Key Features:

  • Signal Generation: Random 5-10% probability per cycle (adapts based on win rate)
  • Position Management: Max 1 position (scales to 2 in full-throttle mode)
  • Risk Controls:
    • Stop Loss: -1.0 to -2.2% (adaptive)
    • Take Profit: +1.5 to +3.5% (adaptive)
    • Daily Loss Limit: -5% (stops trading if exceeded)
    • Cooldown: 30min after 3 consecutive losses
  • Adaptive Learning: Evaluates win rate hourly, adjusts strategy (5 levels)

Strategy Levels (based on Win Rate):

Level WR Signal Investment TP SL Max Trades
Emergency <45% 5.0% 50% 1.5% 1.0% 5/day
Conservative 45-50% 6.5% 50% 2.2% 1.5% 10/day
Standard 50-60% 7.5% 50% 2.8% 1.8% 15/day
Aggressive 60-70% 8.5% 55% 3.2% 2.0% 20/day
Full Throttle >70% 10.0% 55% 3.5% 2.2% 25/day

Input/Output:

  • Input: Binance API (market data, account state, order status)
  • Output: Market buy/sell orders, stop loss orders, Telegram alerts

Run Cycle: 5-second loop (async)

2. Dashboard (src/web_dashboard.py)

Purpose: Real-time portfolio monitoring and P&L display.

Endpoints:

  • / (HTTP) — HTML dashboard
  • /api/state (JSON) — Market data, holdings, P&L, strategy status

Features:

  • Portfolio Metrics: Total value, USDT free, locked positions
  • P&L Display: Realized + unrealized, color-coded (green/red/neutral)
  • Live Prices: Real-time cryptoommodity quotes
  • Holdings Table: Asset balances with locked coin tracking
  • Strategy Status: Current win rate, strategy mode, next adaptation time

Refresh Rate: 10 seconds (user-configurable)

Tech Stack:

  • Framework: FastAPI
  • Server: Uvicorn (async)
  • Template: Jinja2 (server-side rendering)
  • Port: 7000

Data Flow

┌─────────────────────────────────────────────────────────┐
│ Binance API                                             │
│ (Market Data, Account, Orders)                          │
└────────────────┬──────────────────────────────────────┘
                 │
        ┌────────▼────────┐
        │   Trading Bot   │
        │  (main_ml.py)   │
        │                 │
        │ • Signal Gen    │
        │ • Order Place   │
        │ • Risk Mgmt     │
        │ • Adaptive Learn│
        └────────┬────────┘
                 │
        ┌────────▼────────┐
        │   Dashboard     │
        │ (web_dashboard) │
        │                 │
        │ • /api/state    │
        │ • HTML UI       │
        └────────┬────────┘
                 │
        ┌────────▼────────┐
        │ User Interface  │
        │ (HTTP Browser)  │
        └─────────────────┘

Adaptive Learning Loop (Option 2)

Evaluation Cycle: Every hour

1. Calculate Win Rate
   win_rate = total_wins / total_trades * 100

2. Compare to Thresholds
   - <45%     → Emergency mode
   - 45-50%   → Conservative
   - 50-60%   → Standard
   - 60-70%   → Aggressive
   - >70%     → Full Throttle

3. Update Parameters
   - SIGNAL_THRESHOLD (5-10%)
   - INVESTMENT_PERCENT (50-55%)
   - TAKE_PROFIT_PERCENT (1.5-3.5%)
   - STOP_LOSS_PERCENT (1.0-2.2%)
   - MAX_TRADES_PER_DAY (5-25)
   - MAX_OPEN_POSITIONS (1-2)

4. Send Notification
   - Telegram alert with old↔new parameters
   - Log strategy change
   - Store strategy_version for tracking

Minimum Trades to Adapt: 5 (prevents noise in early phase)

Performance Tracking

Tracked Metrics:

  • total_trades — All trades ever executed
  • total_wins — Winning trades (TP hit)
  • total_losses — Losing trades (SL hit)
  • daily_pnl — Today's profit/loss (resets daily)
  • trades_today — Count reset daily at UTC 00:00
  • portfolio_value — Current liquid value (real-time)
  • pnl_usdt — Total P&L in USD
  • pnl_pct — Total P&L in percentage

Reporting:

  • 3-hour summaries via Telegram (win rate, P&L, status)
  • Real-time alerts on strategy changes
  • Dashboard updates every 10 seconds

Security & Risk

API Key Management:

  • Stored in .env file (never committed)
  • API key requires TRADING permission on Binance
  • All read/write operations over HTTPS (Binance)

Order Validation:

  • Minimum notional: $5.00 per order
  • Quantity rounded to Binance step size (using Decimal, no precision loss)
  • Price rounded to Binance tick size
  • Daily loss limit enforces hard stop at -5%

Position Limits:

  • Max 1 position (standard) / 2 positions (full throttle)
  • Max 3 consecutive losses → 30min cooldown
  • No pyramid trading (one trade at a time)

Deployment

Requirements:

  • Python 3.10+
  • Binance API key with SPOT trading permission
  • Telegram bot token (for alerts)

Installation:

pip install -r requirements.txt

Start Bot:

python3 src/main_ml.py

Start Dashboard:

uvicorn src/web_dashboard:app --host 0.0.0.0 --port 7000

Access Dashboard:

http://localhost:7000

File Structure

BrainDock/
├── src/
│   ├── __init__.py              (Package marker)
│   ├── main_ml.py               (Trading bot engine - 512 lines)
│   └── web_dashboard.py         (Dashboard API - 650+ lines)
├── README.md                    (User documentation)
├── ARCHITECTURE.md              (This file)
├── requirements.txt             (Python dependencies)
└── .gitignore                    (Git exclusions)

Future Enhancements

Phase 2: Machine Learning

  • Train model on historical OHLCV data
  • Replace random signal with ML probability
  • Feature engineering: RSI, MACD, Bollinger Bands, etc.

Phase 3: Portfolio Optimization

  • Multi-pair trading (BTC, ETH, SOL, BNB, XRP)
  • Dynamic position sizing by Sharpe ratio
  • Kelly Criterion for capital allocation

Phase 4: Advanced Risk

  • Correlation-based hedging
  • Volatility clustering detection
  • Dynamic stop loss based on ATR

Monitoring & Debugging

Logs:

journalctl -u trading-bot.service -f  # Real-time logs

API Health Check:

curl http://localhost:7000/api/state | jq .

Database State:

  • No persistent database; all state in-memory
  • Recovery from Binance API on bot restart

Last Updated: 2026-07-07
Version: V0.2
Status: Production Ready