Skip to content

A multi-agent AI trading system using LLMs to optimize strategies and adapt to market conditions in real-time.

License

Notifications You must be signed in to change notification settings

syntax-syndicate/LLM-TradeBot

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

35 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿค– LLM-TradeBot

English ็ฎ€ไฝ“ไธญๆ–‡

Adversarial Intelligence Framework

Intelligent Multi-Agent Quantitative Trading Bot based on the Adversarial Decision Framework (ADF). Achieves high win rates and low drawdown in automated futures trading through market regime detection, price position awareness, dynamic score calibration, and multi-layer physical auditing.

Python License Framework X Follow


โœจ Key Features

  • ๐Ÿ•ต๏ธ Perception First: Unlike strict indicator-based systems, this framework prioritizes judging "IF we should trade" before deciding "HOW to trade".
  • ๐Ÿค– Multi-Agent Collaboration: 4 highly specialized Agents operating independently to form an adversarial verification chain.
  • โšก Async Concurrency: Currently fetches multi-timeframe data (5m/15m/1h) concurrently, ensuring data alignment at the snapshot moment.
  • ๐Ÿ›ก๏ธ Safety First: Stop-loss direction correction, capital pre-rehearsal, and veto mechanisms to safeguard live trading.
  • ๐Ÿ“Š Full-Link Auditing: Every decision's adversarial process and confidence penalty details are recorded, achieving true "White-Box" decision-making.

๐Ÿš€ Quick Start

Startup Flow

Quick Start Flow

Detailed Steps

1. Install Dependencies

pip install -r requirements.txt

2. Configure Environment

# Copy environment variable template
cp .env.example .env

# Set API Keys
./set_api_keys.sh

3. Configure Trading Parameters

# Copy config template
cp config.example.yaml config.yaml

Edit config.yaml to set parameters:

  • Trading pair (symbol)
  • Max position size (max_position_size)
  • Leverage (leverage)
  • Stop loss/Take profit % (stop_loss_pct, take_profit_pct)

4. Start Web Dashboard (Recommended)

Dashboard Preview Live Log Output Built-in modern real-time monitoring dashboard.

# Start main program (automatically starts Web server)
python main.py --mode continuous

After startup, visit: http://localhost:8000

Dashboard Features:

  • ๐Ÿ“‰ Real-time K-Line: Integrated TradingView widget, 1-minute real-time updates
  • ๐Ÿ“ˆ Net Value Curve: Real-time equity tracking
  • ๐Ÿ“‹ Decision Audit: Full history of decision records, including detailed Agent scores (Strategist, Trend, Oscillator, Sentiment)
  • ๐Ÿ“œ Trade History: Complete record of all trades and PnL statistics
  • ๐Ÿ“ก Live Log Output: Real-time scrolling logs with highlighted Agent tags (Oracle, Strategist, Critic, Guardian), 500-line history buffer

๐Ÿ“ Project Structure

Directory Tree

Project Structure

Directory Description

