api.md 13 KB

多平台 Delta 中性控制平面 API 文档

概述

本文档描述了多平台 Delta 中性控制平面的 API 端点和服务接口。该系统实现了跨交易所的 Delta 中性策略管理、风险监控和自动对冲功能。

核心服务架构

SystemOrchestrator

系统协调器,负责管理所有模块的生命周期和依赖关系。

DeltaNeutralController

Delta 中性控制器,提供核心的 Delta 控制和利用率再平衡功能。

RiskMonitoringService

风险监控服务,实时跟踪账户风险指标并生成警报。


API 端点详情

1. Delta 中性控制 API

POST /api/v1/delta/control

执行 Delta 中性控制操作,调整账户仓位以维持目标 Delta 值。

请求参数 (DeltaControlRequest):

{
  targetDelta: number        // 目标 Delta 值 (通常为 0.0)
  accounts: string[]         // 要控制的账户ID列表
  maxDeviation: number       // 最大允许偏差 (0.0-1.0)
  symbol: string            // 交易标的 (如 "BTC-USD")
  tolerancePercent?: number  // 容差百分比 (默认 0.05)
  dryRun?: boolean          // 是否为模拟运行 (默认 false)
}

响应格式 (DeltaControlResponse):

{
  success: boolean                    // 操作是否成功
  operationId: string                // 操作唯一标识符
  timestamp: number                  // 操作时间戳
  initialDelta: number               // 初始 Delta 值
  finalDelta: number                 // 最终 Delta 值
  deltaDeviation: number             // Delta 偏差值
  accountsProcessed: string[]        // 已处理的账户列表
  totalAdjustments: number           // 总调整次数
  executionTime: number              // 执行时间 (毫秒)
  adjustmentNeeded: boolean          // 是否需要调整
  hedgeResults?: HedgeExecutionResult // 对冲执行结果
  reason?: string                    // 操作原因或跳过原因
  error?: string                     // 错误信息 (如果失败)
}

示例请求:

curl -X POST http://localhost:3000/api/v1/delta/control \
  -H "Content-Type: application/json" \
  -d '{
    "targetDelta": 0.0,
    "accounts": ["pacifica-main", "aster-hedge"],
    "maxDeviation": 0.1,
    "symbol": "BTC-USD"
  }'

示例响应:

{
  "success": true,
  "operationId": "delta-ctrl-20241027-001",
  "timestamp": 1698393600000,
  "initialDelta": 0.25,
  "finalDelta": 0.02,
  "deltaDeviation": 0.02,
  "accountsProcessed": ["pacifica-main", "aster-hedge"],
  "totalAdjustments": 2,
  "executionTime": 1250,
  "adjustmentNeeded": true,
  "hedgeResults": {
    "success": true,
    "executedOrders": [
      {
        "accountId": "pacifica-main",
        "symbol": "BTC-USD",
        "amount": 0.23,
        "side": "sell"
      }
    ],
    "totalCost": 15234.50,
    "netDeltaChange": -0.23
  }
}

2. 利用率再平衡 API

POST /api/v1/utilization/rebalance

执行账户利用率再平衡,优化资源分配以达到目标利用率。

请求参数 (UtilizationRebalanceRequest):

{
  targetUtilization: number     // 目标利用率 (0.0-1.0)
  accounts: string[]           // 要再平衡的账户列表
  symbol: string              // 交易标的
  tolerancePercent?: number    // 容差百分比 (默认 0.1)
  maxRebalanceAmount?: number  // 最大再平衡金额
  dryRun?: boolean            // 是否为模拟运行
}

响应格式 (UtilizationRebalanceResponse):

{
  success: boolean                          // 操作是否成功
  operationId: string                      // 操作唯一标识符
  timestamp: number                        // 操作时间戳
  accountsProcessed: string[]              // 已处理的账户列表
  averageUtilization: number               // 平均利用率
  targetUtilization: number                // 目标利用率
  executionTime: number                    // 执行时间 (毫秒)
  rebalanceNeeded: boolean                 // 是否需要再平衡
  rebalanceActions: UtilizationAction[]    // 再平衡操作列表
  utilizationMetrics: UtilizationMetric[]  // 利用率指标
  reason?: string                          // 操作原因
  error?: string                           // 错误信息
}

interface UtilizationAction {
  accountId: string      // 账户ID
  action: 'increase' | 'decrease' | 'maintain'  // 操作类型
  currentUtilization: number  // 当前利用率
  targetUtilization: number   // 目标利用率
  adjustmentAmount: number    // 调整金额
}

