🇨🇳 简体中文
🇺🇸 English
🇯🇵 日本語
Skip to the content.

多通道交易 API

模块: channels

本模块提供多通道交易系统的完整管理接口,支持通道配置、状态监控、风险控制和性能分析。

📋 概述

多通道交易系统允许在单个交易会话中并行运行多个独立的交易通道(如激进、平衡、保守),每个通道有独立的资金配置、策略组合和风险参数。

核心功能

🔄 配置版本控制

Fire 支持通道配置的版本控制,允许动态更新配置并在必要时回滚到先前版本。

版本机制

graph LR
    V1[配置 v1] -->|更新| V2[配置 v2]
    V2 -->|更新| V3[配置 v3]
    V3 -->|回滚| V2
    V2 -->|回滚| V1

配置更新流程

  1. 当前版本: 系统维护 current_config_version 标识当前生效的配置
  2. 待定版本: 更新配置后创建新版本,标记为 pending_config_version
  3. 版本激活: 通道重启或重载后新版本生效
  4. 版本回滚: 可回滚到任意历史版本

相关端点

回滚配置

POST /api/v1/sessions/{session_id}/config/rollback

回滚到指定的历史配置版本。

请求体:

{
  "target_version": 2
}

参数说明:

响应:

{
  "session_id": "session_123",
  "previous_version": 3,
  "current_version": 2,
  "rollback_time": "2024-01-15T14:30:00Z",
  "message": "配置已回滚到版本 2"
}

错误响应:

{
  "detail": "目标版本不存在: 5"
}

HTTP 状态码:

获取配置历史

GET /api/v1/sessions/{session_id}/config/history

获取配置变更历史记录。

查询参数:

响应:

{
  "session_id": "session_123",
  "current_version": 3,
  "history": [
    {
      "version": 3,
      "timestamp": "2024-01-15T14:00:00Z",
      "changes": {
        "aggressive_channel": {
          "capital_allocation": 0.45,
          "leverage": 2.5
        }
      },
      "changed_by": "user_123",
      "is_current": true
    },
    {
      "version": 2,
      "timestamp": "2024-01-14T10:00:00Z",
      "changes": {
        "balanced_channel": {
          "strategy_weights": {
            "MACD": 0.3,
            "RSI": 0.3
          }
        }
      },
      "changed_by": "user_123",
      "is_current": false
    }
  ],
  "total_versions": 3
}

🔌 WebSocket 实时更新

Fire 提供 WebSocket 接口实现通道状态的实时推送,支持自动重连和数据补偿机制。

WebSocket 连接

连接地址: ws://localhost:8000/ws/trading/{session_id}

认证方式: 通过查询参数传递 token

ws://localhost:8000/ws/trading/session_123?token=your_jwt_token

消息格式

服务端推送消息

{
  "type": "channel_update",
  "data": {
    "channel_id": "aggressive",
    "status": "running",
    "metrics": {
      "total_pnl": 1250.50,
      "win_rate": 0.58,
      "total_trades": 45
    }
  },
  "timestamp": "2024-01-15T14:30:00.123Z"
}

消息类型:

客户端发送消息

{
  "type": "ping"
}

心跳机制

// 客户端示例
const ws = new WebSocket('ws://localhost:8000/ws/sessions/session_123/channels?token=xxx');

// 启动心跳
const heartbeatInterval = setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'ping' }));
  }
}, 15000);

// 监听 pong 响应
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  if (message.type === 'pong') {
    console.log('Heart beat OK');
  }
};

自动重连机制

当 WebSocket 连接中断时,客户端应实施指数退避重连策略。

重连参数

重连流程

stateDiagram-v2
    [*] --> 已连接: connect()
    已连接 --> 断开连接: 网络中断/服务器关闭
    断开连接 --> 重连中: 尝试重连(1s)
    重连中 --> 已连接: 成功
    重连中 --> 重连中: 失败,延迟3s
    重连中 --> 重连中: 失败,延迟10s
    重连中 --> 连接失败: 3次失败
    连接失败 --> [*]: 显示错误提示

实现示例

class ChannelWebSocket {
  constructor(sessionId, token) {
    this.sessionId = sessionId;
    this.token = token;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 3;
    this.reconnectDelays = [1000, 3000, 10000];
  }