LLM-TradeBot/
โ”œโ”€โ”€ src/                    # Core Source Code
โ”‚   โ”œโ”€โ”€ agents/            # Multi-Agent Definitions (DataSync, Quant, Decision, Risk)
โ”‚   โ”œโ”€โ”€ api/               # Binance API Client
โ”‚   โ”œโ”€โ”€ data/              # Data Processing (processor, validator)
โ”‚   โ”œโ”€โ”€ execution/         # Order Execution Engine
โ”‚   โ”œโ”€โ”€ features/          # Feature Engineering
โ”‚   โ”œโ”€โ”€ monitoring/        # Monitoring & Logging
โ”‚   โ”œโ”€โ”€ risk/              # Risk Management
โ”‚   โ”œโ”€โ”€ strategy/          # LLM Decision Engine
โ”‚   โ””โ”€โ”€ utils/             # Utilities (DataSaver, TradeLogger, etc.)
โ”‚
โ”œโ”€โ”€ docs/                  # Documentation
โ”‚   โ”œโ”€โ”€ data_flow_analysis.md          # Data Flow Analysis
โ”‚   โ””โ”€โ”€ *.png                          # Architecture & Flow Diagrams
โ”‚
โ”œโ”€โ”€ data/                  # Structured Data Storage (Archived by Date)
โ”‚   โ”œโ”€โ”€ market_data/       # Raw K-Line Data
โ”‚   โ”œโ”€โ”€ indicators/        # Technical Indicators
โ”‚   โ”œโ”€โ”€ features/          # Feature Snapshots
โ”‚   โ”œโ”€โ”€ decisions/         # Final Decision Results
โ”‚   โ””โ”€โ”€ execution/         # Execution Records
โ”‚
โ”œโ”€โ”€ logs/                  # System Runtime Logs
โ”œโ”€โ”€ tests/                 # Unit Tests
โ”œโ”€โ”€ config/                # Configuration Files
โ”‚
โ”œโ”€โ”€ main.py                # Main Entry Point (Multi-Agent Loop)
โ”œโ”€โ”€ config.yaml            # Trading Parameters
โ”œโ”€โ”€ .env                   # API Key Configuration
โ””โ”€โ”€ requirements.txt       # Python Dependencies

๐ŸŽฏ Core Architecture

Adversarial Multi-Agent Workflow

  1. ๐Ÿ•ต๏ธ DataSyncAgent (The Oracle)

    • Role: Unified Data Provider.
    • Action: Asynchronously fetches and aligns multi-timeframe K-lines (5m, 15m, 1h) and external quant data (Netflow, LSR) to ensure a consistent market snapshot.
  2. ๐Ÿ‘จโ€๐Ÿ”ฌ QuantAnalystAgent (The Strategist)

    • Role: Signal Generator (Technical Analysis).
    • Composition:
      • TrendSubAgent: Analyzes EMA/MACD across timeframes.
      • OscillatorSubAgent: Detects reversal zones using RSI/Bollinger Bands.
      • SentimentSubAgent: Incorporates external data like Funding Rates and Open Interest.
    • Output: A raw comprehensive score and detailed sub-signal breakdown.
  3. ๐Ÿ”ฎ PredictAgent (The Prophet)

    • Role: Future Predictor (ML Model).
    • Action:
      • Uses LightGBM machine learning model trained on historical data.
      • Analyzes 50+ technical features to predict price direction for the next 30 minutes.
      • Supports auto-retraining (every 2h) to adapt to changing market conditions.
    • Output: Probability of price increase (P_Up) and confidence score.
  4. โš–๏ธ DecisionCoreAgent (The Critic)

    • Role: Adversarial Judge.
    • Action:
      • Contextualization: Uses RegimeDetector to identify market state (Trending/Choppy) and PositionAnalyzer to locate price relative to history.
      • Integration: Combines Strategist's technical signals with Prophet's ML predictions.
      • Weighted Voting: Re-evaluates granular signals with dynamic weights adapted to the current regime.
      • Output: The final trading intent (Long/Short/Wait) with a confidence score.
  5. ๐Ÿ›ก๏ธ RiskAuditAgent (The Guardian)

    • Role: Risk Controller.
    • Action: Physically independent audit layer. Checks Max Drawdown protection, R/R requirements, and exposure limits. Has Veto Power to block high-risk trades regardless of high confidence.
  6. ๐Ÿš€ ExecutionEngine

    • Role: Sniper.
    • Action: Precision execution within the closing seconds of the candle, handling order lifecycle and state updates.

Collaboration Sequence

Multi-Agent Sequence

Data Flow Architecture

Data Flow Architecture