interface UtilizationMetric {
  accountId: string          // 账户ID
  currentUtilization: number // 当前利用率
  targetUtilization: number  // 目标利用率
  deviationPercent: number   // 偏差百分比
  withinTolerance: boolean   // 是否在容差范围内
}

示例请求:

curl -X POST http://localhost:3000/api/v1/utilization/rebalance \
  -H "Content-Type: application/json" \
  -d '{
    "targetUtilization": 0.75,
    "accounts": ["pacifica-main", "aster-hedge", "binance-backup"],
    "symbol": "BTC-USD",
    "tolerancePercent": 0.1
  }'

3. 风险监控 API

GET /api/v1/risk/metrics/{accountId}

获取指定账户的风险指标。

路径参数:

  • accountId: 账户ID

响应格式 (RiskMetrics):

{
  accountId: string        // 账户ID
  deltaDeviation: number   // Delta 偏差
  utilizationRate: number  // 利用率
  leverageRatio: number    // 杠杆比率
  unrealizedPnl: number    // 未实现盈亏
  maxDrawdown: number      // 最大回撤
  timestamp: number        // 时间戳
}

GET /api/v1/risk/alerts

获取所有活跃的风险警报。

查询参数:

  • accountId?: 可选,筛选特定账户的警报
  • severity?: 可选,筛选特定严重程度的警报 (INFO|WARN|CRITICAL)

响应格式 (RiskAlert[]):

[
  {
    id: string                    // 警报ID
    type: 'delta-alert' | 'utilization-alert' | 'failover-alert' | 'proxy-alert'
    severity: 'INFO' | 'WARN' | 'CRITICAL'  // 严重程度
    accountId: string            // 相关账户ID
    message: string              // 警报消息
    timestamp: number            // 时间戳
    data: Record<string, any>    // 警报数据
  }
]

GET /api/v1/risk/history/{accountId}

获取指定账户的风险指标历史记录。

查询参数:

  • limit?: 返回记录数量限制 (默认 100)
  • since?: 起始时间戳

4. 账户同步 API

POST /api/v1/account/sync

同步账户状态和余额信息。

请求参数 (AccountSyncRequest):

{
  accounts: string[]           // 要同步的账户列表
  includePositions: boolean    // 是否包含仓位信息
  includeBalances: boolean     // 是否包含余额信息
  timeout?: number            // 超时时间 (毫秒)
}

响应格式 (AccountSyncResponse):

{
  success: boolean                    // 同步是否成功
  syncedAccounts: string[]           // 已同步的账户列表
  failedAccounts: string[]           // 同步失败的账户列表
  syncTime: number                   // 同步耗时
  accountStates: AccountState[]      // 账户状态列表
  errors?: string[]                  // 错误信息列表
}

interface AccountState {
  accountId: string        // 账户ID
  exchange: string         // 交易所
  totalBalance: number     // 总余额
  availableBalance: number // 可用余额
  netPosition: number      // 净仓位
  unrealizedPnl: number    // 未实现盈亏
  entryPrice?: number      // 入场价格
  currentPrice?: number    // 当前价格
  leverage?: number        // 杠杆倍数
  lastUpdated: number      // 最后更新时间
}

5. 对冲执行 API

POST /api/v1/hedge/execute

执行对冲交易操作。

请求参数 (HedgeExecutionRequest):

{
  symbol: string              // 交易标的
  targetAccounts: string[]    // 目标账户列表
  hedgeAmount: number         // 对冲金额
  hedgeStrategy: 'delta-neutral' | 'cross-platform' | 'same-platform'
  maxSlippage?: number        // 最大滑点 (默认 0.005)
  timeout?: number           // 超时时间 (默认 30000ms)
  dryRun?: boolean           // 是否模拟执行
}

响应格式 (HedgeExecutionResult):

{
  success: boolean                // 执行是否成功
  executedOrders: OrderExecution[] // 已执行的订单
  totalCost: number              // 总成本
  executionTime: number          // 执行时间 (毫秒)
  netDeltaChange: number         // 净 Delta 变化
  slippage: number              // 实际滑点
  error?: string                // 错误信息
}

interface OrderExecution {
  orderId: string      // 订单ID
  accountId: string    // 账户ID
  symbol: string       // 交易标的
  amount: number       // 交易数量
  side: 'buy' | 'sell' // 买卖方向
  executedPrice: number // 执行价格
  fees: number         // 手续费
  timestamp: number    // 执行时间
}

6. 市场数据故障转移 API

