Skip to content

whosly/trust

Repository files navigation

Binance HFT 量化交易系统

高频量化交易系统,采用 Rust + Python 混合架构,专为量化交易所设计。

gitee.com/whosly/trust

github.com/whosly/trust

文档导航: 完整文档索引 | 快速开始 | 命令速查表 | 项目结构

特性

  • 高性能: Rust 核心引擎,极低的延迟
  • 灵活策略: Python 策略层,快速开发和迭代
  • 实时数据: WebSocket 实时行情和订单更新
  • 风险控制: 多层风险管理机制
  • 多策略: 支持网格、趋势跟踪等多种策略
  • 完整日志: 统一的日志系统,支持日志轮转
  • 配置管理: JSON 配置文件 + 环境变量覆盖
  • Web 监控面板: 实时监控系统状态和交易数据
  • 自动重连: gRPC 客户端自动重连机制,确保系统稳定性
  • 健康检查: 完善的健康检查接口,监控各组件状态

系统要求

必需

  • Rust: 1.70 或更高版本
  • Python: 3.10 或更高版本
  • 操作系统: Windows 10+, Linux, macOS

推荐

  • 内存: 4GB 以上
  • CPU: 4 核心以上
  • 网络: 稳定的低延迟网络连接

安装指南

1. 安装 Rust

Windows:

# 下载并运行 rustup-init.exe
# https://rustup.rs/

Linux/macOS:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env

验证安装:

rustc --version
cargo --version

2. 安装 Python

Windows:

# 从 python.org 下载 Python 3.10+
# 或使用 Anaconda

Linux:

sudo apt update
sudo apt install python3.10 python3-pip

macOS:

brew install python@3.10

验证安装:

python --version
pip --version

3. 克隆项目

4. 安装依赖

Rust 依赖:

cargo fetch

Python 依赖:

pip install -r requirements.txt

编译和构建

Rust 项目编译

开发模式编译

# 编译所有 crate
cargo build

# 编译特定 crate
cargo build -p trading-engine
cargo build -p binance-api
cargo build -p market-data
cargo build -p common

# 检查代码(不生成二进制文件,速度更快)
cargo check
cargo check --all-targets

发布模式编译(优化)

# 完整优化编译(LTO、单 codegen-unit)
cargo build --release

# 编译特定 crate(发布模式)
cargo build --release -p trading-engine

清理构建产物

# 清理所有构建产物
cargo clean

# 清理特定 crate
cargo clean -p trading-engine

Python 项目

语法检查

# 编译检查所有 Python 文件
python -m py_compile src/python/**/*.py

# 或使用 compileall
python -m compileall src/python

代码格式化

# 使用 black 格式化
black src/python

# 使用 isort 排序导入
isort src/python

# 一起使用
black src/python && isort src/python

代码检查

# Flake8 检查
flake8 src/python --max-line-length=100

# MyPy 类型检查
mypy src/python --ignore-missing-imports

# 所有检查
flake8 src/python && mypy src/python

测试

快速测试

# 使用脚本(推荐,自动处理依赖)
.\scripts\test_all.ps1          # 所有测试
.\scripts\test_rust.ps1         # 仅 Rust
.\scripts\test_python.ps1       # 仅 Python

# 手动命令
cargo test                                  # Rust
python -m pytest src/python/tests/ -v      # Python

测试状态: ✅ 36/36 通过 (Rust: 21, Python: 15)

按模块测试

# Rust 模块
cargo test -p trading-engine        # 交易引擎
cargo test -p binance-api          # 币安 API
cargo test -p market-data          # 市场数据

📖 完整测试指南: 查看 testing.md 了解所有测试命令、脚本和最佳实践

运行系统

配置

  1. 复制配置文件模板:
cp config/config.example.json config/config.json
  1. 编辑配置文件 config/config.json:
{
  "system": {
    "api_key": "你的币安API密钥",
    "api_secret": "你的币安API密钥",
    "base_url": "https://api.binance.com",
    "log_level": "INFO"
  },
  "symbols": [
    {
      "symbol": "BTCUSDT",
      "enabled": true,
      "strategy": {
        "type": "grid",
        "params": {
          "grid_spacing": 0.01,
          "grid_quantity": 0.001
        }
      }
    }
  ]
}
  1. 或使用环境变量:
# Linux/macOS
export BINANCE_API_KEY="your_api_key"
export BINANCE_API_SECRET="your_api_secret"
export LOG_LEVEL="DEBUG"

