306 lines
7.5 KiB
Markdown
306 lines
7.5 KiB
Markdown
# OpenClaw Trading
|
||
|
||
一个基于ClawWork生存压力机制的多Agent量化交易系统。
|
||
|
||
## 系统概述
|
||
|
||
OpenClaw Trading是一个创新的量化交易框架,通过模拟Agent在交易环境中的"生存压力"来实现智能决策。每个Agent都有自己的经济状况,需要权衡交易、学习和风险管理的资源分配。
|
||
|
||
### 核心概念
|
||
|
||
- **ClawWork机制**: Agent根据经济状况(繁荣/稳定/挣扎/临界/破产)决定行动策略
|
||
- **多Agent协作**: 使用LangGraph编排多个专业Agent并行分析市场
|
||
- **因子市场**: 可购买、解锁和交易各类技术指标因子
|
||
- **技能学习**: Agent可以通过学习提升交易技能
|
||
- **风险管理**: 头寸集中度、回撤控制和VaR计算
|
||
|
||
## 快速开始
|
||
|
||
### 安装
|
||
|
||
```bash
|
||
# 克隆仓库
|
||
git clone <repository-url>
|
||
cd openclaw-trading
|
||
|
||
# 安装依赖
|
||
pip install -e .
|
||
```
|
||
|
||
### 基础示例
|
||
|
||
```python
|
||
from openclaw.core.economy import TradingEconomicTracker
|
||
|
||
# 创建经济追踪器
|
||
tracker = TradingEconomicTracker(
|
||
agent_id="my_agent",
|
||
initial_capital=10000.0
|
||
)
|
||
|
||
# 检查生存状态
|
||
status = tracker.get_survival_status()
|
||
print(f"当前状态: {status.value}")
|
||
print(f"余额: ${tracker.balance:,.2f}")
|
||
|
||
# 模拟决策成本
|
||
cost = tracker.calculate_decision_cost(
|
||
tokens_input=1000,
|
||
tokens_output=500
|
||
)
|
||
|
||
# 模拟交易
|
||
trade_result = tracker.calculate_trade_cost(
|
||
trade_value=1000.0,
|
||
is_win=True,
|
||
win_amount=100.0
|
||
)
|
||
```
|
||
|
||
## 核心模块
|
||
|
||
### 1. Agent系统 (`openclaw.agents`)
|
||
|
||
```python
|
||
from openclaw.agents.trader import TraderAgent
|
||
|
||
agent = TraderAgent(
|
||
agent_id="trader_001",
|
||
initial_capital=5000.0,
|
||
skill_level=0.6
|
||
)
|
||
```
|
||
|
||
**关键特性**:
|
||
- 每个Agent独立的经济追踪器
|
||
- 可升级的技能系统
|
||
- 事件钩子机制(交易、学习、破产等)
|
||
|
||
### 2. 经济系统 (`openclaw.core.economy`)
|
||
|
||
Agent的生存状态根据资金水平自动计算:
|
||
|
||
| 状态 | 资金比例 | 行为特征 |
|
||
|------|---------|---------|
|
||
| 繁荣(Thriving) | >150% | 70%交易,30%学习 |
|
||
| 稳定(Stable) | 100-150% | 80%交易,20%学习 |
|
||
| 挣扎(Struggling) | 50-100% | 90%交易,10%学习 |
|
||
| 临界(Critical) | <50% | 100%最小化交易 |
|
||
| 破产(Bankrupt) | <阈值 | 停止交易 |
|
||
|
||
### 3. 工作/交易平衡 (`openclaw.core.work_trade_balance`)
|
||
|
||
```python
|
||
from openclaw.core.work_trade_balance import WorkTradeBalance, WorkTradeConfig
|
||
|
||
config = WorkTradeConfig()
|
||
balance = WorkTradeBalance(
|
||
economic_tracker=tracker,
|
||
config=config
|
||
)
|
||
|
||
# 决定活动
|
||
decision = balance.decide_activity(skill_level=0.6, win_rate=0.55)
|
||
# 返回: ActivityDecision.TRADE / LEARN / MINIMAL_TRADE / PAPER_TRADE
|
||
|
||
# 获取交易强度
|
||
intensity = balance.get_trade_intensity(win_rate=0.55)
|
||
# 返回: position_size_multiplier, max_concurrent_positions, risk_per_trade
|
||
```
|
||
|
||
### 4. LangGraph工作流 (`openclaw.workflow`)
|
||
|
||
6个专业Agent并行分析:
|
||
|
||
```python
|
||
from openclaw.workflow.trading_workflow import TradingWorkflow
|
||
|
||
workflow = TradingWorkflow(
|
||
symbol="AAPL",
|
||
initial_capital=1000.0,
|
||
enable_parallel=True
|
||
)
|
||
|
||
# 工作流图:
|
||
# START → [MarketAnalysis, SentimentAnalysis, FundamentalAnalysis] → BullBearDebate → DecisionFusion → RiskAssessment → END
|
||
```
|
||
|
||
### 5. 因子市场 (`openclaw.factor`)
|
||
|
||
```python
|
||
from openclaw.factor import FactorStore
|
||
|
||
store = FactorStore(agent_id="factor_trader", tracker=tracker)
|
||
|
||
# 列出可用因子
|
||
factors = store.list_available()
|
||
|
||
# 获取因子
|
||
factor = store.get_factor("buy_ma_crossover")
|
||
|
||
# 购买高级因子
|
||
result = store.purchase("buy_ml_prediction")
|
||
|
||
# 使用因子
|
||
from openclaw.factor.types import FactorContext
|
||
context = FactorContext(symbol="AAPL", equity=10000.0)
|
||
signal = factor.evaluate(context)
|
||
```
|
||
|
||
**因子类型**:
|
||
- 基础因子(免费): MA Crossover, RSI Oversold, MACD Crossover, Bollinger Band
|
||
- 高级因子(付费): ML Prediction, Sentiment Momentum, Multi-Factor Ensemble
|
||
|
||
### 6. 学习系统 (`openclaw.learning`)
|
||
|
||
```python
|
||
from openclaw.learning.manager import CourseManager
|
||
from openclaw.learning.courses import create_technical_analysis_course
|
||
|
||
manager = CourseManager(agent=agent)
|
||
|
||
# 检查是否可以注册
|
||
can_enroll, reason = manager.can_enroll("technical_analysis_101")
|
||
|
||
# 注册课程
|
||
success, message = manager.enroll("technical_analysis_101")
|
||
|
||
# 更新进度
|
||
manager.update_progress("technical_analysis_101", 50)
|
||
|
||
# 查看技能等级
|
||
for skill, level in manager.skill_levels.items():
|
||
print(f"{skill.value}: {level:.2f}")
|
||
```
|
||
|
||
### 7. 投资组合风险管理 (`openclaw.portfolio`)
|
||
|
||
```python
|
||
from openclaw.portfolio.risk import PortfolioRiskManager
|
||
|
||
manager = PortfolioRiskManager(
|
||
portfolio_id="my_portfolio",
|
||
max_concentration_pct=0.20,
|
||
max_drawdown_pct=0.10,
|
||
var_limit_pct=0.05
|
||
)
|
||
|
||
# 检查头寸集中度
|
||
result = manager.concentration_limit.check_concentration(
|
||
symbol="AAPL",
|
||
position_value=2500.0,
|
||
portfolio_value=10000.0
|
||
)
|
||
|
||
# 回撤控制
|
||
manager.drawdown_controller.update(portfolio_value=9500.0)
|
||
allowed = manager.drawdown_controller.is_trading_allowed()
|
||
|
||
# VaR计算
|
||
var_result = manager.var_calculator.calculate_var(
|
||
portfolio_value=10000.0,
|
||
positions={"AAPL": 3000.0, "GOOGL": 2000.0},
|
||
volatilities={"AAPL": 0.25, "GOOGL": 0.20}
|
||
)
|
||
```
|
||
|
||
## 示例脚本
|
||
|
||
项目包含6个完整示例:
|
||
|
||
```bash
|
||
# 1. 快速开始 - 经济追踪基础
|
||
python examples/01_quickstart.py
|
||
|
||
# 2. LangGraph工作流演示
|
||
python examples/02_workflow_demo.py
|
||
|
||
# 3. 因子市场使用
|
||
python examples/03_factor_market.py
|
||
|
||
# 4. 学习系统演示
|
||
python examples/04_learning_system.py
|
||
|
||
# 5. 工作/交易平衡决策
|
||
python examples/05_work_trade_balance.py
|
||
|
||
# 6. 投资组合风险管理
|
||
python examples/06_portfolio_risk.py
|
||
```
|
||
|
||
## 测试
|
||
|
||
```bash
|
||
# 运行所有测试
|
||
pytest tests/ -v
|
||
|
||
# 运行特定模块测试
|
||
pytest tests/unit/test_economy.py -v
|
||
pytest tests/integration/ -v
|
||
```
|
||
|
||
## 项目结构
|
||
|
||
```
|
||
openclaw/
|
||
├── agents/ # Agent实现
|
||
│ ├── base.py # 基础Agent类
|
||
│ ├── trader.py # 交易Agent
|
||
│ └── ... # 专业分析Agent
|
||
├── core/ # 核心功能
|
||
│ ├── economy.py # 经济追踪
|
||
│ └── work_trade_balance.py # 工作/交易平衡
|
||
├── factor/ # 因子市场
|
||
│ ├── base.py # 因子基类
|
||
│ ├── basic.py # 基础因子
|
||
│ ├── advanced.py # 高级因子
|
||
│ └── store.py # 因子商店
|
||
├── learning/ # 学习系统
|
||
│ ├── manager.py # 课程管理
|
||
│ └── courses.py # 预定义课程
|
||
├── portfolio/ # 投资组合
|
||
│ └── risk.py # 风险管理
|
||
├── workflow/ # LangGraph工作流
|
||
│ ├── trading_workflow.py
|
||
│ └── state.py
|
||
└── utils/ # 工具函数
|
||
└── logging.py
|
||
|
||
examples/ # 示例脚本
|
||
tests/ # 测试用例
|
||
design/ # 设计文档
|
||
```
|
||
|
||
## 配置
|
||
|
||
可以通过环境变量或配置文件自定义:
|
||
|
||
```python
|
||
# 经济追踪器配置
|
||
TradingEconomicTracker(
|
||
agent_id="agent_001",
|
||
initial_capital=10000.0,
|
||
token_cost_per_1m_input=3.0, # $3 per 1M input tokens
|
||
token_cost_per_1m_output=15.0, # $15 per 1M output tokens
|
||
trade_fee_rate=0.001, # 0.1% trading fee
|
||
data_cost_per_call=0.01 # $0.01 per market data call
|
||
)
|
||
```
|
||
|
||
## 开发计划
|
||
|
||
- [x] Phase 1: 基础框架 (100%)
|
||
- [x] Phase 2: 多Agent协作 (92%)
|
||
- [x] Phase 3: 高级功能 (25%)
|
||
- [x] Phase 4: 生产就绪 (78%)
|
||
|
||
详见 [design/TASKS.md](design/TASKS.md)
|
||
|
||
## 许可证
|
||
|
||
MIT License
|
||
|
||
## 贡献
|
||
|
||
欢迎提交Issue和Pull Request!
|