GET /api/v1/market/feeds

获取市场数据源状态。

响应格式:

{
  feeds: MarketDataFeedStatus[]  // 数据源状态列表
  activeFeed: string            // 当前活跃数据源
  lastFailover: number          // 最后故障转移时间
}

interface MarketDataFeedStatus {
  feedId: string                               // 数据源ID
  status: 'healthy' | 'degraded' | 'failing'  // 状态
  latency: number                             // 延迟 (毫秒)
  lastUpdate: number                          // 最后更新时间
  errorCount: number                          // 错误计数
}

POST /api/v1/market/failover

手动触发市场数据源故障转移。

请求参数:

{
  targetFeed: string     // 目标数据源
  reason?: string        // 故障转移原因
}

7. 系统状态 API

GET /api/v1/system/status

获取系统整体状态。

响应格式:

{
  status: 'running' | 'stopped' | 'error'  // 系统状态
  uptime: number                          // 运行时间 (毫秒)
  services: ServiceStatus[]               // 服务状态列表
  performance: PerformanceMetrics         // 性能指标
  activeAccounts: number                  // 活跃账户数
  totalOperations: number                 // 总操作数
}

interface ServiceStatus {
  name: string                           // 服务名称
  status: 'running' | 'stopped' | 'error'  // 服务状态
  lastHeartbeat: number                  // 最后心跳时间
  errorCount: number                     // 错误计数
}

interface PerformanceMetrics {
  avgResponseTime: number     // 平均响应时间
  operationsPerSecond: number // 每秒操作数
  memoryUsage: number        // 内存使用量 (MB)
  cpuUsage: number           // CPU 使用率
}

POST /api/v1/system/restart

重启系统服务。

POST /api/v1/system/stop

停止系统服务。


错误码说明

错误码 说明 解决方案
1001 无效的账户ID 检查账户ID格式和存在性
1002 Delta偏差超出限制 调整maxDeviation参数
1003 对冲执行失败 检查账户余额和市场条件
1004 风险警报阻止操作 处理相关风险警报后重试
1005 市场数据不可用 等待数据源恢复或手动故障转移
2001 服务超时 增加timeout参数或检查网络连接
2002 代理连接失败 检查代理配置和网络状态
3001 权限不足 检查API密钥和账户权限
3002 请求频率过高 适当降低请求频率

配置参数

性能配置

  • 控制循环延迟: 目标 8 秒以内
  • 故障转移SLA: 10 秒以内
  • 资源利用率: 50-80% 目标范围

风险控制配置

  • 最大Delta偏差: 默认 10%
  • 利用率容差: 默认 10%
  • 最大回撤: 账户特定配置

网络配置

  • 代理轮换: 支持多代理负载均衡
  • 超时设置: 可配置的请求超时
  • 重试机制: 指数退避重试策略

使用示例

完整的Delta中性策略工作流

# 1. 检查系统状态
curl http://localhost:3000/api/v1/system/status

# 2. 同步账户状态
curl -X POST http://localhost:3000/api/v1/account/sync \
  -H "Content-Type: application/json" \
  -d '{"accounts": ["pacifica-main", "aster-hedge"], "includePositions": true}'

# 3. 检查风险指标
curl http://localhost:3000/api/v1/risk/metrics/pacifica-main

# 4. 执行Delta控制
curl -X POST http://localhost:3000/api/v1/delta/control \
  -H "Content-Type: application/json" \
  -d '{
    "targetDelta": 0.0,
    "accounts": ["pacifica-main", "aster-hedge"],
    "maxDeviation": 0.1,
    "symbol": "BTC-USD"
  }'

# 5. 检查执行结果和新的风险状态
curl http://localhost:3000/api/v1/risk/alerts

监控和报警集成

# 持续监控风险警报
while true; do
  curl -s http://localhost:3000/api/v1/risk/alerts?severity=CRITICAL
  sleep 30
done

# 定期利用率再平衡
curl -X POST http://localhost:3000/api/v1/utilization/rebalance \
  -H "Content-Type: application/json" \
  -d '{
    "targetUtilization": 0.75,
    "accounts": ["pacifica-main", "aster-hedge"],
    "symbol": "BTC-USD"
  }'

版本信息

  • API版本: v1.0
  • 实现版本: 1.0.0
  • 最后更新: 2024-10-27
  • 兼容性: 向后兼容支持

技术支持

如需技术支持或报告问题,请参考:

  • 系统日志: /logs/system.log
  • 错误日志: /logs/error.log
  • 性能监控: /api/v1/system/status