# Windows PowerShell
$env:BINANCE_API_KEY="your_api_key"
$env:BINANCE_API_SECRET="your_api_secret"
$env:LOG_LEVEL="DEBUG"

启动系统

Rust 交易引擎:

# 开发模式
cargo run --bin trading-engine

# 发布模式(推荐生产环境)
cargo run --release --bin trading-engine

Python 策略管理器:

# 直接运行
python -m src.python.main

# 或使用 poetry
poetry run python -m src.python.main

Web 监控面板:

# 启动 Web 监控面板
cd src/python
python web/app.py

# 访问监控面板
# 浏览器打开: http://localhost:8000

系统启动顺序

推荐启动顺序:

  1. 先启动 Rust 交易引擎(gRPC 服务器)
  2. 再启动 Web 监控面板
  3. 最后启动 Python 策略管理器

注意事项:

  • Web 面板会自动尝试连接 gRPC 服务器
  • 如果 Rust 服务重启,Web 面板会自动重连
  • 健康检查端点: http://localhost:8080/health

开发工具

使用 Makefile (推荐 Linux/macOS)

# 查看所有可用命令
make help

# 安装依赖
make install

# 构建项目
make build
make build-release

# 运行测试
make test

# 代码格式化
make format

# 代码检查
make lint

# 清理构建产物
make clean

# 开发工作流(格式化 + 检查 + 测试)
make dev

使用 PowerShell 脚本 (推荐 Windows)

# 查看帮助
Get-Help .\build.ps1

# 开发模式构建
.\build.ps1

# 发布模式构建
.\build.ps1 -Mode release

# 清理并构建
.\build.ps1 -Clean

# 构建并测试
.\build.ps1 -Test

# 清理、构建、测试(完整流程)
.\build.ps1 -Clean -Test -Mode release

代码格式化

Rust:

# 格式化所有代码
cargo fmt --all

# 检查格式(不修改)
cargo fmt --all -- --check

# Clippy 检查
cargo clippy --all-targets --all-features -- -D warnings

Python:

# Black 格式化
black src/python

# isort 排序导入
isort src/python

# 检查格式(不修改)
black --check src/python
isort --check-only src/python

Git Hooks

安装 pre-commit hooks 自动检查代码质量:

# 安装 pre-commit
pip install pre-commit

# 安装 hooks
pre-commit install

# 手动运行所有 hooks
pre-commit run --all-files

监控和健康检查

Web 监控面板

访问 http://localhost:8000 查看实时监控面板,包括:

  • 系统状态: gRPC 连接、引擎状态、运行时间
  • 连接状态: Binance API、WebSocket 连接状态
  • 性能指标: 订单延迟、市场数据延迟、吞吐量
  • 持仓信息: 实时持仓、盈亏统计
  • 订单历史: 最近订单记录

特性:

  • 自动刷新(每 5 秒)
  • 自动重连(Rust 服务重启后自动恢复)
  • 优雅降级(服务断开时显示友好提示)

健康检查

# 检查系统健康状态
curl http://localhost:8080/health

# 返回示例
{
  "healthy": true,
  "timestamp": "2025-11-09T12:00:00Z",
  "uptime_seconds": 3600,
  "components": {
    "api_connection": {"connected": true},
    "websocket_connection": {"connected": true},
    "order_manager": {"running": true},
    "position_manager": {"running": true}
  }
}

日志系统

日志位置

  • 日志文件存储在 logs/ 目录
  • 每日自动轮转,保留 30 天
  • 文件命名格式: <component>.log.YYYY-MM-DD

日志级别

Rust (使用 RUST_LOG 环境变量):

# Linux/macOS
export RUST_LOG=debug
export RUST_LOG=trading_engine=debug,binance_api=info

# Windows
$env:RUST_LOG="debug"

Python (在配置文件中设置):

{
  "system": {
    "log_level": "DEBUG"
  }
}

可用级别: TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL

查看日志

# 实时查看日志
tail -f logs/trading-engine.log

# Windows PowerShell
Get-Content logs/trading-engine.log -Wait -Tail 50