  connect() {
    this.ws = new WebSocket(
      `ws://localhost:8000/ws/sessions/${this.sessionId}/channels?token=${this.token}`
    );

    this.ws.onopen = () => {
      console.log('WebSocket connected');
      this.reconnectAttempts = 0; // 重置重连计数
    };

    this.ws.onclose = (event) => {
      if (event.code !== 1000) { // 非正常关闭
        this.attemptReconnect();
      }
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }

  attemptReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnect attempts reached');
      alert('连接失败,请刷新页面');
      return;
    }

    const delay = this.reconnectDelays[
      Math.min(this.reconnectAttempts, this.reconnectDelays.length - 1)
    ];

    console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`);

    setTimeout(() => {
      this.reconnectAttempts++;
      this.connect();
    }, delay);
  }
}

数据补偿机制

重连成功后,客户端应请求断线期间的数据更新。

获取增量更新

GET /api/v1/sessions/{session_id}/updates

查询参数:

响应:

{
  "session_id": "session_123",
  "updates": [
    {
      "type": "channel_update",
      "data": {
        "channel_id": "aggressive",
        "status": "running"
      },
      "timestamp": "2024-01-15T14:31:00.123Z"
    },
    {
      "type": "channel_metrics",
      "data": {
        "channel_id": "aggressive",
        "total_pnl": 1255.80
      },
      "timestamp": "2024-01-15T14:31:15.456Z"
    }
  ],
  "count": 2,
  "last_timestamp": "2024-01-15T14:31:15.456Z"
}

使用流程

// 记录最后更新时间
let lastUpdateTime = new Date().toISOString();

ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  lastUpdateTime = message.timestamp; // 更新时间戳
};

// 重连成功后获取断线期间的更新
ws.onopen = async () => {
  if (reconnected) { // 非首次连接
    const response = await fetch(
      `/api/v1/sessions/${sessionId}/updates?since=${lastUpdateTime}`
    );
    const { updates } = await response.json();

    // 应用增量更新
    updates.forEach(update => {
      handleUpdate(update);
      lastUpdateTime = update.timestamp;
    });
  }
};

📖 API 端点详情

会话汇总

获取会话汇总

GET /api/v1/sessions/{session_id}/summary

获取会话的汇总信息,包含所有通道的聚合数据。

路径参数:

响应:

{
  "session_id": "session_123",
  "user_id": "user_456",
  "status": "running",
  "total_pnl": 2580.75,
  "total_capital": 100000.00,
  "capital_used": 45000.00,
  "total_trades": 127,
  "weighted_win_rate": 0.58,
  "channel_count": 3,
  "running_channels": 2,
  "total_orders": 150,
  "pending_orders": 5,
  "executed_orders": 145
}

通道管理

列出所有通道

GET /api/v1/sessions/{session_id}/channels

获取会话中所有通道的列表和状态。

响应:

{
  "session_id": "session_123",
  "channels": [
    {
      "channel_id": "aggressive",
      "channel_type": "AGGRESSIVE",
      "status": "running",
      "capital_allocation": 0.40,
      "metrics": {
        "total_pnl": 1250.50,
        "win_rate": 0.58,
        "total_trades": 45
      },
      "strategy_count": 3,
      "started_at": "2024-01-15T09:00:00Z",
      "error_message": null
    },
    {
      "channel_id": "balanced",
      "channel_type": "BALANCED",
      "status": "running",
      "capital_allocation": 0.40,
      "metrics": {
        "total_pnl": 880.25,
        "win_rate": 0.62,
        "total_trades": 52
      },
      "strategy_count": 4,
      "started_at": "2024-01-15T09:00:00Z",
      "error_message": null
    },
    {
      "channel_id": "conservative",
      "channel_type": "CONSERVATIVE",
      "status": "stopped",
      "capital_allocation": 0.20,
      "metrics": {
        "total_pnl": 450.00,
        "win_rate": 0.65,
        "total_trades": 30
      },
      "strategy_count": 2,
      "started_at": null,
      "error_message": null
    }
  ],
  "total_channels": 3,
  "running_channels": 2
}

获取通道详情

GET /api/v1/sessions/{session_id}/channels/{channel_id}

获取指定通道的详细状态信息。

路径参数:

响应: 同 ChannelStatusResponse 格式

获取通道指标

GET /api/v1/sessions/{session_id}/channels/{channel_id}/metrics

获取通道的详细绩效指标。

响应:

{
  "channel_id": "aggressive",
  "timestamp": "2024-01-15T14:30:00Z",
  "total_pnl": 1250.50,
  "realized_pnl": 980.30,
  "unrealized_pnl": 270.20,
  "daily_pnl": 125.50,
  "current_drawdown": 0.05,
  "total_trades": 45,
  "winning_trades": 26,
  "losing_trades": 19,
  "win_rate": 0.58,
  "active_positions": 3,
  "capital_used": 18000.00,
  "available_capital": 22000.00
}

获取通道分解

GET /api/v1/sessions/{session_id}/channels/breakdown

获取所有通道的性能分解对比。

响应:

{
  "session_id": "session_123",
  "timestamp": "2024-01-15T14:30:00Z",
  "channels": [
    {
      "channel_id": "aggressive",
      "contribution_to_pnl": 0.48,
      "capital_allocation": 0.40,
      "roi": 0.069,
      "sharpe_ratio": 1.45
    },
    {
      "channel_id": "balanced",
      "contribution_to_pnl": 0.34,
      "capital_allocation": 0.40,
      "roi": 0.022,
      "sharpe_ratio": 1.72
    },
    {
      "channel_id": "conservative",
      "contribution_to_pnl": 0.18,
      "capital_allocation": 0.20,
      "roi": 0.0225,
      "sharpe_ratio": 1.88
    }
  ]
}

通道控制

启动通道

POST /api/v1/sessions/{session_id}/channels/{channel_id}/start

启动指定通道的交易。

路径参数:

响应:

{
  "channel_id": "aggressive",
  "status": "running",
  "message": "通道已启动",
  "started_at": "2024-01-15T14:30:00Z"
}

错误响应:

{
  "detail": "通道已在运行中"
}

HTTP 状态码:

停止通道

POST /api/v1/sessions/{session_id}/channels/{channel_id}/stop

停止指定通道的交易。

响应:

{
  "channel_id": "aggressive",
  "status": "stopped",
  "message": "通道已停止",
  "stopped_at": "2024-01-15T15:00:00Z"
}

暂停通道

POST /api/v1/sessions/{session_id}/channels/{channel_id}/pause

暂停通道交易(保持持仓,停止新交易)。

响应:

{
  "channel_id": "aggressive",
  "status": "paused",
  "message": "通道已暂停",
  "paused_at": "2024-01-15T14:45:00Z"
}

恢复通道

POST /api/v1/sessions/{session_id}/channels/{channel_id}/resume

恢复暂停的通道。

响应:

{
  "channel_id": "aggressive",
  "status": "running",
  "message": "通道已恢复",
  "resumed_at": "2024-01-15T14:50:00Z"
}

风险管理

更新通道风险限制

PUT /api/v1/sessions/{session_id}/channels/{channel_id}/risk-limits

动态更新通道的风险限制参数。

请求体:

{
  "max_drawdown": 0.15,
  "max_daily_loss": 0.05,
  "max_loss_per_trade": 0.02,
  "leverage_limit": 3.0
}

参数说明:

响应:

{
  "channel_id": "aggressive",
  "updated_limits": {
    "max_drawdown": 0.15,
    "max_daily_loss": 0.05,
    "max_loss_per_trade": 0.02,
    "leverage_limit": 3.0
  },
  "effective_at": "2024-01-15T14:30:00Z",
  "message": "风险限制已更新"
}

错误响应:

{
  "detail": "max_drawdown 必须在 0.01 到 1.0 之间"
}

获取通道风险报告

GET /api/v1/sessions/{session_id}/channels/{channel_id}/risk-report

获取通道的实时风险报告。

响应:

{
  "channel_id": "aggressive",
  "timestamp": "2024-01-15T14:30:00Z",
  "daily_pnl": 125.50,
  "current_drawdown": 0.05,
  "trades_count": 45,
  "risk_utilization": {
    "drawdown_usage": 0.33,
    "daily_loss_usage": 0.25,
    "leverage_usage": 0.67
  },
  "is_halted": false,
  "warnings": [
    "杠杆使用率较高 (67%)"
  ]
}

获取所有风险报告

GET /api/v1/sessions/{session_id}/risk-reports

获取会话中所有通道的风险报告。

响应:

{
  "session_id": "session_123",
  "timestamp": "2024-01-15T14:30:00Z",
  "reports": [
    {
      "channel_id": "aggressive",
      "current_drawdown": 0.05,
      "is_halted": false,
      "warnings": ["杠杆使用率较高"]
    },
    {
      "channel_id": "balanced",
      "current_drawdown": 0.03,
      "is_halted": false,
      "warnings": []
    }
  ]
}

告警管理

获取告警摘要

GET /api/v1/sessions/{session_id}/alerts/summary

获取会话的告警摘要统计。

响应:

{
  "session_id": "session_123",
  "total_alerts": 15,
  "unacknowledged_alerts": 3,
  "alerts_by_level": {
    "critical": 1,
    "warning": 10,
    "info": 4
  },
  "alerts_by_type": {
    "risk_limit": 5,
    "performance": 6,
    "system": 4
  },
  "recent_critical_alerts_24h": 2
}

获取告警列表

GET /api/v1/sessions/{session_id}/alerts

获取会话的详细告警列表。

查询参数:

响应:

{
  "alerts": [
    {
      "alert_id": "alert_001",
      "channel_id": "aggressive",
      "level": "critical",
      "type": "risk_limit",
      "message": "回撤超过限制 (12% > 10%)",
      "timestamp": "2024-01-15T14:25:00Z",
      "acknowledged": false,
      "acknowledged_at": null,
      "acknowledged_by": null
    },
    {
      "alert_id": "alert_002",
      "channel_id": "balanced",
      "level": "warning",
      "type": "performance",
      "message": "胜率低于预期 (45% < 50%)",
      "timestamp": "2024-01-15T14:20:00Z",
      "acknowledged": true,
      "acknowledged_at": "2024-01-15T14:21:00Z",
      "acknowledged_by": "user_456"
    }
  ],
  "total": 15,
  "unacknowledged": 3
}

确认告警

POST /api/v1/sessions/{session_id}/alerts/{alert_id}/acknowledge

标记告警为已确认。

路径参数:

响应:

{
  "alert_id": "alert_001",
  "acknowledged": true,
  "acknowledged_at": "2024-01-15T14:30:00Z",
  "acknowledged_by": "user_456",
  "message": "告警已确认"
}

🔍 错误响应示例

Fire API 使用标准 HTTP 状态码和统一的错误响应格式。

错误响应格式

{
  "detail": "错误描述信息",
  "error_code": "ERROR_CODE",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/start"
}

常见错误场景

404 Not Found - 资源不存在

{
  "detail": "会话不存在: session_999",
  "error_code": "SESSION_NOT_FOUND",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_999/channels"
}
{
  "detail": "通道不存在: invalid_channel",
  "error_code": "CHANNEL_NOT_FOUND",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/invalid_channel"
}

400 Bad Request - 请求无效

{
  "detail": "通道已在运行中",
  "error_code": "CHANNEL_ALREADY_RUNNING",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/start"
}
{
  "detail": "max_drawdown 必须在 0.01 到 1.0 之间",
  "error_code": "INVALID_PARAMETER",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/risk-limits"
}
{
  "detail": "会话未初始化多通道",
  "error_code": "CHANNEL_MANAGER_NOT_INITIALIZED",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/summary"
}

409 Conflict - 冲突状态

{
  "detail": "无法停止运行中的通道,请先暂停",
  "error_code": "INVALID_STATE_TRANSITION",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/stop"
}
{
  "detail": "会话正在运行,无法回滚配置",
  "error_code": "SESSION_RUNNING",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/config/rollback"
}

403 Forbidden - 权限不足

{
  "detail": "没有权限访问此会话",
  "error_code": "ACCESS_DENIED",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels"
}

500 Internal Server Error - 服务器错误

{
  "detail": "通道引擎内部错误",
  "error_code": "INTERNAL_ERROR",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/start",
  "trace_id": "abc123def456"
}

503 Service Unavailable - 服务不可用

{
  "detail": "交易引擎暂时不可用",
  "error_code": "SERVICE_UNAVAILABLE",
  "timestamp": "2024-01-15T14:30:00Z",
  "path": "/api/v1/sessions/session_123/channels/aggressive/start",
  "retry_after": 30
}

错误码参考

错误码 HTTP状态 说明
SESSION_NOT_FOUND 404 会话不存在
CHANNEL_NOT_FOUND 404 通道不存在
CHANNEL_ALREADY_RUNNING 400 通道已运行
CHANNEL_NOT_RUNNING 400 通道未运行
INVALID_PARAMETER 400 参数无效
INVALID_STATE_TRANSITION 409 状态转换非法
CHANNEL_MANAGER_NOT_INITIALIZED 400 通道管理器未初始化
CONFIG_VERSION_NOT_FOUND 404 配置版本不存在
SESSION_RUNNING 409 会话运行中
ACCESS_DENIED 403 权限不足
INTERNAL_ERROR 500 内部错误
SERVICE_UNAVAILABLE 503 服务不可用

📚 相关文档