# express-curd-auto-backend **Repository Path**: dzy_gitee/express-curd-auto-backend ## Basic Information - **Project Name**: express-curd-auto-backend - **Description**: 自动生成curd 初始化操作 - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-08-29 - **Last Updated**: 2025-08-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 🤖 OKX Trading Robot Backend [![Node.js](https://img.shields.io/badge/Node.js-16+-green.svg)](https://nodejs.org/) [![Express](https://img.shields.io/badge/Express-4.18+-blue.svg)](https://expressjs.com/) [![MySQL](https://img.shields.io/badge/MySQL-8.0+-orange.svg)](https://www.mysql.com/) [![Redis](https://img.shields.io/badge/Redis-6.0+-red.svg)](https://redis.io/) [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Build Status](https://img.shields.io/badge/Build-Passing-brightgreen.svg)]() > 🚀 专业的OKX自动交易机器人后端API服务,提供完整的交易策略管理、用户认证、实时监控等功能 ## 📋 目录 - [✨ 功能特性](#-功能特性) - [🖼️ 项目截图](#️-项目截图) - [🏗️ 系统架构](#️-系统架构) - [📋 系统要求](#-系统要求) - [🚀 快速开始](#-快速开始) - [⚙️ 配置说明](#️-配置说明) - [🔧 API文档](#-api文档) - [🧪 测试](#-测试) - [📦 部署](#-部署) - [🔒 安全特性](#-安全特性) - [📊 监控系统](#-监控系统) - [📁 项目结构](#-项目结构) - [🤝 贡献指南](#-贡献指南) - [📄 许可证](#-许可证) ## ✨ 功能特性 ### 🔐 用户认证与授权 - **JWT + 会话管理** - 双重认证机制 - **角色权限控制** - 细粒度权限管理 - **API密钥管理** - 安全的API访问控制 - **密码策略** - 强密码要求与加密 ### 💾 数据管理 - **MySQL数据库** - 关系型数据存储 - **Redis缓存** - 高性能数据缓存 - **数据备份** - 自动备份机制 - **数据迁移** - 版本化数据库管理 ### 🤖 交易功能 - **策略管理** - 交易策略配置与执行 - **订单管理** - 订单创建、修改、取消 - **仓位管理** - 实时仓位监控 - **历史记录** - 完整的交易历史 ### 🔄 任务调度 - **定时任务** - 自动化任务执行 - **任务监控** - 实时任务状态监控 - **失败重试** - 智能重试机制 - **日志记录** - 详细的任务执行日志 ### 🛡️ 安全防护 - **多层安全中间件** - 全方位安全防护 - **速率限制** - 防止API滥用 - **XSS防护** - 跨站脚本攻击防护 - **SQL注入防护** - 数据库安全 ### 📊 监控系统 - **性能监控** - 实时性能指标 - **健康检查** - 系统状态监控 - **日志管理** - 结构化日志记录 - **告警系统** - 异常情况告警 ## 🖼️ 项目截图 ### 📱 API文档界面 ``` ┌─────────────────────────────────────────────────────────────┐ │ Swagger API Documentation │ ├─────────────────────────────────────────────────────────────┤ │ 🔍 /api/auth/login │ │ 📝 POST - 用户登录 │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ Request Body: │ │ │ │ { │ │ │ │ "email": "user@example.com", │ │ │ │ "password": "securePassword123" │ │ │ │ } │ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ │ ✅ Response: 200 OK │ │ { │ │ "success": true, │ │ "token": "eyJhbGciOiJIUzI1NiIs...", │ │ "user": { ... } │ │ } │ └─────────────────────────────────────────────────────────────┘ ``` ### 📊 系统监控面板 ``` ┌─────────────────────────────────────────────────────────────┐ │ System Monitor Dashboard │ ├─────────────────────────────────────────────────────────────┤ │ 📈 Performance Metrics │ │ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │ │ │ CPU Usage │ Memory │ Response │ Error Rate │ │ │ │ 45% │ 2.1GB/8GB │ 120ms │ 0.02% │ │ │ └─────────────┴─────────────┴─────────────┴─────────────┘ │ │ │ │ 🔄 Active Connections: 1,247 │ │ 📊 Requests/min: 1,890 │ │ ⚡ Uptime: 15d 8h 32m │ │ 🟢 Status: Healthy │ └─────────────────────────────────────────────────────────────┘ ``` ### 🗄️ 数据库结构 ``` ┌─────────────────────────────────────────────────────────────┐ │ Database Schema │ ├─────────────────────────────────────────────────────────────┤ │ 👥 Users 📊 TradingStrategies │ │ ├── id (PK) ├── id (PK) │ │ ├── email ├── name │ │ ├── password ├── description │ │ ├── role ├── parameters │ │ └── created_at └── user_id (FK) │ │ │ │ 📈 TradingOrders 📊 TradingPositions │ │ ├── id (PK) ├── id (PK) │ │ ├── symbol ├── symbol │ │ ├── side ├── size │ │ ├── price ├── entry_price │ │ └── status └── pnl │ └─────────────────────────────────────────────────────────────┘ ``` ## 🏗️ 系统架构 ``` ┌─────────────────────────────────────────────────────────────┐ │ Frontend │ │ (React/Vue/Angular) │ └─────────────────────┬───────────────────────────────────────┘ │ HTTPS/WebSocket ┌─────────────────────▼───────────────────────────────────────┐ │ Load Balancer │ │ (Nginx/HAProxy) │ └─────────────────────┬───────────────────────────────────────┘ │ ┌─────────────────────▼───────────────────────────────────────┐ │ API Gateway │ │ (Express.js) │ ├─────────────────────────────────────────────────────────────┤ │ 🔐 Authentication 📊 Rate Limiting 🛡️ Security │ │ 📝 Validation 🔄 Caching 📈 Monitoring │ └─────────────────────┬───────────────────────────────────────┘ │ ┌─────────────────────▼───────────────────────────────────────┐ │ Business Logic │ │ (Controllers/Services) │ ├─────────────────────────────────────────────────────────────┤ │ 👤 User Management 🤖 Trading Logic 📊 Analytics │ │ 🔑 API Key Mgmt 📈 Strategy Exec 📝 Notifications │ └─────────────────────┬───────────────────────────────────────┘ │ ┌─────────────────────▼───────────────────────────────────────┐ │ Data Layer │ ├─────────────────────────────────────────────────────────────┤ │ 🗄️ MySQL Database 🔴 Redis Cache 📁 File Storage │ │ 📊 Trading Data ⚡ Session Store 📄 Logs │ └─────────────────────────────────────────────────────────────┘ ``` ## 📋 系统要求 ### 最低要求 - **Node.js** >= 16.0.0 - **MySQL** >= 8.0 - **Redis** >= 6.0 - **内存** >= 2GB RAM - **存储** >= 10GB 可用空间 ### 推荐配置 - **Node.js** >= 18.0.0 - **MySQL** >= 8.0 - **Redis** >= 7.0 - **内存** >= 4GB RAM - **存储** >= 50GB SSD - **CPU** >= 2核心 ## 🚀 快速开始 ### 1️⃣ 克隆项目 ```bash git clone https://github.com/yourusername/okx-robot-backend.git cd okx-robot-backend ``` ### 2️⃣ 安装依赖 ```bash # 使用 npm npm install # 或使用 pnpm (推荐) pnpm install # 或使用 yarn yarn install ``` ### 3️⃣ 环境配置 ```bash # 复制环境配置文件 cp .env.example .env # 编辑配置文件 nano .env ``` ### 4️⃣ 数据库初始化 ```bash # 初始化数据库 npm run db:init # 或使用脚本 npm run db:init:shell # Linux/Mac npm run db:init:windows # Windows ``` ### 5️⃣ 启动服务 ```bash # 开发环境 npm run dev # 生产环境 npm start # 使用PM2 (推荐生产环境) npm run pm2:start ``` ### 6️⃣ 验证安装 访问以下端点验证服务是否正常运行: - 🔍 **健康检查**: `http://localhost:3000/health` - 📚 **API文档**: `http://localhost:3000/api-docs` - ℹ️ **API信息**: `http://localhost:3000/api/info` ## ⚙️ 配置说明 ### 环境变量配置 创建 `.env` 文件并配置以下参数: ```env # ======================================== # 应用配置 # ======================================== NODE_ENV=development PORT=3000 FRONTEND_URL=http://localhost:3000 API_VERSION=v1 # ======================================== # 数据库配置 # ======================================== DB_HOST=localhost DB_PORT=3306 DB_USER=root DB_PASSWORD=your_password DB_NAME=okx_robot DB_DIALECT=mysql # ======================================== # Redis配置 # ======================================== REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD= REDIS_DB=0 # ======================================== # JWT配置 # ======================================== JWT_SECRET=your-super-secret-jwt-key-here JWT_EXPIRE=30d JWT_REFRESH_SECRET=your-super-secret-refresh-key JWT_REFRESH_EXPIRE=7d # ======================================== # 安全配置 # ======================================== BCRYPT_ROUNDS=12 PASSWORD_MIN_LENGTH=8 SESSION_SECRET=your-session-secret-key # ======================================== # OKX API配置 # ======================================== OKX_API_KEY=your-okx-api-key OKX_SECRET_KEY=your-okx-secret-key OKX_PASSPHRASE=your-okx-passphrase OKX_SANDBOX=true # ======================================== # 邮件配置 (可选) # ======================================== SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your-email@gmail.com SMTP_PASS=your-app-password ``` ### 数据库配置 项目支持多种数据库配置: ```javascript // 开发环境 { host: 'localhost', port: 3306, username: 'root', password: 'password', database: 'okx_robot_dev', dialect: 'mysql' } // 生产环境 { host: process.env.DB_HOST, port: process.env.DB_PORT, username: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, dialect: 'mysql', pool: { max: 20, min: 5, acquire: 30000, idle: 10000 } } ``` ## 🔧 API文档 ### 认证端点 #### 用户登录 ```http POST /api/auth/login Content-Type: application/json { "email": "user@example.com", "password": "securePassword123" } ``` #### 用户注册 ```http POST /api/auth/register Content-Type: application/json { "email": "newuser@example.com", "password": "securePassword123", "confirmPassword": "securePassword123", "firstName": "John", "lastName": "Doe" } ``` ### 用户管理端点 #### 获取用户信息 ```http GET /api/users/profile Authorization: Bearer ``` #### 更新用户信息 ```http PUT /api/users/profile Authorization: Bearer Content-Type: application/json { "firstName": "John", "lastName": "Smith", "phone": "+1234567890" } ``` ### 交易策略端点 #### 创建策略 ```http POST /api/strategies Authorization: Bearer Content-Type: application/json { "name": "MA Crossover Strategy", "description": "Moving Average Crossover Strategy", "symbol": "BTC-USDT", "parameters": { "fastPeriod": 10, "slowPeriod": 20, "quantity": 0.001 } } ``` #### 获取策略列表 ```http GET /api/strategies Authorization: Bearer ``` ### 订单管理端点 #### 创建订单 ```http POST /api/orders Authorization: Bearer Content-Type: application/json { "symbol": "BTC-USDT", "side": "buy", "type": "market", "quantity": 0.001 } ``` #### 获取订单历史 ```http GET /api/orders Authorization: Bearer ``` ## 🧪 测试 ### 运行测试 ```bash # 运行所有测试 npm test # 运行测试并生成覆盖率报告 npm run test:coverage # 监听模式运行测试 npm run test:watch # 运行特定测试文件 npm test -- --testPathPattern=auth.test.js ``` ### 测试覆盖率 项目包含完整的测试套件: - ✅ **单元测试** - 核心功能测试 - ✅ **集成测试** - API端点测试 - ✅ **数据库测试** - 数据操作测试 - ✅ **安全测试** - 安全功能测试 ### 测试示例 ```javascript // 用户认证测试 describe('Auth Controller', () => { test('should login user with valid credentials', async () => { const response = await request(app) .post('/api/auth/login') .send({ email: 'test@example.com', password: 'password123' }); expect(response.status).toBe(200); expect(response.body).toHaveProperty('token'); }); }); ``` ## 📦 部署 ### 使用PM2部署 (推荐) ```bash # 安装PM2 npm install -g pm2 # 启动应用 npm run pm2:start # 查看应用状态 npm run pm2:monit # 查看日志 npm run pm2:logs # 重启应用 npm run pm2:restart # 停止应用 npm run pm2:stop ``` ### Docker部署 创建 `Dockerfile`: ```dockerfile FROM node:18-alpine # 设置工作目录 WORKDIR /app # 复制package文件 COPY package*.json ./ # 安装依赖 RUN npm ci --only=production # 复制源代码 COPY . . # 创建非root用户 RUN addgroup -g 1001 -S nodejs RUN adduser -S nodejs -u 1001 # 更改文件所有权 RUN chown -R nodejs:nodejs /app USER nodejs # 暴露端口 EXPOSE 3000 # 健康检查 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 # 启动应用 CMD ["npm", "start"] ``` 创建 `docker-compose.yml`: ```yaml version: '3.8' services: app: build: . ports: - "3000:3000" environment: - NODE_ENV=production - DB_HOST=mysql - REDIS_HOST=redis depends_on: - mysql - redis restart: unless-stopped mysql: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: rootpassword MYSQL_DATABASE: okx_robot volumes: - mysql_data:/var/lib/mysql restart: unless-stopped redis: image: redis:7-alpine volumes: - redis_data:/data restart: unless-stopped volumes: mysql_data: redis_data: ``` ### Nginx配置 ```nginx server { listen 80; server_name your-domain.com; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; } } ``` ## 🔒 安全特性 ### 安全中间件 项目集成了多层安全防护: ```javascript // 安全头设置 app.use(helmet()); // 速率限制 app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, // 15分钟 max: 100 // 限制每个IP 15分钟内最多100个请求 })); // XSS防护 app.use(xss()); // SQL注入防护 app.use(mongoSanitize()); // 请求大小限制 app.use(express.json({ limit: '10mb' })); ``` ### 认证授权 - **JWT令牌认证** - 无状态认证 - **刷新令牌机制** - 安全的令牌更新 - **会话管理** - Redis存储会话数据 - **角色权限控制** - 基于角色的访问控制 ### 数据加密 - **密码加密** - bcrypt哈希加密 - **敏感数据加密** - AES加密存储 - **传输加密** - HTTPS/TLS加密 ## 📊 监控系统 ### 性能监控 项目包含完整的性能监控系统: ```javascript // 请求响应时间监控 app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; logger.info(`${req.method} ${req.path} - ${res.statusCode} - ${duration}ms`); }); next(); }); ``` ### 健康检查 访问 `/health` 端点获取系统状态: ```json { "status": "healthy", "timestamp": "2024-01-01T00:00:00.000Z", "uptime": 3600, "environment": "production", "version": "1.0.0", "services": { "database": "connected", "redis": "connected", "okx_api": "connected" }, "metrics": { "memory_usage": "45%", "cpu_usage": "12%", "active_connections": 1247 } } ``` ### 日志系统 结构化日志记录: ```javascript // 日志配置 const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), new winston.transports.File({ filename: 'logs/combined.log' }) ] }); ``` ## 📁 项目结构 ``` backend/ ├── 📁 src/ # 源代码目录 │ ├── 📁 config/ # 配置文件 │ │ ├── config.js # 主配置文件 │ │ ├── database.js # 数据库配置 │ │ └── env.js # 环境变量配置 │ ├── 📁 controllers/ # 控制器层 │ │ ├── authController.js # 认证控制器 │ │ ├── userController.js # 用户控制器 │ │ └── ApiKeysController.js # API密钥控制器 │ ├── 📁 middleware/ # 中间件 │ │ ├── authMiddleware.js # 认证中间件 │ │ ├── errorMiddleware.js # 错误处理中间件 │ │ ├── securityMiddleware.js # 安全中间件 │ │ └── validationMiddleware.js # 验证中间件 │ ├── 📁 models/ # 数据模型 │ │ ├── index.js # 模型索引 │ │ ├── Users.js # 用户模型 │ │ ├── TradingStrategies.js # 交易策略模型 │ │ ├── TradingOrders.js # 交易订单模型 │ │ └── TradingPositions.js # 交易仓位模型 │ ├── 📁 routes/ # 路由定义 │ │ ├── authRoutes.js # 认证路由 │ │ ├── userRoutes.js # 用户路由 │ │ └── ApiKeysRoutes.js # API密钥路由 │ ├── 📁 utils/ # 工具函数 │ │ ├── cache.js # 缓存工具 │ │ ├── logger.js # 日志工具 │ │ └── scheduler.js # 调度工具 │ ├── 📁 validators/ # 数据验证 │ │ └── ApiKeysValidator.js # API密钥验证 │ └── app.js # 应用入口文件 ├── 📁 tools/ # 工具脚本 │ ├── 📁 express-db-generator/ # 数据库生成器 │ └── 📁 express-sequelize-generator/ # Sequelize生成器 ├── 📁 scripts/ # 脚本文件 ├── 📄 package.json # 项目配置 ├── 📄 ecosystem.config.js # PM2配置 ├── 📄 .env.example # 环境变量示例 └── 📄 README.md # 项目说明 ``` ## 🤝 贡献指南 我们欢迎所有形式的贡献! ### 贡献流程 1. **Fork项目** - 点击右上角的Fork按钮 2. **创建分支** - `git checkout -b feature/amazing-feature` 3. **提交更改** - `git commit -m 'Add amazing feature'` 4. **推送分支** - `git push origin feature/amazing-feature` 5. **创建Pull Request** - 提交合并请求 ### 开发规范 #### 代码风格 - 使用ESLint和Prettier保持代码风格一致 - 遵循JavaScript标准规范 - 添加适当的注释和文档 #### 提交规范 ``` feat: 新功能 fix: 修复bug docs: 文档更新 style: 代码格式调整 refactor: 代码重构 test: 测试相关 chore: 构建过程或辅助工具的变动 ``` #### 测试要求 - 新功能必须包含测试用例 - 修复bug必须包含回归测试 - 测试覆盖率不低于80% ### 问题反馈 如果您发现了bug或有功能建议,请: 1. 查看[Issues](https://github.com/yourusername/okx-robot-backend/issues)页面 2. 创建新的Issue,详细描述问题 3. 提供复现步骤和环境信息 ## 📄 许可证 本项目采用 [MIT License](LICENSE) 许可证。 ``` MIT License Copyright (c) 2024 OKX Trading Robot Backend Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` ## 📞 联系我们 - 🌐 **项目主页**: [https://github.com/yourusername/okx-robot-backend](https://github.com/yhemeo613/express-curd-auto-backend) - 📧 **邮箱**: dzyperson@163.com - 💬 **讨论区**: [GitHub Discussions](https://github.com/yhemeo613/express-curd-auto-backend/discussions) - 🐛 **问题反馈**: [GitHub Issues](https://github.com/yhemeo613/express-curd-auto-backend/issues) ---
**如果这个项目对您有帮助,请给它一个 ⭐️ Star!** Made with ❤️ by [Your Name](https://github.com/yhemeo613)