Architecture Details:

  1. Data Collection Layer (Blue): DataSyncAgent async concurrent collection
  2. Quant Analysis Layer (Green): QuantAnalystAgent with 3 parallel Sub-Agents
  3. Prediction Layer (Magenta): PredictAgent with LightGBM ML model
  4. Decision Adversarial Layer (Orange): DecisionCoreAgent with regime-aware weighted voting
  5. Risk Audit Layer (Red): RiskAuditAgent final check and auto-correction
  6. Execution Layer (Purple): ExecutionEngine order execution
  7. Visualization Layer: Recent Decisions table showing full Agent data (16 columns)

Detailed Flowchart

graph TB
    subgraph "1๏ธโƒฃ Data Collection Layer"
        A[๐Ÿ•ต๏ธ DataSyncAgent] --> MS[MarketSnapshot<br/>5m/15m/1h + External Data]
    end
    
    subgraph "2๏ธโƒฃ Quant Analysis Layer"
        MS --> QA[๐Ÿ‘จโ€๐Ÿ”ฌ QuantAnalystAgent]
        QA --> TS[TrendSubAgent]
        QA --> OS[OscillatorSubAgent]
        QA --> SS[SentimentSubAgent]
        TS & OS & SS --> QR[quant_analysis]
    end

    subgraph "3๏ธโƒฃ Prediction Layer"
        MS --> PA[๐Ÿ”ฎ PredictAgent]
        PA --> ML[LightGBM Model<br/>Auto-Train 2h]
        ML --> PR[Prediction<br/>P_Up, Conf]
    end
    
    subgraph "4๏ธโƒฃ Decision Adversarial Layer"
        QR & PR --> DC[โš–๏ธ DecisionCoreAgent<br/>Weighted Voting]
        DC --> RD[RegimeDetector]
        DC --> POS[PositionAnalyzer]
        RD & POS --> VR[VoteResult<br/>Action, Conf]
    end
    
    subgraph "5๏ธโƒฃ Risk Audit Layer"
        VR --> RA[๐Ÿ›ก๏ธ RiskAuditAgent<br/>Veto Power]
        RA --> AR[AuditResult<br/>Risk, Guard]
    end
    
    subgraph "6๏ธโƒฃ Execution Layer"
        AR --> EE[๐Ÿš€ ExecutionEngine]
    end
    
    style A fill:#4A90E2,color:#fff
    style QA fill:#7ED321,color:#fff
    style PA fill:#BD10E0,color:#fff
    style DC fill:#F5A623,color:#fff
    style RA fill:#D0021B,color:#fff
    style EE fill:#9013FE,color:#fff
Loading

๐Ÿ“– Detailed Docs: See Data Flow Analysis for complete mechanisms.


๐Ÿ“„ Full-Link Data Auditing

Data Storage Structure

Data Storage Hierarchy

Storage Organization

The system automatically records intermediate processes for each cycle in the data/ directory, organized by date for easy review and debugging:

data/
โ”œโ”€โ”€ market_data/           # Raw Multi-Timeframe K-Lines
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ”œโ”€โ”€ BTCUSDT_5m_{timestamp}.json
โ”‚       โ”œโ”€โ”€ BTCUSDT_5m_{timestamp}.csv
โ”‚       โ”œโ”€โ”€ BTCUSDT_5m_{timestamp}.parquet
โ”‚       โ”œโ”€โ”€ BTCUSDT_15m_{timestamp}.json
โ”‚       โ””โ”€โ”€ BTCUSDT_1h_{timestamp}.json
โ”‚
โ”œโ”€โ”€ indicators/            # Full Technical Indicators DataFrames
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ”œโ”€โ”€ BTCUSDT_5m_{snapshot_id}.parquet
โ”‚       โ”œโ”€โ”€ BTCUSDT_15m_{snapshot_id}.parquet
โ”‚       โ””โ”€โ”€ BTCUSDT_1h_{snapshot_id}.parquet
โ”‚
โ”œโ”€โ”€ features/              # Feature Snapshots
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ”œโ”€โ”€ BTCUSDT_5m_{snapshot_id}_v1.parquet
โ”‚       โ”œโ”€โ”€ BTCUSDT_15m_{snapshot_id}_v1.parquet
โ”‚       โ””โ”€โ”€ BTCUSDT_1h_{snapshot_id}_v1.parquet
โ”‚
โ”œโ”€โ”€ context/               # Quant Analysis Summary
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ””โ”€โ”€ BTCUSDT_quant_analysis_{snapshot_id}.json
โ”‚
โ”œโ”€โ”€ llm_logs/              # LLM Input Context & Voting Process
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ””โ”€โ”€ BTCUSDT_{snapshot_id}.md
โ”‚
โ”œโ”€โ”€ decisions/             # Final Weighted Vote Results
โ”‚   โ””โ”€โ”€ {date}/
โ”‚       โ””โ”€โ”€ BTCUSDT_{snapshot_id}.json
โ”‚
โ””โ”€โ”€ execution/             # Execution Tracking
    โ””โ”€โ”€ {date}/
        โ””โ”€โ”€ BTCUSDT_{timestamp}.json

