Alpha Arena

repository·main·Indexed 20 days ago

https://github.com/amadeusgb/alpha-arena

An experimental trading platform (v0.1.0) designed to test and compare AI agents (LLMs) such as GPT, Claude, and Gemini in real-world market conditions. It features an Orchestrator for scheduling, an LLM Gateway for unified model interfacing, and an Exchange Adapter supporting paper-trading and Bitget spot trading. The system enforces strict risk controls, including a 20% NAV order limit, a -5% liquidation threshold, and a 10% drawdown kill-switch.

Tokens
2.8K
Snippets
9
Records
13
Agent score
71%

What's inside alpha-arena

  1. System Architecture and Module Responsibilities

    main

    Alpha Arena is organized into several core services within the /arena-mvp directory:

    • Orchestrator: The central scheduler. Every 5 minutes, it fetches the last 60 minutes of K-line data and current order book snapshots for two symbols, generates a unified Prompt, requests LLMs in parallel, validates the JSON schema, and passes the decision to the risk/execution layer.
    • LLM Gateway: Provides a unified interface for different LLMs (OpenAI, DeepSeek, Anthropic, Google, etc.), handling requests, retries, rate limiting, and timeouts (default 8s timeout results in a HOLD decision).
    • Exchange Adapter: Handles market interaction. It supports paper-trading (simulated matching with fixed slippage) and can be switched to Bitget spot trading.
    • Portfolio: Manages independent asset ledgers for each model, tracking cash, positions, and floating PnL, applying unified fees and slippage.
    • Dashboard: A visualization layer (Streamlit or React) for monitoring Net Value curves, PnL, positions, trades, latency, and error rates.

    Storage Layer:

    • PostgreSQL: Stores trades, K-lines, model outputs, executions, and assets.
    • Redis: Used for short-term queues, deduplication, and rate limiting.
  2. Risk Control and Execution Rules

    main

    The platform enforces the following trading and risk constraints:

    • Initial Capital: $10,000 USDT per model.
    • Order Size: Maximum 20% of Net Asset Value (NAV) per trade.
    • Position Limit: Maximum of 1 open symbol at a time.
    • Stop Loss/Take Profit: Provided by the model, but the system enforces a hard liquidation threshold at -5%.
    • Fees & Slippage: 0.05% (5 bp) fee; 10 bp slippage (in paper-trading).
    • Decision Cadence: 5 minutes (only one new decision allowed per 5m window).
    • Timeout Handling: If an LLM fails to respond within 8 seconds, the system defaults to a HOLD action.
    • Kill-Switch: If Net Value drawdown exceeds 10%, the system immediately stops, flattens all positions, and disables new orders.
  3. Understand Alpha Arena Project Structure

    main

    The project is organized into core logic, adapters for external services, and a main entry point:

    • core/: Contains the primary business logic.
      • market.py: Manages market data.
      • decision.py: The decision engine.
    • adapters/: Implements interfaces for external services.
      • llm_base.py: Base class for Large Language Models.
      • openai_adapter.py: Adapter for OpenAI.
      • claude_adapter.py: Adapter for Anthropic Claude.
      • exchange_api.py: Adapter for exchange APIs (Bitget).
    • main.py: The main application entry point.
    • requirements.txt: List of Python dependencies.
    • env.example: Template for environment variables.
    alpha-arena/
    ├── core/
    │   ├── market.py
    │   └── decision.py
    ├── adapters/
    │   ├── llm_base.py
    │   ├── openai_adapter.py
    │   ├── claude_adapter.py
    │   └── exchange_api.py
    ├── main.py
    ├── requirements.txt
    └── env.example
  4. Quickstart Alpha Arena MVP

    main

    To run the minimal MVP (which includes real-time price fetching and comparison of OpenAI vs Claude decisions), follow these steps:

    1. Clone the repository.
    2. Install dependencies via pip.
    3. Configure your API keys in a .env file.
    4. Execute the main entry point.

    Note: The current version is v0.1.0.

    # 1. 克隆项目
    git clone https://github.com/AmadeusGB/alpha-arena.git
    cd alpha-arena
    
    # 2. 安装依赖
    pip install -r requirements.txt
    
    # 3. 配置API密钥
    cp env.example .env
    # 编辑.env文件,填入你的API密钥
    
    # 4. 运行程序
    python main.py
  5. Install and Setup Alpha Arena

    main

    To run the Alpha Arena MVP, ensure you have Python 3.8+ installed. Follow these steps to clone the repository, install dependencies, and configure your environment.

    1. Clone the repository

    git clone https://github.com/AmadeusGB/alpha-arena.git
    cd alpha-arena

    2. Install dependencies

    pip install -r requirements.txt

    3. Configure API Keys

    Alpha Arena requires API keys for OpenAI and Anthropic to power its decision engine. Use the provided template to create your .env file:

    cp env.example .env

    Then, edit the .env file and populate the following keys:

    • OPENAI_API_KEY
    • ANTHROPIC_API_KEY
    # Clone and install
    git clone https://github.com/AmadeusGB/alpha-arena.git
    cd alpha-arena
    pip install -r requirements.txt
    
    # Setup environment
    cp env.example .env
    # Edit .env with your keys
    
    # Run the application
    python main.py
  6. Run Alpha Arena

    main

    Once the environment is configured, execute the main entry point to start the market data retrieval and AI decision process.

    python main.py

    To enable detailed logging for debugging, set the DEBUG environment variable to 1 before running:

    export DEBUG=1
    python main.py
    python main.py
  7. Key Configuration Parameters

    main

    The following parameters govern the behavior of the Alpha Arena environment:

    ParameterDefault Value
    Decision Cycle5m
    SymbolsBTCUSDT, ETHUSDT (spot)
    Initial Capital$10,000 / model
    Max Single Order20% NAV
    Trading Fee0.05% (5 bp) (paper)
    Slippage10 bp (paper)
    Liquidation Threshold-5%
    LLM Timeout8s (results in HOLD)
    ConcurrencyParallel per model, serial database writes
  8. Configure Environment Variables

    main

    Alpha Arena uses python-dotenv for configuration. You must provide valid API keys in a .env file located in the project root.

    Required keys:

    • OPENAI_API_KEY: Your OpenAI API key for GPT-4 access.
    • ANTHROPIC_API_KEY: Your Anthropic API key for Claude-3-Sonnet access.

    If these are missing, the application will fail with an error similar to: ❌ OpenAI API密钥未设置,请设置OPENAI_API_KEY环境变量

    # .env file content example
    OPENAI_API_KEY=your_openai_api_key_here
    ANTHROPIC_API_KEY=your_anthropic_api_key_here
  9. Run the Alpha Arena MVP orchestrator

    main

    The main.py file serves as the entrypoint for the Alpha Arena MVP, a system designed to compare AI trading decisions from different LLM providers. When executed, the orchestrator performs the following workflow:

    1. Market Data Initialization: Initializes MarketData to fetch real-time prices.
    2. LLM Adapter Initialization: Initializes adapters for different models (e.g., OpenAIAdapter, ClaudeAdapter).
    3. Decision Generation: Uses DecisionMaker instances to generate trading decisions based on current market prices.
    4. Comparison: Compares decisions from different models to identify consensus or divergence.

    Ensure you have a .env file configured with the necessary API keys for your chosen providers before running.

    python3 main.py
  10. Troubleshoot Alpha Arena common issues

    main

    API Key Errors

    Error: ❌ OpenAI API密钥未设置,请设置OPENAI_API_KEY环境变量 Solution: Verify that your .env file exists and contains the correct OPENAI_API_KEY.

    Network Connection Issues

    Error: ❌ 获取BTCUSDT价格失败: 网络请求失败 Solution: Check your internet connection and ensure you can reach the Bitget API endpoints.

    Missing Dependencies

    Error: ❌ 请安装openai: pip install openai Solution: Run the full dependency installation command:

    pip install -r requirements.txt
  11. Unified Prompt and Output Schema for LLM Agents

    main

    To ensure comparability, all LLM agents receive a unified system prompt and must respond with a strictly validated JSON schema.

    System Prompt Context: Agents are provided with Market Time (UTC), Account details (cash and positions), Universe (BTCUSDT, ETHUSDT), 60m of 1m-bars (OHLCV), Live Ticker data (bid, ask, mid, spread), and constraints (5m cadence, max 20% NAV exposure per trade, long only, max 1 open symbol).

    Required JSON Output Schema: Every model must return a JSON object following this structure:

    {
      "symbol": "BTCUSDT|ETHUSDT|null",
      "action": "BUY|SELL|HOLD",
      "position_size_pct": 0.0,
      "take_profit": 0.0,
      "stop_loss": 0.0,
      "confidence": 0.0,
      "rationale": "short text (<=200 chars)"
    }
  12. Use DecisionMaker to get AI trading decisions

    main

    The DecisionMaker class is the primary interface for obtaining trading decisions from an LLM. It requires an adapter (implementing the LLM interface) during initialization. You can call .get_decision(prices) passing a dictionary of current market prices to receive a decision object.

    Key Methods:

    • get_decision(prices): Takes a dictionary of prices and returns a decision dictionary.
    • format_decision_for_display(decision): Formats the decision dictionary into a human-readable string.

    Expected Decision Format: A decision dictionary typically contains:

    • symbol: The asset symbol (e.g., 'BTC').
    • action: The trading action (e.g., 'BUY', 'SELL', 'HOLD').
    from core.decision import DecisionMaker
    from adapters.openai_adapter import OpenAIAdapter
    
    # Initialize with an adapter
    adapter = OpenAIAdapter()
    decision_maker = DecisionMaker(adapter)
    
    # Get decision based on current prices
    prices = {'BTC': 65000, 'ETH': 3500}
    decision = decision_maker.get_decision(prices)
    
    # Display the result
    print(decision_maker.format_decision_for_display(decision))