# Openfund Agent

<div align="center">

**自我进化的量化交易智能体系统**

A Self-Evolving Quantitative Trading Agent System Based on Claude Agent SDK

[![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

</div>

## 📖 目录 / Table of Contents

- [概述 / Overview](#概述--overview)
- [核心特性 / Features](#核心特性--features)
- [系统架构 / Architecture](#系统架构--architecture)
- [安装指南 / Installation](#安装指南--installation)
- [配置说明 / Configuration](#配置说明--configuration)
- [使用示例 / Usage Examples](#使用示例--usage-examples)
- [项目结构 / Project Structure](#项目结构--project-structure)
- [开发指南 / Development](#开发指南--development)
- [常见问题 / FAQ](#常见问题--faq)
- [许可证 / License](#许可证--license)

## 概述 / Overview

Openfund Agent 是一个基于 Claude Agent SDK 的自我进化量化交易智能体系统。该系统能够自动分析交易表现、识别策略改进机会、修改策略代码并通过回测验证改进效果，形成完整的自我优化闭环。

Openfund Agent is an intelligent trading system that automatically analyzes trading performance, identifies strategy improvement opportunities, modifies strategy code, and validates improvements through backtesting, forming a complete self-optimization loop.

### 核心能力 / Core Capabilities

- 🤖 **智能决策**: 基于 Claude 大模型的策略分析和改进决策
- 📊 **数据采集**: 集成 Openfund-core，支持多时间框架的市场数据和 SMC-ICT 技术指标
- 🎯 **策略执行**: 整合 Openfund-maker 和 Openfund-taker，实现信号生成和订单管理
- 📈 **表现分析**: 全面的交易指标分析，包括胜率、盈亏比、最大回撤、夏普比率等
- 🔧 **代码修改**: 自动生成符合 PEP8 规范的代码，保持接口一致性
- ✅ **验证风控**: Docker 沙盒测试、回测验证、风险评估
- 🔄 **自我进化**: 持续的策略优化闭环

## 核心特性 / Features

### 1. 自动化数据采集 / Automated Data Collection

- 支持多个交易所（通过 CCXT）
- 多时间框架数据获取（1m, 5m, 15m, 1h, 4h, 1d）
- SMC-ICT 技术指标（Struct, FVG, OrderBlock, PDArray）
- 智能缓存机制，减少 API 调用
- 自动重试和错误处理

### 2. 策略执行引擎 / Strategy Execution Engine

- 集成 Openfund-maker 生成交易信号
- 集成 Openfund-taker 管理订单和持仓
- 支持多策略并发执行
- 策略状态隔离
- 完整的订单记录和追踪

### 3. 智能表现分析 / Intelligent Performance Analysis

- 实时交易指标计算
- 周期性表现报告
- 风险调整后收益指标
- 异常数据检测和标记
- 可视化权益曲线

### 4. Agent 决策中枢 / Agent Decision Engine

- Claude 模型驱动的策略分析
- 自动识别策略问题
- 生成改进方案
- 风险评估和人工审核机制
- 决策历史追踪

### 5. 自动代码修改 / Automated Code Modification

- Claude 生成符合规范的代码
- 自动添加 docstring 注释
- 接口一致性验证
- Git 版本管理和回滚
- 代码质量检查（PEP8, Black）

### 6. 验证和风控 / Validation & Risk Control

- Docker 沙盒隔离测试
- Pytest 测试套件自动运行
- 回测验证
- 核心逻辑修改拦截
- 过度拟合检测
- 实盘亏损自动回滚

### 7. 自我进化闭环 / Self-Evolution Loop

- 六步迭代流程：数据采集 → 策略执行 → 结果反馈 → 决策 → 代码修改 → 验证
- 自动部署新版本
- 错误处理和回滚
- 进化监控和状态追踪
- 最终报告生成

## 系统架构 / Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                     Claude Agent SDK                         │
│  ┌───────────────────────────────────────────────────────┐  │
│  │              Agent 决策中枢 (Claude Model)            │  │
│  └───────────────────────────────────────────────────────┘  │
│                            │                                 │
│                            ▼                                 │
│  ┌───────────────────────────────────────────────────────┐  │
│  │                   Tool Manager                         │  │
│  └───────────────────────────────────────────────────────┘  │
│    │         │         │         │         │                │
│    ▼         ▼         ▼         ▼         ▼                │
│  ┌────┐  ┌────┐  ┌────┐  ┌────┐  ┌────┐                   │
│  │Data│  │Stgy│  │Fdbk│  │Code│  │Dcsn│                   │
│  │Tool│  │Tool│  │Tool│  │Tool│  │Tool│                   │
│  └────┘  └────┘  └────┘  └────┘  └────┘                   │
└─────────────────────────────────────────────────────────────┘
     │        │        │        │        │
     ▼        ▼        ▼        ▼        ▼
┌────────┐┌────────┐┌────────┐┌────────┐┌────────┐
│Openfund││Openfund││Perform.││Code    ││Decision│
│Core    ││Maker/  ││Analyzer││Modifier││Engine  │
│        ││Taker   ││        ││        ││        │
└────────┘└────────┘└────────┘└────────┘└────────┘
```

## 安装指南 / Installation

### 系统要求 / Prerequisites

- **Python**: 3.12 或更高版本 / 3.12 or higher
- **Docker**: 用于沙盒测试 / For sandbox testing
- **Git**: 版本控制 / Version control
- **Poetry**: Python 依赖管理（推荐）/ Python dependency management (recommended)

### 方法 1: 使用 Poetry 安装（推荐）/ Method 1: Install with Poetry (Recommended)

```bash
# 1. 克隆仓库 / Clone the repository
git clone https://github.com/openfund/openfund-agent.git
cd openfund-agent

# 2. 安装 Poetry（如果尚未安装）/ Install Poetry (if not already installed)
curl -sSL https://install.python-poetry.org | python3 -

# 3. 安装依赖 / Install dependencies
poetry install

# 4. 激活虚拟环境 / Activate virtual environment
poetry shell
```

### 方法 2: 使用 pip 安装 / Method 2: Install with pip

```bash
# 1. 克隆仓库 / Clone the repository
git clone https://github.com/openfund/openfund-agent.git
cd openfund-agent

# 2. 创建虚拟环境 / Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# 3. 安装依赖 / Install dependencies
pip install -r requirements.txt

# 4. 安装包 / Install package
pip install -e .
```

### 安装 Openfund 依赖 / Install Openfund Dependencies

```bash
# 安装 Openfund-core
cd ../openfund-core
pip install -e .

# 安装 Openfund-maker
cd ../openfund-maker
pip install -e .

# 安装 Openfund-taker
cd ../openfund-taker
pip install -e .

# 返回 openfund-agent 目录
cd ../openfund-agent
```

### 构建 Docker 沙盒镜像 / Build Docker Sandbox Image

```bash
# 构建沙盒镜像 / Build sandbox image
docker build -t openfund-agent-sandbox:latest -f Dockerfile .

# 验证镜像 / Verify image
docker images | grep openfund-agent-sandbox
```

## 配置说明 / Configuration

### 1. 创建配置文件 / Create Configuration File

```bash
# 复制配置模板 / Copy configuration template
cp config/development.yaml config/local.yaml
```

### 2. 编辑配置文件 / Edit Configuration File

打开 `config/local.yaml` 并根据需要修改配置：

```yaml
# 交易所配置 / Exchange Configuration
exchange:
  name: "okx"  # 支持的交易所: okx, binance, bybit
  api_key: "${EXCHANGE_API_KEY}"
  api_secret: "${EXCHANGE_API_SECRET}"
  api_password: "${EXCHANGE_API_PASSWORD}"  # OKX 需要
  testnet: true  # 使用测试网

# Claude API 配置 / Claude API Configuration
claude:
  api_key: "${CLAUDE_API_KEY}"
  model: "claude-3-5-sonnet-20241022"
  max_tokens: 4096
  temperature: 0.7

# 数据采集配置 / Data Collection Configuration
data_collection:
  cache_ttl: 60  # 缓存时间（分钟）
  retry_max: 3
  retry_delay: 1.0
  timeframes: ["1m", "5m", "15m", "1h", "4h", "1d"]

# 策略配置 / Strategy Configuration
strategy:
  default_strategy: "BestTopDownStrategy"
  max_concurrent: 3
  isolation_enabled: true

# 风险控制配置 / Risk Control Configuration
risk:
  max_drawdown_threshold: 0.20  # 20%
  max_loss_threshold: 0.10  # 10%
  iteration_frequency_limit: 1  # 每天最多迭代次数
  core_logic_review_required: true
  overfitting_detection_enabled: true

# 验证配置 / Validation Configuration
validation:
  sandbox_enabled: true
  sandbox_timeout: 300  # 秒
  pytest_required: true
  black_check_required: true
  backtest_required: true

# 通知配置 / Notification Configuration
notification:
  feishu_webhook: "${FEISHU_WEBHOOK_URL}"
  enabled: true

# 日志配置 / Logging Configuration
logging:
  level: "INFO"
  format: "json"
  file: "logs/openfund_agent.log"
  rotation: "1 day"
  retention: "30 days"

# 进化配置 / Evolution Configuration
evolution:
  max_iterations: 100
  goal_check_interval: 10
  auto_deploy: true
  rollback_on_failure: true
```

### 3. 设置环境变量 / Set Environment Variables

创建 `.env` 文件：

```bash
# 交易所 API / Exchange API
EXCHANGE_API_KEY=your_api_key_here
EXCHANGE_API_SECRET=your_api_secret_here
EXCHANGE_API_PASSWORD=your_api_password_here  # OKX only

# Claude API
CLAUDE_API_KEY=your_claude_api_key_here

# 通知 / Notifications
FEISHU_WEBHOOK_URL=your_feishu_webhook_url_here

# 数据库 / Database
DATABASE_PATH=data/openfund_agent.db

# Git 配置 / Git Configuration
GIT_USER_NAME=Openfund Agent
GIT_USER_EMAIL=agent@openfund.com
```

然后加载环境变量：

```bash
# Linux/Mac
export $(cat .env | xargs)

# 或使用 direnv
direnv allow
```

## 使用示例 / Usage Examples

### 示例 1: 基本使用 / Example 1: Basic Usage

```python
from openfund_agent.evolution.orchestrator import EvolutionOrchestrator
from openfund_agent.config.loader import ConfigLoader

# 加载配置 / Load configuration
config = ConfigLoader.load("config/local.yaml")

# 初始化进化编排器 / Initialize evolution orchestrator
orchestrator = EvolutionOrchestrator(config=config)

# 启动自我进化流程 / Start self-evolution loop
result = orchestrator.start_evolution(
    strategy_name="BestTopDownStrategy",
    symbol="BTC/USDT:USDT",
    optimization_goal="sharpe_ratio",
    goal_threshold=2.0,
    max_iterations=50
)

print(f"Evolution completed: {result}")
```

### 示例 2: 手动执行单个步骤 / Example 2: Manual Step Execution

```python
from agent.data.collector import DataCollector
from agent.strategy.executor import StrategyExecutor
from agent.feedback.analyzer import PerformanceAnalyzer
from agent.decision.engine import DecisionEngine
from agent.modification.modifier import CodeModifier
from agent.validation.validator import Validator

# 步骤 1: 数据采集 / Step 1: Data Collection
collector = DataCollector(config)
market_data = collector.collect_market_data(
    symbol="BTC/USDT:USDT",
    timeframes=["1h", "4h", "1d"]
)

# 步骤 2: 策略执行 / Step 2: Strategy Execution
executor = StrategyExecutor(config)
trades = executor.execute_strategy(
    strategy_name="BestTopDownStrategy",
    market_data=market_data
)

# 步骤 3: 表现分析 / Step 3: Performance Analysis
analyzer = PerformanceAnalyzer(config)
performance = analyzer.analyze(trades)
print(f"Sharpe Ratio: {performance.sharpe_ratio}")
print(f"Win Rate: {performance.win_rate}")
print(f"Max Drawdown: {performance.max_drawdown}")

# 步骤 4: 决策 / Step 4: Decision Making
engine = DecisionEngine(config)
decision = engine.make_decision(
    performance=performance,
    market_data=market_data,
    strategy_code=open("strategies/best_top_down.py").read()
)

# 步骤 5: 代码修改 / Step 5: Code Modification
if decision.should_modify:
    modifier = CodeModifier(config)
    modified_code = modifier.modify_code(
        original_code=decision.target_code,
        modification_plan=decision.modification_plan
    )
    
    # 步骤 6: 验证 / Step 6: Validation
    validator = Validator(config)
    validation_result = validator.validate(
        modified_code=modified_code,
        original_performance=performance
    )
    
    if validation_result.passed:
        print("Validation passed! Deploying new version...")
        modifier.deploy(modified_code)
    else:
        print(f"Validation failed: {validation_result.reason}")
```

### 示例 3: 命令行使用 / Example 3: Command Line Usage

```bash
# 启动自我进化流程 / Start evolution loop
openfund-agent evolve \
    --strategy BestTopDownStrategy \
    --symbol BTC/USDT:USDT \
    --goal sharpe_ratio \
    --threshold 2.0 \
    --max-iterations 50

# 查看策略表现 / View strategy performance
openfund-agent analyze \
    --strategy BestTopDownStrategy \
    --period 7d

# 手动触发代码修改 / Manually trigger code modification
openfund-agent modify \
    --strategy BestTopDownStrategy \
    --reason "Improve entry timing"

# 运行回测验证 / Run backtest validation
openfund-agent backtest \
    --strategy BestTopDownStrategy \
    --start-date 2024-01-01 \
    --end-date 2024-11-24
```

## 项目结构 / Project Structure

```
openfund-agent/
├── src/
│   └── agent/                    # Main package
│       ├── __init__.py
│       ├── main.py              # Entry point
│       ├── config/              # Configuration management
│       ├── datas/               # Data collection module
│       ├── strategy/            # Strategy execution module
│       ├── feedback/            # Performance analysis module
│       ├── decision/            # Agent decision module
│       ├── modification/        # Code modification module
│       ├── validation/          # Validation module
│       ├── risk/                # Risk control module
│       ├── tools/               # Tool management
│       ├── evolution/           # Evolution orchestrator
│       ├── models/              # Data models
│       ├── storage/             # Data persistence
│       ├── logging/             # Logging configuration
│       └── errors/              # Error handling
├── config/                      # Configuration files
│   ├── development.yaml
│   ├── production.yaml
│   └── test.yaml
├── tests/                       # Test suite
│   ├── unit/
│   ├── integration/
│   └── e2e/
├── docs/                        # Documentation
│   ├── architecture.md
│   ├── api.md
│   └── deployment.md
├── examples/                    # Usage examples
├── deploy/                      # Deployment scripts
├── logs/                        # Log files
├── Dockerfile                   # Docker configuration
├── build_sandbox.sh            # Sandbox build script
├── pyproject.toml              # Poetry configuration
└── README.md                   # This file
```

## 开发指南 / Development

### 运行测试 / Running Tests

```bash
# 运行所有测试 / Run all tests
poetry run pytest

# 运行测试并生成覆盖率报告 / Run tests with coverage
poetry run pytest --cov=src/agent --cov-report=html

# 运行特定测试文件 / Run specific test file
poetry run pytest tests/unit/test_data_collector.py

# 运行特定测试函数 / Run specific test function
poetry run pytest tests/unit/test_data_collector.py::test_collect_market_data
```

### 代码质量检查 / Code Quality

```bash
# 格式化代码 / Format code
poetry run black src/agent/

# 检查代码风格 / Check code style
poetry run pycodestyle src/agent/

# 类型检查 / Type checking
poetry run mypy src/agent/

# 运行所有检查 / Run all checks
poetry run black src/agent/ && \
poetry run pycodestyle src/agent/ && \
poetry run mypy src/agent/
```

### 构建和部署 / Build and Deploy

```bash
# 构建 Docker 镜像 / Build Docker image
docker build -t openfund-agent:latest .

# 构建沙盒镜像 / Build sandbox image
./build_sandbox.sh

# 运行容器 / Run container
docker run -d \
  --name openfund-agent \
  -v $(pwd)/config:/app/config \
  -v $(pwd)/logs:/app/logs \
  --env-file .env \
  openfund-agent:latest
```

### 调试 / Debugging

```bash
# 启用调试日志 / Enable debug logging
export LOG_LEVEL=DEBUG

# 使用 IPython 进行交互式调试 / Interactive debugging with IPython
poetry run ipython

# 在 Jupyter Notebook 中测试 / Test in Jupyter Notebook
poetry run jupyter notebook examples/
```

## 常见问题 / FAQ

### Q1: 如何更换交易所？/ How to switch exchanges?

修改 `config/local.yaml` 中的 `exchange.name` 字段，支持的交易所包括：okx, binance, bybit 等。

Edit `exchange.name` in `config/local.yaml`. Supported exchanges: okx, binance, bybit, etc.

### Q2: 如何调整风险控制参数？/ How to adjust risk control parameters?

在配置文件的 `risk` 部分修改相关阈值，如 `max_drawdown_threshold` 和 `max_loss_threshold`。

Modify thresholds in the `risk` section of the config file, such as `max_drawdown_threshold` and `max_loss_threshold`.

### Q3: 如何禁用自动代码修改？/ How to disable automatic code modification?

设置 `evolution.auto_deploy: false`，系统将在生成修改建议后等待人工审核。

Set `evolution.auto_deploy: false` to require manual review before deploying modifications.

### Q4: 沙盒测试失败怎么办？/ What if sandbox testing fails?

检查 Docker 是否正常运行，确保镜像已正确构建。可以通过 `docker logs` 查看详细错误信息。

Check if Docker is running properly and the image is built correctly. Use `docker logs` to view detailed error messages.

### Q5: 如何添加自定义策略？/ How to add custom strategies?

在 `openfund-maker` 中创建新的策略类，继承 `BaseStrategy`，然后在配置中指定策略名称。

Create a new strategy class in `openfund-maker` that inherits from `BaseStrategy`, then specify the strategy name in the config.

### Q6: 支持哪些优化目标？/ What optimization goals are supported?

支持的优化目标包括：`sharpe_ratio`（夏普比率）、`win_rate`（胜率）、`profit_factor`（盈利因子）、`max_drawdown`（最大回撤）等。

Supported goals: `sharpe_ratio`, `win_rate`, `profit_factor`, `max_drawdown`, etc.

## 路线图 / Roadmap

- [ ] 支持更多交易所和交易对 / Support more exchanges and trading pairs
- [ ] 增强多策略组合优化 / Enhanced multi-strategy portfolio optimization
- [ ] 实时监控仪表板 / Real-time monitoring dashboard
- [ ] 策略市场和分享功能 / Strategy marketplace and sharing
- [ ] 机器学习模型集成 / Machine learning model integration
- [ ] 移动端应用 / Mobile application

## 许可证 / License

MIT License - 详见 [LICENSE](LICENSE) 文件

## 贡献 / Contributing

欢迎贡献！请在提交 Pull Request 之前阅读我们的贡献指南。

Contributions are welcome! Please read our contributing guidelines before submitting pull requests.

### 贡献者 / Contributors

感谢所有为本项目做出贡献的开发者！

Thanks to all contributors who have helped improve this project!

## 支持 / Support

- 📧 Email: contact@openfund.com
- 💬 Discord: [Join our community](https://discord.gg/openfund)
- 🐛 Issues: [GitHub Issues](https://github.com/openfund/openfund-agent/issues)
- 📖 Documentation: [Full Documentation](https://docs.openfund.com)

## 致谢 / Acknowledgments

- [Anthropic Claude](https://www.anthropic.com/) - AI 决策引擎
- [CCXT](https://github.com/ccxt/ccxt) - 交易所连接
- [Openfund Core](https://github.com/openfund/openfund-core) - 核心数据和指标库

---

<div align="center">

**Built with ❤️ by the Openfund Team**

[Website](https://openfund.com) • [Documentation](https://docs.openfund.com) • [Blog](https://blog.openfund.com)

</div>