Data Formats

  • JSON: Human-readable, used for configuration and decision results
  • CSV: High compatibility, easy for Excel import
  • Parquet: Efficient compression, used for large-scale time-series data

๐Ÿ›ก๏ธ Safety Warning

โš ๏ธ Important Safety Measures:

  1. API Keys: Keep them safe, DO NOT commit to version control.
  2. Test First: Use --test argument to run simulations first.
  3. Risk Control: Set reasonable stop-loss and position limits in config.yaml.
  4. Minimal Permissions: Grant only necessary Futures Trading permissions to API keys.
  5. Monitoring: Regularly check the logs/ directory for anomalies.

๐Ÿ“š Documentation Navigation

Document Description
README.md Project Overview & Quick Start
Data Flow Analysis Complete Data Flow Mechanisms
API Key Guide API Key Configuration Guide
Config Example Trading Parameters Template
Env Example Environment Variables Template

๐ŸŽ‰ Latest Updates

2025-12-23:

  • โœ… Trade History Enhanced: Added Open/Close Cycle columns, PnL % with color indicators.
  • โœ… Net Value Curve: Dashed initial capital baseline with centered Y-axis logic.
  • โœ… Decision Table Refactor: Removed Active PnL column, added tooltip for Guardian block reasons.
  • โœ… Strategy Improvements: Added add_position action for "buy the dip", confidence calibration rules.
  • โœ… Documentation: Translated dashboard agent descriptions to English.

2025-12-21:

  • โœ… ML Model Upgrade: Upgraded PredictAgent to use LightGBM machine learning model.
  • โœ… Auto-Training: Implemented automatic model retraining every 2 hours to adapt to market drifts.
  • โœ… Dashboard Refinement: Enhanced dashboard with auto-scrolling logs, robust scrollbars, and ML probability display.
  • โœ… Cycle Optimization: Optimized decision cycle to 3 minutes for faster response.

2025-12-20:

  • โœ… Adversarial Decision Framework: Introduced PositionAnalyzer and RegimeDetector.
  • โœ… Confidence Score Refactor: Implemented dynamic confidence penalties.
  • โœ… Documentation Optimization: Updated README to highlight adversarial architecture.
  • โœ… Project Renamed: Officially renamed to LLM-TradeBot.
  • โœ… Full-Link Auditing: Implemented complete intermediate state archiving.

๐Ÿค Contribution

Issues and Pull Requests are welcome!


This project is licensed under the GNU Affero General Public License v3.0. See the LICENSE file for details.


Empowered by AI, Focused on Precision, Starting a New Era of Intelligent Quant! ๐Ÿš€

About

A multi-agent AI trading system using LLMs to optimize strategies and adapt to market conditions in real-time.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 88.1%
  • JavaScript 5.1%
  • HTML 2.7%
  • CSS 2.3%
  • Shell 1.8%