# 搜索错误
grep ERROR logs/*.log

# Windows PowerShell
Select-String -Path logs/*.log -Pattern "ERROR"

项目结构

.
├── src/
│   ├── rust/                    # Rust 核心组件
│   │   ├── binance-api/        # 币安 API 客户端
│   │   ├── trading-engine/     # 交易引擎
│   │   ├── market-data/        # 行情数据处理
│   │   └── common/             # 共享工具
│   └── python/                  # Python 应用层
│       ├── config/             # 配置管理
│       ├── strategy/           # 交易策略
│       ├── manager/            # 策略管理
│       ├── notifier/           # 通知服务
│       ├── storage/            # 数据存储
│       └── utils/              # 工具函数
├── config/                      # 配置文件
├── data/                        # 数据目录
├── logs/                        # 日志目录
├── Cargo.toml                   # Rust 工作空间配置
├── pyproject.toml              # Python 项目配置
├── requirements.txt            # Python 依赖
├── Makefile                    # 构建脚本 (Linux/macOS)
└── build.ps1                   # 构建脚本 (Windows)

详细结构请参考 project-structure.md

常见问题

Rust 编译问题

问题: 编译速度慢

# 使用增量编译(默认开启)
# 使用 sccache 缓存
cargo install sccache
export RUSTC_WRAPPER=sccache

问题: 链接错误

# 清理并重新编译
cargo clean
cargo build

Python 问题

问题: 模块导入错误

# 确保在项目根目录
export PYTHONPATH="${PYTHONPATH}:$(pwd)"

# Windows
$env:PYTHONPATH="$env:PYTHONPATH;$(pwd)"

问题: 依赖冲突

# 使用虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/macOS
.\venv\Scripts\activate   # Windows

pip install -r requirements.txt

Web 面板问题

问题: Web 面板显示 "gRPC Connection Disconnected"

解决方案:

  1. 确保 Rust 交易引擎正在运行
  2. 检查 gRPC 端口 50051 是否被占用
  3. 刷新浏览器页面,Web 面板会自动尝试重连

问题: 数据库错误 "unable to open database file"

解决方案:

# 创建数据目录
mkdir -p data

# 初始化数据库
python init_database.py

问题: Rust 服务重启后 Web 面板无数据

这是正常的,Web 面板会在下次请求时自动重连。只需:

  1. 等待几秒钟
  2. 或手动点击页面上的"刷新"按钮

技术栈

后端(Rust)

  • tonic - gRPC 框架
  • tokio - 异步运行时
  • rust_decimal - 精确数值计算
  • serde - 序列化/反序列化
  • reqwest - HTTP 客户端
  • tokio-tungstenite - WebSocket 客户端

前端(Python)

  • grpcio - gRPC 客户端
  • sqlalchemy - ORM 数据库
  • pandas - 数据分析
  • asyncio - 异步支持
  • loguru - 日志系统

通信协议

  • Protocol Buffers - 数据序列化
  • gRPC (HTTP/2) - RPC 通信
  • WebSocket - 实时数据流

实现状态

✅ 已完成

  • Rust 核心交易引擎
  • 币安 API 集成(REST + WebSocket)
  • gRPC 服务定义(8个接口)
  • Rust gRPC 服务端实现
  • Python gRPC 客户端实现
  • 订单管理模块
  • 持仓管理模块
  • 风险控制模块
  • 市场数据处理模块
  • 数据存储模块(SQLAlchemy ORM)
  • 配置管理系统
  • 钉钉通知服务
  • 日志和监控系统
  • 完整测试覆盖(36个测试)
  • Web 监控面板(FastAPI)
  • gRPC 自动重连机制
  • 健康检查服务
  • 连接状态监控

🚧 进行中

  • 网格交易策略实现
  • 趋势跟踪策略实现
  • 海龟交易法策略
  • 回测引擎
  • 增强的监控和可观测性
    • 市场数据延迟跟踪
    • API 错误率统计
    • Prometheus 指标导出
    • OpenTelemetry 分布式追踪
    • 告警系统
    • 性能分析报告

📝 计划中

  • 机器学习策略
  • 套利策略
  • 做市策略
  • 期货交易支持
  • 多交易所支持(火币、OKX)
  • 性能监控面板
  • 移动端 App

文档导航

📖 系统概览

  • 系统简介(中文) - 完整的系统介绍
    • 系统架构和技术栈
    • 交易原理和策略详解(网格、趋势跟踪、海龟交易法)
    • 核心模块实现说明
    • 部署方案和配置指南
    • 性能指标和风险提示
    • 常见问题解答

快速入门

核心文档

规范文档

模块文档

许可证

MIT License

免责声明

本系统仅供学习和研究使用。加密货币交易存在风险,请谨慎使用。作者不对任何交易损失负责。

About

高频量化交易系统,采用 Rust + Python 混合架构,专为量化交易设计。高性能: Rust 核心引擎,极低的延迟。灵活策略: Python 策略层,快速开发和迭代

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors