# 智能期货期权分析系统 - 部署文档

## 前端部署

### 静态部署（当前方式）

**适用场景**: 纯前端演示、无后端API依赖

**步骤**:

1. 构建生产版本
```bash
cd /mnt/okcomputer/output/app
npm run build
```

2. 部署到静态服务器
```bash
# 部署到任意静态服务器
# 例如: Nginx, Apache, Vercel, Netlify, GitHub Pages
```

3. 使用Kimi部署
```bash
# 已自动部署到
# https://ow45rp4dokfss.ok.kimi.link
```

### Nginx配置示例

```nginx
server {
    listen 80;
    server_name futures.example.com;
    root /var/www/futures-analysis/dist;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    # 静态资源缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Gzip压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;
}
```

---

## 后端部署（待实现）

### 技术栈建议

- **语言**: Node.js / Python / Go
- **框架**: NestJS / FastAPI / Gin
- **数据库**: PostgreSQL + Redis
- **消息队列**: Kafka / RabbitMQ
- **容器**: Docker + Kubernetes

### 服务架构

```
┌─────────────────────────────────────────────────────────────┐
│                        Load Balancer                        │
└─────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
┌───────▼──────┐    ┌────────▼────────┐   ┌───────▼──────┐
│   API Gateway │    │   API Gateway   │   │   API Gateway │
└───────┬───────┘    └────────┬────────┘   └───────┬───────┘
        │                     │                     │
        └─────────────────────┼─────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
┌───────▼──────┐    ┌────────▼────────┐   ┌───────▼──────┐
│  User Service │    │ Market Service  │   │  AI Service  │
└───────┬───────┘    └────────┬────────┘   └───────┬───────┘
        │                     │                     │
        └─────────────────────┼─────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
┌───────▼──────┐    ┌────────▼────────┐   ┌───────▼──────┐
│  PostgreSQL   │    │     Redis       │   │    Kafka     │
└───────────────┘    └─────────────────┘   └───────────────┘
```

### Docker部署

#### 1. 创建Dockerfile

```dockerfile
# 前端Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
```

#### 2. Docker Compose配置

```yaml
version: '3.8'

services:
  frontend:
    build: ./frontend
    ports:
      - "80:80"
    depends_on:
      - backend

  backend:
    build: ./backend
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://user:pass@postgres:5432/futures
      - REDIS_URL=redis://redis:6379
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=futures
    volumes:
      - postgres_data:/var/lib/postgresql/data

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data

  kafka:
    image: confluentinc/cp-kafka:latest
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092

  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181

volumes:
  postgres_data:
  redis_data:
```

#### 3. 启动服务

```bash
docker-compose up -d
```

---

## 数据库设计

### PostgreSQL表结构

```sql
-- 品种表
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    symbol VARCHAR(20) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    exchange VARCHAR(50),
    unit VARCHAR(20),
    min_change DECIMAL(10, 4),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- K线数据表（按品种和周期分表）
CREATE TABLE kline_sc_15m (
    time TIMESTAMP NOT NULL,
    open DECIMAL(10, 2) NOT NULL,
    high DECIMAL(10, 2) NOT NULL,
    low DECIMAL(10, 2) NOT NULL,
    close DECIMAL(10, 2) NOT NULL,
    volume BIGINT NOT NULL,
    open_interest BIGINT,
    PRIMARY KEY (time)
);

-- 用户表
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    phone VARCHAR(20),
    avatar_url VARCHAR(255),
    membership_level INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 自选股表
CREATE TABLE watchlist (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    symbol VARCHAR(20) NOT NULL,
    alert_price DECIMAL(10, 2),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, symbol)
);

-- 价格预警表
CREATE TABLE price_alerts (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    symbol VARCHAR(20) NOT NULL,
    alert_type VARCHAR(20) NOT NULL, -- above, below
    alert_price DECIMAL(10, 2) NOT NULL,
    is_active BOOLEAN DEFAULT true,
    triggered_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 热点事件表
CREATE TABLE hot_events (
    id SERIAL PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    summary TEXT,
    impact VARCHAR(20) NOT NULL, -- bullish, bearish, neutral
    impact_level INTEGER NOT NULL,
    source VARCHAR(100),
    event_time TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 事件影响品种关联表
CREATE TABLE event_products (
    event_id INTEGER REFERENCES hot_events(id) ON DELETE CASCADE,
    symbol VARCHAR(20) NOT NULL,
    impact_confidence DECIMAL(3, 2),
    PRIMARY KEY (event_id, symbol)
);

-- 交易信号表
CREATE TABLE trading_signals (
    id SERIAL PRIMARY KEY,
    symbol VARCHAR(20) NOT NULL,
    timeframe VARCHAR(10) NOT NULL,
    signal_type VARCHAR(20) NOT NULL, -- buy, sell, neutral
    strength INTEGER NOT NULL,
    indicators JSONB,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 模拟交易记录表
CREATE TABLE paper_trades (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
    symbol VARCHAR(20) NOT NULL,
    direction VARCHAR(10) NOT NULL, -- long, short
    entry_price DECIMAL(10, 2) NOT NULL,
    exit_price DECIMAL(10, 2),
    quantity INTEGER NOT NULL,
    entry_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    exit_time TIMESTAMP,
    pnl DECIMAL(10, 2),
    status VARCHAR(20) DEFAULT 'open' -- open, closed
);

-- 创建索引
CREATE INDEX idx_kline_time ON kline_sc_15m(time);
CREATE INDEX idx_watchlist_user ON watchlist(user_id);
CREATE INDEX idx_alerts_user ON price_alerts(user_id);
CREATE INDEX idx_signals_symbol ON trading_signals(symbol, created_at);
```

### Redis数据结构

```
# 实时行情
market:tick:{symbol} -> Hash
  - price
  - change
  - volume
  - timestamp

# K线数据（最近100条）
market:kline:{symbol}:{period} -> Sorted Set

# 用户会话
session:{token} -> Hash
  - user_id
  - expires_at

# 价格预警
alert:{symbol} -> Sorted Set (score: alert_price)

# 热点事件缓存
events:hot -> List (最近20条)
```

---

## 环境变量配置

### 前端环境变量

```bash
# .env.production
VITE_API_BASE_URL=https://api.futures.example.com
VITE_WS_URL=wss://ws.futures.example.com
VITE_APP_NAME=期货智析
```

### 后端环境变量

```bash
# .env
NODE_ENV=production
PORT=3000

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/futures
REDIS_URL=redis://localhost:6379

# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=1h
JWT_REFRESH_EXPIRES_IN=7d

# Market Data
MARKET_DATA_API_KEY=your-api-key
MARKET_DATA_WS_URL=wss://market-data.example.com

# External APIs
OPENAI_API_KEY=your-openai-key
SENDGRID_API_KEY=your-sendgrid-key
```

---

## CI/CD配置

### GitHub Actions

```yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run tests
        run: npm test
        
      - name: Build
        run: npm run build
        
      - name: Deploy to server
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          source: "dist/"
          target: "/var/www/futures-analysis"
```

---

## 监控与日志

### 监控指标

- **应用指标**: QPS、响应时间、错误率
- **业务指标**: 活跃用户数、交易信号准确率
- **系统指标**: CPU、内存、磁盘、网络

### 日志收集

```yaml
# docker-compose.logging.yml
version: '3.8'

services:
  elasticsearch:
    image: elasticsearch:8.0.0
    environment:
      - discovery.type=single-node
    ports:
      - "9200:9200"

  logstash:
    image: logstash:8.0.0
    volumes:
      - ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf

  kibana:
    image: kibana:8.0.0
    ports:
      - "5601:5601"
```

---

## 安全建议

1. **HTTPS**: 强制使用HTTPS
2. **CORS**: 配置跨域白名单
3. **Rate Limiting**: 接口限流
4. **Input Validation**: 输入验证
5. **SQL Injection**: 使用参数化查询
6. **XSS**: 输出转义
7. **CSRF**: 令牌验证
