Skip to content

Conversation

@jamiesun
Copy link
Contributor

🐛 问题描述

用户在设置现有仓位的止盈止损时,遇到 HyperLiquid API 返回 422 反序列化错误

{
  "success": false,
  "error": "(422, None, 'Failed to deserialize the JSON body into the target type', ...)"
}

请求示例:

{
  "coin": "BTC",
  "position_size": 0.009,
  "stop_loss_price": 114000,
  "take_profit_price": 120000
}

🔍 根本原因

订单结构中存在矛盾配置

  • 设置了 isMarket: true (市价单)
  • 同时又提供了与触发价不同的 limit_px (使用激进价格计算)
  • HyperLiquid API 无法正确反序列化这种矛盾的订单结构

✅ 修复方案

1. 止盈订单 (Take Profit): 使用限价单

tp_order = {
    "limit_px": float(tp_px),  # 直接使用止盈价格
    "order_type": {
        "trigger": {
            "triggerPx": float(tp_px),
            "isMarket": False,  # ✅ 限价单
            "tpsl": "tp",
        }
    },
}
  • 确保在达到或超过目标价格时成交
  • 防止滑点造成的利润损失

2. 止损订单 (Stop Loss): 使用市价单

sl_order = {
    "limit_px": float(sl_px),  # 使用触发价格
    "order_type": {
        "trigger": {
            "triggerPx": float(sl_px),
            "isMarket": True,  # ✅ 市价单
            "tpsl": "sl",
        }
    },
}
  • 触发后立即以市价执行
  • 优先保证成交速度,防止损失扩大

3. 移除激进价格计算

  • 不再使用 _slippage_price() 计算激进价格
  • 直接使用用户指定的触发价格作为 limit_px

🧪 测试覆盖

新增单元测试 (8个)

  • test_take_profit_order_structure - 止盈订单结构验证
  • test_stop_loss_order_structure - 止损订单结构验证
  • test_combined_tpsl_order_structure - 同时设置止盈止损
  • test_short_position_tpsl_direction - 空头仓位方向测试
  • test_tpsl_without_position_fails - 无仓位时失败测试
  • test_tpsl_price_validation - 价格验证
  • test_auto_detect_position_size - 自动检测仓位大小
  • test_limit_px_equals_trigger_px - limit_px 等于 trigger_px 验证

更新集成测试 (2个)

  • test_bracket_order_uses_correct_grouping - Bracket订单分组验证
  • test_set_position_tpsl_uses_correct_grouping - 止盈止损分组验证

测试结果

======================== 34 passed in 0.33s ========================

所有测试全部通过 ✅

📝 变更文件

  • services/hyperliquid_services.py - 修复 set_position_tpsl() 方法
  • tests/unit/test_tpsl_orders.py - 新增单元测试
  • tests/integration/test_oco_grouping.py - 更新集成测试

🔄 影响范围

  • ✅ 仅影响 set_position_tpsl() 方法
  • ✅ 不影响其他订单类型功能
  • ✅ 向后兼容,API 调用方式不变
  • ✅ OCO 分组机制保持不变 (positionTpSl)

📋 Checklist

  • 代码修复已完成
  • 单元测试已添加
  • 集成测试已更新
  • 所有测试通过
  • 代码格式化通过 (ruff)
  • 提交信息符合规范

🎯 相关Issue

修复用户报告的止盈止损设置失败问题(422错误)

问题: 设置现有仓位的止盈止损时API返回422错误,原因是订单结构中isMarket=true与limit_px使用激进价格冲突

修复: 止盈使用限价单(isMarket:false),止损使用市价单(isMarket:true),limit_px直接使用触发价格

测试: 新增8个单元测试,更新2个集成测试,所有34个测试通过
@jamiesun jamiesun merged commit b8d3f06 into main Oct 28, 2025
7 checks passed
@jamiesun jamiesun mentioned this pull request Oct 28, 2025
@jamiesun jamiesun deleted the fix/tpsl-order-structure branch October 28, 2025 11:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants