Merge branch 'dev' into dev

This commit is contained in:
Icyoung
2025-11-05 16:21:57 +08:00
committed by GitHub
92 changed files with 13861 additions and 4058 deletions

View File

@@ -438,13 +438,23 @@ func (t *AsterTrader) GetBalance() (map[string]interface{}, error) {
return nil, err
}
// 🔍 调试打印原始API响应
log.Printf("🔍 Aster API原始响应: %s", string(body))
// 查找USDT余额
totalBalance := 0.0
availableBalance := 0.0
crossUnPnl := 0.0
for _, bal := range balances {
// 🔍 调试:打印每条余额记录
log.Printf("🔍 余额记录: %+v", bal)
if asset, ok := bal["asset"].(string); ok && asset == "USDT" {
// 🔍 调试打印USDT余额详情
log.Printf("🔍 USDT余额详情: balance=%v, availableBalance=%v, crossUnPnl=%v",
bal["balance"], bal["availableBalance"], bal["crossUnPnl"])
if wb, ok := bal["balance"].(string); ok {
totalBalance, _ = strconv.ParseFloat(wb, 64)
}
@@ -458,11 +468,25 @@ func (t *AsterTrader) GetBalance() (map[string]interface{}, error) {
}
}
// ✅ Aster API完全兼容Binance API格式
// balance字段 = wallet balance不包含未实现盈亏
// crossUnPnl = unrealized profit未实现盈亏
// crossWalletBalance = balance + crossUnPnl全仓钱包余额包含盈亏
//
// 参考Binance官方文档
// - Account Information V2: marginBalance = walletBalance + unrealizedProfit
// - Balance V3: crossWalletBalance = balance + crossUnPnl
log.Printf("✓ Aster API返回: 钱包余额=%.2f, 未实现盈亏=%.2f, 可用余额=%.2f",
totalBalance,
crossUnPnl,
availableBalance)
// 返回与Binance相同的字段名确保AutoTrader能正确解析
return map[string]interface{}{
"totalWalletBalance": totalBalance,
"totalWalletBalance": totalBalance, // 钱包余额(不含未实现盈亏)
"availableBalance": availableBalance,
"totalUnrealizedProfit": crossUnPnl,
"totalUnrealizedProfit": crossUnPnl, // 未实现盈亏
}, nil
}
@@ -971,6 +995,161 @@ func (t *AsterTrader) SetTakeProfit(symbol string, positionSide string, quantity
return err
}
// CancelStopOrders 取消该币种的止盈/止损单(用于调整止盈止损位置)
func (t *AsterTrader) CancelStopOrders(symbol string) error {
// 获取该币种的所有未完成订单
params := map[string]interface{}{
"symbol": symbol,
}
body, err := t.request("GET", "/fapi/v3/openOrders", params)
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
var orders []map[string]interface{}
if err := json.Unmarshal(body, &orders); err != nil {
return fmt.Errorf("解析订单数据失败: %w", err)
}
// 过滤出止盈止损单并取消
canceledCount := 0
for _, order := range orders {
orderType, _ := order["type"].(string)
// 只取消止损和止盈订单
if orderType == "STOP_MARKET" ||
orderType == "TAKE_PROFIT_MARKET" ||
orderType == "STOP" ||
orderType == "TAKE_PROFIT" {
orderID, _ := order["orderId"].(float64)
cancelParams := map[string]interface{}{
"symbol": symbol,
"orderId": int64(orderID),
}
_, err := t.request("DELETE", "/fapi/v3/order", cancelParams)
if err != nil {
log.Printf(" ⚠ 取消订单 %d 失败: %v", int64(orderID), err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消 %s 的止盈/止损单 (订单ID: %d, 类型: %s)",
symbol, int64(orderID), orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈/止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈/止损单", symbol, canceledCount)
}
return nil
}
// CancelStopLossOrders 仅取消止损单(不影响止盈单)
func (t *AsterTrader) CancelStopLossOrders(symbol string) error {
// 获取该币种的所有未完成订单
params := map[string]interface{}{
"symbol": symbol,
}
body, err := t.request("GET", "/fapi/v3/openOrders", params)
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
var orders []map[string]interface{}
if err := json.Unmarshal(body, &orders); err != nil {
return fmt.Errorf("解析订单数据失败: %w", err)
}
// 过滤出止损单并取消
canceledCount := 0
for _, order := range orders {
orderType, _ := order["type"].(string)
// 只取消止损订单(不取消止盈订单)
if orderType == "STOP_MARKET" || orderType == "STOP" {
orderID, _ := order["orderId"].(float64)
cancelParams := map[string]interface{}{
"symbol": symbol,
"orderId": int64(orderID),
}
_, err := t.request("DELETE", "/fapi/v1/order", cancelParams)
if err != nil {
log.Printf(" ⚠ 取消止损单 %d 失败: %v", int64(orderID), err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消止损单 (订单ID: %d, 类型: %s)", int64(orderID), orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止损单", symbol, canceledCount)
}
return nil
}
// CancelTakeProfitOrders 仅取消止盈单(不影响止损单)
func (t *AsterTrader) CancelTakeProfitOrders(symbol string) error {
// 获取该币种的所有未完成订单
params := map[string]interface{}{
"symbol": symbol,
}
body, err := t.request("GET", "/fapi/v3/openOrders", params)
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
var orders []map[string]interface{}
if err := json.Unmarshal(body, &orders); err != nil {
return fmt.Errorf("解析订单数据失败: %w", err)
}
// 过滤出止盈单并取消
canceledCount := 0
for _, order := range orders {
orderType, _ := order["type"].(string)
// 只取消止盈订单(不取消止损订单)
if orderType == "TAKE_PROFIT_MARKET" || orderType == "TAKE_PROFIT" {
orderID, _ := order["orderId"].(float64)
cancelParams := map[string]interface{}{
"symbol": symbol,
"orderId": int64(orderID),
}
_, err := t.request("DELETE", "/fapi/v1/order", cancelParams)
if err != nil {
log.Printf(" ⚠ 取消止盈单 %d 失败: %v", int64(orderID), err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消止盈单 (订单ID: %d, 类型: %s)", int64(orderID), orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈单", symbol, canceledCount)
}
return nil
}
// CancelAllOrders 取消所有订单
func (t *AsterTrader) CancelAllOrders(symbol string) error {
params := map[string]interface{}{
@@ -981,6 +1160,61 @@ func (t *AsterTrader) CancelAllOrders(symbol string) error {
return err
}
// CancelStopOrders 取消该币种的止盈/止损单(用于调整止盈止损位置)
func (t *AsterTrader) CancelStopOrders(symbol string) error {
// 获取该币种的所有未完成订单
params := map[string]interface{}{
"symbol": symbol,
}
body, err := t.request("GET", "/fapi/v3/openOrders", params)
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
var orders []map[string]interface{}
if err := json.Unmarshal(body, &orders); err != nil {
return fmt.Errorf("解析订单数据失败: %w", err)
}
// 过滤出止盈止损单并取消
canceledCount := 0
for _, order := range orders {
orderType, _ := order["type"].(string)
// 只取消止损和止盈订单
if orderType == "STOP_MARKET" ||
orderType == "TAKE_PROFIT_MARKET" ||
orderType == "STOP" ||
orderType == "TAKE_PROFIT" {
orderID, _ := order["orderId"].(float64)
cancelParams := map[string]interface{}{
"symbol": symbol,
"orderId": int64(orderID),
}
_, err := t.request("DELETE", "/fapi/v3/order", cancelParams)
if err != nil {
log.Printf(" ⚠ 取消订单 %d 失败: %v", int64(orderID), err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消 %s 的止盈/止损单 (订单ID: %d, 类型: %s)",
symbol, int64(orderID), orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈/止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈/止损单", symbol, canceledCount)
}
return nil
}
// FormatQuantity 格式化数量实现Trader接口
func (t *AsterTrader) FormatQuantity(symbol string, quantity float64) (string, error) {
formatted, err := t.formatQuantity(symbol, quantity)

View File

@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"log"
"math"
"nofx/decision"
"nofx/logger"
"nofx/market"
@@ -101,13 +102,15 @@ type AutoTrader struct {
positionFirstSeenTime map[string]int64 // 持仓首次出现时间 (symbol_side -> timestamp毫秒)
stopMonitorCh chan struct{} // 用于停止监控goroutine
monitorWg sync.WaitGroup // 用于等待监控goroutine结束
// 最高收益缓存 (symbol -> 峰值盈亏百分比)
peakPnLCache map[string]float64
peakPnLCache map[string]float64 // 最高收益缓存 (symbol -> 峰值盈亏百分比)
peakPnLCacheMutex sync.RWMutex // 缓存读写锁
lastBalanceSyncTime time.Time // 上次余额同步时间
database interface{} // 数据库引用(用于自动更新余额)
userID string // 用户ID
}
// NewAutoTrader 创建自动交易器
func NewAutoTrader(config AutoTraderConfig) (*AutoTrader, error) {
func NewAutoTrader(config AutoTraderConfig, database interface{}, userID string) (*AutoTrader, error) {
// 设置默认值
if config.ID == "" {
config.ID = "default_trader"
@@ -201,7 +204,8 @@ func NewAutoTrader(config AutoTraderConfig) (*AutoTrader, error) {
// 设置默认系统提示词模板
systemPromptTemplate := config.SystemPromptTemplate
if systemPromptTemplate == "" {
systemPromptTemplate = "default" // 默认使用 default 模板
// feature/partial-close-dynamic-tpsl 分支默认使用 adaptive支持动态止盈止损
systemPromptTemplate = "adaptive"
}
return &AutoTrader{
@@ -226,6 +230,9 @@ func NewAutoTrader(config AutoTraderConfig) (*AutoTrader, error) {
monitorWg: sync.WaitGroup{},
peakPnLCache: make(map[string]float64),
peakPnLCacheMutex: sync.RWMutex{},
lastBalanceSyncTime: time.Now(), // 初始化为当前时间
database: database,
userID: userID,
}, nil
}
@@ -268,6 +275,101 @@ func (at *AutoTrader) Stop() {
log.Println("⏹ 自动交易系统停止")
}
// autoSyncBalanceIfNeeded 自动同步余额每10分钟检查一次变化>5%才更新)
func (at *AutoTrader) autoSyncBalanceIfNeeded() {
// 距离上次同步不足10分钟跳过
if time.Since(at.lastBalanceSyncTime) < 10*time.Minute {
return
}
log.Printf("🔄 [%s] 开始自动检查余额变化...", at.name)
// 查询实际余额
balanceInfo, err := at.trader.GetBalance()
if err != nil {
log.Printf("⚠️ [%s] 查询余额失败: %v", at.name, err)
at.lastBalanceSyncTime = time.Now() // 即使失败也更新时间,避免频繁重试
return
}
// 提取可用余额
var actualBalance float64
if availableBalance, ok := balanceInfo["available_balance"].(float64); ok && availableBalance > 0 {
actualBalance = availableBalance
} else if availableBalance, ok := balanceInfo["availableBalance"].(float64); ok && availableBalance > 0 {
actualBalance = availableBalance
} else if totalBalance, ok := balanceInfo["balance"].(float64); ok && totalBalance > 0 {
actualBalance = totalBalance
} else {
log.Printf("⚠️ [%s] 无法提取可用余额", at.name)
at.lastBalanceSyncTime = time.Now()
return
}
oldBalance := at.initialBalance
// 防止除以零:如果初始余额无效,直接更新为实际余额
if oldBalance <= 0 {
log.Printf("⚠️ [%s] 初始余额无效 (%.2f),直接更新为实际余额 %.2f USDT", at.name, oldBalance, actualBalance)
at.initialBalance = actualBalance
if at.database != nil {
type DatabaseUpdater interface {
UpdateTraderInitialBalance(userID, id string, newBalance float64) error
}
if db, ok := at.database.(DatabaseUpdater); ok {
if err := db.UpdateTraderInitialBalance(at.userID, at.id, actualBalance); err != nil {
log.Printf("❌ [%s] 更新数据库失败: %v", at.name, err)
} else {
log.Printf("✅ [%s] 已自动同步余额到数据库", at.name)
}
} else {
log.Printf("⚠️ [%s] 数据库类型不支持UpdateTraderInitialBalance接口", at.name)
}
} else {
log.Printf("⚠️ [%s] 数据库引用为空,余额仅在内存中更新", at.name)
}
at.lastBalanceSyncTime = time.Now()
return
}
changePercent := ((actualBalance - oldBalance) / oldBalance) * 100
// 变化超过5%才更新
if math.Abs(changePercent) > 5.0 {
log.Printf("🔔 [%s] 检测到余额大幅变化: %.2f → %.2f USDT (%.2f%%)",
at.name, oldBalance, actualBalance, changePercent)
// 更新内存中的 initialBalance
at.initialBalance = actualBalance
// 更新数据库(需要类型断言)
if at.database != nil {
// 这里需要根据实际的数据库类型进行类型断言
// 由于使用了 interface{},我们需要在 TraderManager 层面处理更新
// 或者在这里进行类型检查
type DatabaseUpdater interface {
UpdateTraderInitialBalance(userID, id string, newBalance float64) error
}
if db, ok := at.database.(DatabaseUpdater); ok {
err := db.UpdateTraderInitialBalance(at.userID, at.id, actualBalance)
if err != nil {
log.Printf("❌ [%s] 更新数据库失败: %v", at.name, err)
} else {
log.Printf("✅ [%s] 已自动同步余额到数据库", at.name)
}
} else {
log.Printf("⚠️ [%s] 数据库类型不支持UpdateTraderInitialBalance接口", at.name)
}
} else {
log.Printf("⚠️ [%s] 数据库引用为空,余额仅在内存中更新", at.name)
}
} else {
log.Printf("✓ [%s] 余额变化不大 (%.2f%%),无需更新", at.name, changePercent)
}
at.lastBalanceSyncTime = time.Now()
}
// runCycle 运行一个交易周期使用AI全权决策
func (at *AutoTrader) runCycle() error {
at.callCount++
@@ -299,7 +401,10 @@ func (at *AutoTrader) runCycle() error {
log.Println("📅 日盈亏已重置")
}
// 3. 收集交易上下文
// 3. 自动同步余额每10分钟检查一次充值/提现后自动更新)
at.autoSyncBalanceIfNeeded()
// 4. 收集交易上下文
ctx, err := at.buildTradingContext()
if err != nil {
record.Success = false
@@ -339,7 +444,7 @@ func (at *AutoTrader) runCycle() error {
log.Printf("📊 账户净值: %.2f USDT | 可用: %.2f USDT | 持仓: %d",
ctx.Account.TotalEquity, ctx.Account.AvailableBalance, ctx.Account.PositionCount)
// 4. 调用AI获取完整决策
// 5. 调用AI获取完整决策
log.Printf("🤖 正在请求AI分析并决策... [模板: %s]", at.systemPromptTemplate)
decision, err := decision.GetFullDecisionWithCustomPrompt(ctx, at.mcpClient, at.customPrompt, at.overrideBasePrompt, at.systemPromptTemplate)
@@ -496,6 +601,12 @@ func (at *AutoTrader) buildTradingContext() (*decision.Context, error) {
if quantity < 0 {
quantity = -quantity // 空仓数量为负,转为正数
}
// 跳过已平仓的持仓quantity = 0防止"幽灵持仓"传递给AI
if quantity == 0 {
continue
}
unrealizedPnl := pos["unRealizedProfit"].(float64)
liquidationPrice := pos["liquidationPrice"].(float64)
@@ -608,6 +719,12 @@ func (at *AutoTrader) executeDecisionWithRecord(decision *decision.Decision, act
return at.executeCloseLongWithRecord(decision, actionRecord)
case "close_short":
return at.executeCloseShortWithRecord(decision, actionRecord)
case "update_stop_loss":
return at.executeUpdateStopLossWithRecord(decision, actionRecord)
case "update_take_profit":
return at.executeUpdateTakeProfitWithRecord(decision, actionRecord)
case "partial_close":
return at.executePartialCloseWithRecord(decision, actionRecord)
case "hold", "wait":
// 无需执行,仅记录
return nil
@@ -641,6 +758,27 @@ func (at *AutoTrader) executeOpenLongWithRecord(decision *decision.Decision, act
actionRecord.Quantity = quantity
actionRecord.Price = marketData.CurrentPrice
// ⚠️ 保证金验证防止保证金不足错误code=-2019
requiredMargin := decision.PositionSizeUSD / float64(decision.Leverage)
balance, err := at.trader.GetBalance()
if err != nil {
return fmt.Errorf("获取账户余额失败: %w", err)
}
availableBalance := 0.0
if avail, ok := balance["availableBalance"].(float64); ok {
availableBalance = avail
}
// 手续费估算Taker费率 0.04%
estimatedFee := decision.PositionSizeUSD * 0.0004
totalRequired := requiredMargin + estimatedFee
if totalRequired > availableBalance {
return fmt.Errorf("❌ 保证金不足: 需要 %.2f USDT保证金 %.2f + 手续费 %.2f),可用 %.2f USDT",
totalRequired, requiredMargin, estimatedFee, availableBalance)
}
// 设置仓位模式
if err := at.trader.SetMarginMode(decision.Symbol, at.config.IsCrossMargin); err != nil {
log.Printf(" ⚠️ 设置仓位模式失败: %v", err)
@@ -700,6 +838,27 @@ func (at *AutoTrader) executeOpenShortWithRecord(decision *decision.Decision, ac
actionRecord.Quantity = quantity
actionRecord.Price = marketData.CurrentPrice
// ⚠️ 保证金验证防止保证金不足错误code=-2019
requiredMargin := decision.PositionSizeUSD / float64(decision.Leverage)
balance, err := at.trader.GetBalance()
if err != nil {
return fmt.Errorf("获取账户余额失败: %w", err)
}
availableBalance := 0.0
if avail, ok := balance["availableBalance"].(float64); ok {
availableBalance = avail
}
// 手续费估算Taker费率 0.04%
estimatedFee := decision.PositionSizeUSD * 0.0004
totalRequired := requiredMargin + estimatedFee
if totalRequired > availableBalance {
return fmt.Errorf("❌ 保证金不足: 需要 %.2f USDT保证金 %.2f + 手续费 %.2f),可用 %.2f USDT",
totalRequired, requiredMargin, estimatedFee, availableBalance)
}
// 设置仓位模式
if err := at.trader.SetMarginMode(decision.Symbol, at.config.IsCrossMargin); err != nil {
log.Printf(" ⚠️ 设置仓位模式失败: %v", err)
@@ -786,6 +945,201 @@ func (at *AutoTrader) executeCloseShortWithRecord(decision *decision.Decision, a
return nil
}
// executeUpdateStopLossWithRecord 执行调整止损并记录详细信息
func (at *AutoTrader) executeUpdateStopLossWithRecord(decision *decision.Decision, actionRecord *logger.DecisionAction) error {
log.Printf(" 🎯 调整止损: %s → %.2f", decision.Symbol, decision.NewStopLoss)
// 获取当前价格
marketData, err := market.Get(decision.Symbol)
if err != nil {
return err
}
actionRecord.Price = marketData.CurrentPrice
// 获取当前持仓
positions, err := at.trader.GetPositions()
if err != nil {
return fmt.Errorf("获取持仓失败: %w", err)
}
// 查找目标持仓
var targetPosition map[string]interface{}
for _, pos := range positions {
symbol, _ := pos["symbol"].(string)
posAmt, _ := pos["positionAmt"].(float64)
if symbol == decision.Symbol && posAmt != 0 {
targetPosition = pos
break
}
}
if targetPosition == nil {
return fmt.Errorf("持仓不存在: %s", decision.Symbol)
}
// 获取持仓方向和数量
side, _ := targetPosition["side"].(string)
positionSide := strings.ToUpper(side)
positionAmt, _ := targetPosition["positionAmt"].(float64)
// 验证新止损价格合理性
if positionSide == "LONG" && decision.NewStopLoss >= marketData.CurrentPrice {
return fmt.Errorf("多单止损必须低于当前价格 (当前: %.2f, 新止损: %.2f)", marketData.CurrentPrice, decision.NewStopLoss)
}
if positionSide == "SHORT" && decision.NewStopLoss <= marketData.CurrentPrice {
return fmt.Errorf("空单止损必须高于当前价格 (当前: %.2f, 新止损: %.2f)", marketData.CurrentPrice, decision.NewStopLoss)
}
// 取消旧的止损单(避免多个止损单共存)
if err := at.trader.CancelStopOrders(decision.Symbol); err != nil {
log.Printf(" ⚠ 取消旧止损单失败: %v", err)
// 不中断执行,继续设置新止损
}
// 调用交易所 API 修改止损
quantity := math.Abs(positionAmt)
err = at.trader.SetStopLoss(decision.Symbol, positionSide, quantity, decision.NewStopLoss)
if err != nil {
return fmt.Errorf("修改止损失败: %w", err)
}
log.Printf(" ✓ 止损已调整: %.2f (当前价格: %.2f)", decision.NewStopLoss, marketData.CurrentPrice)
return nil
}
// executeUpdateTakeProfitWithRecord 执行调整止盈并记录详细信息
func (at *AutoTrader) executeUpdateTakeProfitWithRecord(decision *decision.Decision, actionRecord *logger.DecisionAction) error {
log.Printf(" 🎯 调整止盈: %s → %.2f", decision.Symbol, decision.NewTakeProfit)
// 获取当前价格
marketData, err := market.Get(decision.Symbol)
if err != nil {
return err
}
actionRecord.Price = marketData.CurrentPrice
// 获取当前持仓
positions, err := at.trader.GetPositions()
if err != nil {
return fmt.Errorf("获取持仓失败: %w", err)
}
// 查找目标持仓
var targetPosition map[string]interface{}
for _, pos := range positions {
symbol, _ := pos["symbol"].(string)
posAmt, _ := pos["positionAmt"].(float64)
if symbol == decision.Symbol && posAmt != 0 {
targetPosition = pos
break
}
}
if targetPosition == nil {
return fmt.Errorf("持仓不存在: %s", decision.Symbol)
}
// 获取持仓方向和数量
side, _ := targetPosition["side"].(string)
positionSide := strings.ToUpper(side)
positionAmt, _ := targetPosition["positionAmt"].(float64)
// 验证新止盈价格合理性
if positionSide == "LONG" && decision.NewTakeProfit <= marketData.CurrentPrice {
return fmt.Errorf("多单止盈必须高于当前价格 (当前: %.2f, 新止盈: %.2f)", marketData.CurrentPrice, decision.NewTakeProfit)
}
if positionSide == "SHORT" && decision.NewTakeProfit >= marketData.CurrentPrice {
return fmt.Errorf("空单止盈必须低于当前价格 (当前: %.2f, 新止盈: %.2f)", marketData.CurrentPrice, decision.NewTakeProfit)
}
// 取消旧的止盈单(避免多个止盈单共存)
if err := at.trader.CancelStopOrders(decision.Symbol); err != nil {
log.Printf(" ⚠ 取消旧止盈单失败: %v", err)
// 不中断执行,继续设置新止盈
}
// 调用交易所 API 修改止盈
quantity := math.Abs(positionAmt)
err = at.trader.SetTakeProfit(decision.Symbol, positionSide, quantity, decision.NewTakeProfit)
if err != nil {
return fmt.Errorf("修改止盈失败: %w", err)
}
log.Printf(" ✓ 止盈已调整: %.2f (当前价格: %.2f)", decision.NewTakeProfit, marketData.CurrentPrice)
return nil
}
// executePartialCloseWithRecord 执行部分平仓并记录详细信息
func (at *AutoTrader) executePartialCloseWithRecord(decision *decision.Decision, actionRecord *logger.DecisionAction) error {
log.Printf(" 📊 部分平仓: %s %.1f%%", decision.Symbol, decision.ClosePercentage)
// 验证百分比范围
if decision.ClosePercentage <= 0 || decision.ClosePercentage > 100 {
return fmt.Errorf("平仓百分比必须在 0-100 之间,当前: %.1f", decision.ClosePercentage)
}
// 获取当前价格
marketData, err := market.Get(decision.Symbol)
if err != nil {
return err
}
actionRecord.Price = marketData.CurrentPrice
// 获取当前持仓
positions, err := at.trader.GetPositions()
if err != nil {
return fmt.Errorf("获取持仓失败: %w", err)
}
// 查找目标持仓
var targetPosition map[string]interface{}
for _, pos := range positions {
symbol, _ := pos["symbol"].(string)
posAmt, _ := pos["positionAmt"].(float64)
if symbol == decision.Symbol && posAmt != 0 {
targetPosition = pos
break
}
}
if targetPosition == nil {
return fmt.Errorf("持仓不存在: %s", decision.Symbol)
}
// 获取持仓方向和数量
side, _ := targetPosition["side"].(string)
positionSide := strings.ToUpper(side)
positionAmt, _ := targetPosition["positionAmt"].(float64)
// 计算平仓数量
totalQuantity := math.Abs(positionAmt)
closeQuantity := totalQuantity * (decision.ClosePercentage / 100.0)
actionRecord.Quantity = closeQuantity
// 执行平仓
var order map[string]interface{}
if positionSide == "LONG" {
order, err = at.trader.CloseLong(decision.Symbol, closeQuantity)
} else {
order, err = at.trader.CloseShort(decision.Symbol, closeQuantity)
}
if err != nil {
return fmt.Errorf("部分平仓失败: %w", err)
}
// 记录订单ID
if orderID, ok := order["orderId"].(int64); ok {
actionRecord.OrderID = orderID
}
remainingQuantity := totalQuantity - closeQuantity
log.Printf(" ✓ 部分平仓成功: 平仓 %.4f (%.1f%%), 剩余 %.4f",
closeQuantity, decision.ClosePercentage, remainingQuantity)
return nil
}
// GetID 获取trader ID
func (at *AutoTrader) GetID() string {
return at.id
@@ -999,12 +1353,14 @@ func sortDecisionsByPriority(decisions []decision.Decision) []decision.Decision
// 定义优先级
getActionPriority := func(action string) int {
switch action {
case "close_long", "close_short":
return 1 // 最高优先级:先平仓
case "close_long", "close_short", "partial_close":
return 1 // 最高优先级:先平仓(包括部分平仓)
case "update_stop_loss", "update_take_profit":
return 2 // 调整持仓止盈止损
case "open_long", "open_short":
return 2 // 次优先级:后开仓
return 3 // 次优先级:后开仓
case "hold", "wait":
return 3 // 最低优先级:观望
return 4 // 最低优先级:观望
default:
return 999 // 未知动作放最后
}

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"strconv"
"strings"
"sync"
"time"
@@ -32,10 +33,40 @@ type FuturesTrader struct {
// NewFuturesTrader 创建合约交易器
func NewFuturesTrader(apiKey, secretKey string) *FuturesTrader {
client := futures.NewClient(apiKey, secretKey)
return &FuturesTrader{
trader := &FuturesTrader{
client: client,
cacheDuration: 15 * time.Second, // 15秒缓存
}
// 设置双向持仓模式Hedge Mode
// 这是必需的,因为代码中使用了 PositionSide (LONG/SHORT)
if err := trader.setDualSidePosition(); err != nil {
log.Printf("⚠️ 设置双向持仓模式失败: %v (如果已是双向模式则忽略此警告)", err)
}
return trader
}
// setDualSidePosition 设置双向持仓模式(初始化时调用)
func (t *FuturesTrader) setDualSidePosition() error {
// 尝试设置双向持仓模式
err := t.client.NewChangePositionModeService().
DualSide(true). // true = 双向持仓Hedge Mode
Do(context.Background())
if err != nil {
// 如果错误信息包含"No need to change",说明已经是双向持仓模式
if strings.Contains(err.Error(), "No need to change position side") {
log.Printf(" ✓ 账户已是双向持仓模式Hedge Mode")
return nil
}
// 其他错误则返回(但在调用方不会中断初始化)
return err
}
log.Printf(" ✓ 账户已切换为双向持仓模式Hedge Mode")
log.Printf(" 双向持仓模式允许同时持有多单和空单")
return nil
}
// GetBalance 获取账户余额(带缓存)
@@ -411,6 +442,137 @@ func (t *FuturesTrader) CloseShort(symbol string, quantity float64) (map[string]
return result, nil
}
// CancelStopOrders 取消该币种的止盈/止损单(已废弃:会同时删除止损和止盈)
func (t *FuturesTrader) CancelStopOrders(symbol string) error {
// 获取该币种的所有未完成订单
orders, err := t.client.NewListOpenOrdersService().
Symbol(symbol).
Do(context.Background())
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
// 过滤出止盈止损单并取消
canceledCount := 0
for _, order := range orders {
orderType := order.Type
// 只取消止损和止盈订单
if orderType == futures.OrderTypeStopMarket ||
orderType == futures.OrderTypeTakeProfitMarket ||
orderType == futures.OrderTypeStop ||
orderType == futures.OrderTypeTakeProfit {
_, err := t.client.NewCancelOrderService().
Symbol(symbol).
OrderID(order.OrderID).
Do(context.Background())
if err != nil {
log.Printf(" ⚠ 取消订单 %d 失败: %v", order.OrderID, err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消 %s 的止盈/止损单 (订单ID: %d, 类型: %s)",
symbol, order.OrderID, orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈/止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈/止损单", symbol, canceledCount)
}
return nil
}
// CancelStopLossOrders 仅取消止损单(不影响止盈单)
func (t *FuturesTrader) CancelStopLossOrders(symbol string) error {
// 获取该币种的所有未完成订单
orders, err := t.client.NewListOpenOrdersService().
Symbol(symbol).
Do(context.Background())
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
// 过滤出止损单并取消
canceledCount := 0
for _, order := range orders {
orderType := order.Type
// 只取消止损订单(不取消止盈订单)
if orderType == futures.OrderTypeStopMarket || orderType == futures.OrderTypeStop {
_, err := t.client.NewCancelOrderService().
Symbol(symbol).
OrderID(order.OrderID).
Do(context.Background())
if err != nil {
log.Printf(" ⚠ 取消止损单 %d 失败: %v", order.OrderID, err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消止损单 (订单ID: %d, 类型: %s)", order.OrderID, orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止损单", symbol, canceledCount)
}
return nil
}
// CancelTakeProfitOrders 仅取消止盈单(不影响止损单)
func (t *FuturesTrader) CancelTakeProfitOrders(symbol string) error {
// 获取该币种的所有未完成订单
orders, err := t.client.NewListOpenOrdersService().
Symbol(symbol).
Do(context.Background())
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
// 过滤出止盈单并取消
canceledCount := 0
for _, order := range orders {
orderType := order.Type
// 只取消止盈订单(不取消止损订单)
if orderType == futures.OrderTypeTakeProfitMarket || orderType == futures.OrderTypeTakeProfit {
_, err := t.client.NewCancelOrderService().
Symbol(symbol).
OrderID(order.OrderID).
Do(context.Background())
if err != nil {
log.Printf(" ⚠ 取消止盈单 %d 失败: %v", order.OrderID, err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消止盈单 (订单ID: %d, 类型: %s)", order.OrderID, orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈单", symbol, canceledCount)
}
return nil
}
// CancelAllOrders 取消该币种的所有挂单
func (t *FuturesTrader) CancelAllOrders(symbol string) error {
err := t.client.NewCancelAllOpenOrdersService().
@@ -425,6 +587,53 @@ func (t *FuturesTrader) CancelAllOrders(symbol string) error {
return nil
}
// CancelStopOrders 取消该币种的止盈/止损单(用于调整止盈止损位置)
func (t *FuturesTrader) CancelStopOrders(symbol string) error {
// 获取该币种的所有未完成订单
orders, err := t.client.NewListOpenOrdersService().
Symbol(symbol).
Do(context.Background())
if err != nil {
return fmt.Errorf("获取未完成订单失败: %w", err)
}
// 过滤出止盈止损单并取消
canceledCount := 0
for _, order := range orders {
orderType := order.Type
// 只取消止损和止盈订单
if orderType == futures.OrderTypeStopMarket ||
orderType == futures.OrderTypeTakeProfitMarket ||
orderType == futures.OrderTypeStop ||
orderType == futures.OrderTypeTakeProfit {
_, err := t.client.NewCancelOrderService().
Symbol(symbol).
OrderID(order.OrderID).
Do(context.Background())
if err != nil {
log.Printf(" ⚠ 取消订单 %d 失败: %v", order.OrderID, err)
continue
}
canceledCount++
log.Printf(" ✓ 已取消 %s 的止盈/止损单 (订单ID: %d, 类型: %s)",
symbol, order.OrderID, orderType)
}
}
if canceledCount == 0 {
log.Printf(" %s 没有止盈/止损单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个止盈/止损单", symbol, canceledCount)
}
return nil
}
// GetMarketPrice 获取市场价格
func (t *FuturesTrader) GetMarketPrice(symbol string) (float64, error) {
prices, err := t.client.NewListPricesService().Symbol(symbol).Do(context.Background())

View File

@@ -2,10 +2,12 @@ package trader
import (
"context"
"crypto/ecdsa"
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/crypto"
"github.com/sonirico/go-hyperliquid"
@@ -22,6 +24,9 @@ type HyperliquidTrader struct {
// NewHyperliquidTrader 创建Hyperliquid交易器
func NewHyperliquidTrader(privateKeyHex string, walletAddr string, testnet bool) (*HyperliquidTrader, error) {
// 去掉私钥的 0x 前缀(如果有,不区分大小写)
privateKeyHex = strings.TrimPrefix(strings.ToLower(privateKeyHex), "0x")
// 解析私钥
privateKey, err := crypto.HexToECDSA(privateKeyHex)
if err != nil {
@@ -34,13 +39,18 @@ func NewHyperliquidTrader(privateKeyHex string, walletAddr string, testnet bool)
apiURL = hyperliquid.TestnetAPIURL
}
// // 从私钥生成钱包地址
// pubKey := privateKey.Public()
// publicKeyECDSA, ok := pubKey.(*ecdsa.PublicKey)
// if !ok {
// return nil, fmt.Errorf("无法转换公钥")
// }
// walletAddr := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
// 从私钥生成钱包地址(如果未提供)
if walletAddr == "" {
pubKey := privateKey.Public()
publicKeyECDSA, ok := pubKey.(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("无法转换公钥")
}
walletAddr = crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
log.Printf("✓ 从私钥自动生成钱包地址: %s", walletAddr)
} else {
log.Printf("✓ 使用提供的钱包地址: %s", walletAddr)
}
ctx := context.Background()
@@ -76,23 +86,54 @@ func NewHyperliquidTrader(privateKeyHex string, walletAddr string, testnet bool)
func (t *HyperliquidTrader) GetBalance() (map[string]interface{}, error) {
log.Printf("🔄 正在调用Hyperliquid API获取账户余额...")
// 获取账户状态
// ✅ Step 1: 查询 Spot 现货账户余额
spotState, err := t.exchange.Info().SpotUserState(t.ctx, t.walletAddr)
var spotUSDCBalance float64 = 0.0
if err != nil {
log.Printf("⚠️ 查询 Spot 余额失败(可能无现货资产): %v", err)
} else if spotState != nil && len(spotState.Balances) > 0 {
for _, balance := range spotState.Balances {
if balance.Coin == "USDC" {
spotUSDCBalance, _ = strconv.ParseFloat(balance.Total, 64)
log.Printf("✓ 发现 Spot 现货余额: %.2f USDC", spotUSDCBalance)
break
}
}
}
// ✅ Step 2: 查询 Perpetuals 合约账户状态
accountState, err := t.exchange.Info().UserState(t.ctx, t.walletAddr)
if err != nil {
log.Printf("❌ Hyperliquid API调用失败: %v", err)
log.Printf("❌ Hyperliquid Perpetuals API调用失败: %v", err)
return nil, fmt.Errorf("获取账户信息失败: %w", err)
}
// 解析余额信息MarginSummary字段都是string
result := make(map[string]interface{})
// 🔍 调试打印API返回的完整CrossMarginSummary结构
summaryJSON, _ := json.MarshalIndent(accountState.MarginSummary, " ", " ")
log.Printf("🔍 [DEBUG] Hyperliquid API CrossMarginSummary完整数据:")
log.Printf("%s", string(summaryJSON))
// ✅ Step 3: 根据保证金模式动态选择正确的摘要(CrossMarginSummary 或 MarginSummary
var accountValue, totalMarginUsed float64
var summaryType string
var summary interface{}
accountValue, _ := strconv.ParseFloat(accountState.MarginSummary.AccountValue, 64)
totalMarginUsed, _ := strconv.ParseFloat(accountState.MarginSummary.TotalMarginUsed, 64)
if t.isCrossMargin {
// 全仓模式:使用 CrossMarginSummary
accountValue, _ = strconv.ParseFloat(accountState.CrossMarginSummary.AccountValue, 64)
totalMarginUsed, _ = strconv.ParseFloat(accountState.CrossMarginSummary.TotalMarginUsed, 64)
summaryType = "CrossMarginSummary (全仓)"
summary = accountState.CrossMarginSummary
} else {
// 逐仓模式:使用 MarginSummary
accountValue, _ = strconv.ParseFloat(accountState.MarginSummary.AccountValue, 64)
totalMarginUsed, _ = strconv.ParseFloat(accountState.MarginSummary.TotalMarginUsed, 64)
summaryType = "MarginSummary (逐仓)"
summary = accountState.MarginSummary
}
// 🔍 调试打印API返回的完整摘要结构
summaryJSON, _ := json.MarshalIndent(summary, " ", " ")
log.Printf("🔍 [DEBUG] Hyperliquid API %s 完整数据:", summaryType)
log.Printf("%s", string(summaryJSON))
// ⚠️ 关键修复:从所有持仓中累加真正的未实现盈亏
totalUnrealizedPnl := 0.0
@@ -109,16 +150,47 @@ func (t *HyperliquidTrader) GetBalance() (map[string]interface{}, error) {
// 需要返回"不包含未实现盈亏的钱包余额"
walletBalanceWithoutUnrealized := accountValue - totalUnrealizedPnl
result["totalWalletBalance"] = walletBalanceWithoutUnrealized // 钱包余额(不含未实现盈亏
result["availableBalance"] = accountValue - totalMarginUsed // 可用余额(总净值 - 占用保证金)
result["totalUnrealizedProfit"] = totalUnrealizedPnl // 未实现盈亏
// ✅ Step 4: 使用 Withdrawable 欄位PR #443
// Withdrawable 是官方提供的真实可提现余额,比简单计算更可靠
availableBalance := 0.0
if accountState.Withdrawable != "" {
withdrawable, err := strconv.ParseFloat(accountState.Withdrawable, 64)
if err == nil && withdrawable > 0 {
availableBalance = withdrawable
log.Printf("✓ 使用 Withdrawable 作为可用余额: %.2f", availableBalance)
}
}
log.Printf("✓ Hyperliquid 账户: 总净值=%.2f (钱包%.2f+未实现%.2f), 可用=%.2f, 保证金占用=%.2f",
// 降级方案:如果没有 Withdrawable使用简单计算
if availableBalance == 0 && accountState.Withdrawable == "" {
availableBalance = accountValue - totalMarginUsed
if availableBalance < 0 {
log.Printf("⚠️ 计算出的可用余额为负数 (%.2f),重置为 0", availableBalance)
availableBalance = 0
}
}
// ✅ Step 5: 正確處理 Spot + Perpetuals 余额
// 重要Spot 只加到總資產,不加到可用餘額
// 原因Spot 和 Perpetuals 是獨立帳戶,需手動 ClassTransfer 才能轉帳
totalWalletBalance := walletBalanceWithoutUnrealized + spotUSDCBalance
result["totalWalletBalance"] = totalWalletBalance // 總資產Perp + Spot
result["availableBalance"] = availableBalance // 可用餘額(僅 Perpetuals不含 Spot
result["totalUnrealizedProfit"] = totalUnrealizedPnl // 未實現盈虧(僅來自 Perpetuals
result["spotBalance"] = spotUSDCBalance // Spot 現貨餘額(單獨返回)
log.Printf("✓ Hyperliquid 完整账户:")
log.Printf(" • Spot 现货余额: %.2f USDC (需手动转账到 Perpetuals 才能开仓)", spotUSDCBalance)
log.Printf(" • Perpetuals 合约净值: %.2f USDC (钱包%.2f + 未实现%.2f)",
accountValue,
walletBalanceWithoutUnrealized,
totalUnrealizedPnl,
result["availableBalance"],
totalMarginUsed)
totalUnrealizedPnl)
log.Printf(" • Perpetuals 可用余额: %.2f USDC (可直接用於開倉)", availableBalance)
log.Printf(" • 保证金占用: %.2f USDC", totalMarginUsed)
log.Printf(" • 總資產 (Perp+Spot): %.2f USDC", totalWalletBalance)
log.Printf(" ⭐ 总资产: %.2f USDC | Perp 可用: %.2f USDC | Spot 余额: %.2f USDC",
totalWalletBalance, availableBalance, spotUSDCBalance)
return result, nil
}
@@ -477,6 +549,56 @@ func (t *HyperliquidTrader) CloseShort(symbol string, quantity float64) (map[str
return result, nil
}
// CancelStopOrders 取消该币种的止盈/止损单
func (t *HyperliquidTrader) CancelStopOrders(symbol string) error {
coin := convertSymbolToHyperliquid(symbol)
// 获取所有挂单
openOrders, err := t.exchange.Info().OpenOrders(t.ctx, t.walletAddr)
if err != nil {
return fmt.Errorf("获取挂单失败: %w", err)
}
// 注意Hyperliquid SDK 的 OpenOrder 结构不暴露 trigger 字段
// 因此暂时取消该币种的所有挂单(包括止盈止损单)
// 这是安全的,因为在设置新的止盈止损之前,应该清理所有旧订单
canceledCount := 0
for _, order := range openOrders {
if order.Coin == coin {
_, err := t.exchange.Cancel(t.ctx, coin, order.Oid)
if err != nil {
log.Printf(" ⚠ 取消订单失败 (oid=%d): %v", order.Oid, err)
continue
}
canceledCount++
}
}
if canceledCount == 0 {
log.Printf(" %s 没有挂单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个挂单(包括止盈/止损单)", symbol, canceledCount)
}
return nil
}
// CancelStopLossOrders 仅取消止损单Hyperliquid 暂无法区分止损和止盈,取消所有)
func (t *HyperliquidTrader) CancelStopLossOrders(symbol string) error {
// Hyperliquid SDK 的 OpenOrder 结构不暴露 trigger 字段
// 无法区分止损和止盈单,因此取消该币种的所有挂单
log.Printf(" ⚠️ Hyperliquid 无法区分止损/止盈单,将取消所有挂单")
return t.CancelStopOrders(symbol)
}
// CancelTakeProfitOrders 仅取消止盈单Hyperliquid 暂无法区分止损和止盈,取消所有)
func (t *HyperliquidTrader) CancelTakeProfitOrders(symbol string) error {
// Hyperliquid SDK 的 OpenOrder 结构不暴露 trigger 字段
// 无法区分止损和止盈单,因此取消该币种的所有挂单
log.Printf(" ⚠️ Hyperliquid 无法区分止损/止盈单,将取消所有挂单")
return t.CancelStopOrders(symbol)
}
// CancelAllOrders 取消该币种的所有挂单
func (t *HyperliquidTrader) CancelAllOrders(symbol string) error {
coin := convertSymbolToHyperliquid(symbol)
@@ -501,6 +623,40 @@ func (t *HyperliquidTrader) CancelAllOrders(symbol string) error {
return nil
}
// CancelStopOrders 取消该币种的止盈/止损单(用于调整止盈止损位置)
func (t *HyperliquidTrader) CancelStopOrders(symbol string) error {
coin := convertSymbolToHyperliquid(symbol)
// 获取所有挂单
openOrders, err := t.exchange.Info().OpenOrders(t.ctx, t.walletAddr)
if err != nil {
return fmt.Errorf("获取挂单失败: %w", err)
}
// 注意Hyperliquid SDK 的 OpenOrder 结构不暴露 trigger 字段
// 因此暂时取消该币种的所有挂单(包括止盈止损单)
// 这是安全的,因为在设置新的止盈止损之前,应该清理所有旧订单
canceledCount := 0
for _, order := range openOrders {
if order.Coin == coin {
_, err := t.exchange.Cancel(t.ctx, coin, order.Oid)
if err != nil {
log.Printf(" ⚠ 取消订单失败 (oid=%d): %v", order.Oid, err)
continue
}
canceledCount++
}
}
if canceledCount == 0 {
log.Printf(" %s 没有挂单需要取消", symbol)
} else {
log.Printf(" ✓ 已取消 %s 的 %d 个挂单(包括止盈/止损单)", symbol, canceledCount)
}
return nil
}
// GetMarketPrice 获取市场价格
func (t *HyperliquidTrader) GetMarketPrice(symbol string) (float64, error) {
coin := convertSymbolToHyperliquid(symbol)

View File

@@ -36,9 +36,22 @@ type Trader interface {
// SetTakeProfit 设置止盈单
SetTakeProfit(symbol string, positionSide string, quantity, takeProfitPrice float64) error
// CancelStopOrders 取消该币种的止盈/止损单(已废弃:会同时删除止损和止盈)
// 请使用 CancelStopLossOrders 或 CancelTakeProfitOrders
CancelStopOrders(symbol string) error
// CancelStopLossOrders 仅取消止损单(修复 BUG调整止损时不删除止盈
CancelStopLossOrders(symbol string) error
// CancelTakeProfitOrders 仅取消止盈单(修复 BUG调整止盈时不删除止损
CancelTakeProfitOrders(symbol string) error
// CancelAllOrders 取消该币种的所有挂单
CancelAllOrders(symbol string) error
// CancelStopOrders 取消该币种的止盈/止损单(用于调整止盈止损位置)
CancelStopOrders(symbol string) error
// FormatQuantity 格式化数量到正确的精度
FormatQuantity(symbol string, quantity float64) (string, error)
}