From 24bd0399d73a2d48e50233326fca7d9526f06259 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Mon, 29 Dec 2025 14:15:59 +0800
Subject: [PATCH] refactor(trading): 重构MACD策略交易信号生成逻辑

---
 src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java |  357 ++++++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 255 insertions(+), 102 deletions(-)

diff --git a/src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java b/src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java
index b9b0fc6..2490c43 100644
--- a/src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java
+++ b/src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java
@@ -22,11 +22,20 @@
 public class MacdMaStrategy {
 
     /** 持仓状态枚举 */
+    public enum OperationType {
+        /** 开仓平仓 */
+        open,
+        close
+    }
+
+    /** 持仓状态枚举 */
     public enum PositionType {
         /** 多头持仓 */
-        LONG,
+        LONG_BUY,
+        LONG_SELL,
         /** 空头持仓 */
-        SHORT,
+        SHORT_SELL,
+        SHORT_BUY,
         /** 空仓 */
         NONE
     }
@@ -38,10 +47,6 @@
     private int volatilityPeriod; // 波动率计算周期
     private BigDecimal stopLossRatio;   // 止损比例
     private BigDecimal takeProfitRatio; // 止盈比例
-
-    // 持仓信息
-    private BigDecimal entryPrice;       // 开仓价格
-    private long entryTime;              // 开仓时间戳
 
     /**
      * 默认构造函数,使用标准MACD参数
@@ -71,9 +76,6 @@
         this.stopLossRatio = stopLossRatio;
         this.takeProfitRatio = takeProfitRatio;
 
-        // 初始化持仓状态为空仓
-        this.entryPrice = BigDecimal.ZERO;
-        this.entryTime = 0;
     }
 
     /**
@@ -82,7 +84,7 @@
      * @param closePrices 收盘价序列
      * @return 生成的交易信号(LONG、SHORT或NONE)
      */
-    public PositionType analyze(List<BigDecimal> closePrices) {
+    public PositionType analyzeOpen(List<BigDecimal> closePrices) {
         // 数据检查:确保有足够的数据点进行计算
         if (closePrices == null || closePrices.size() < 34) {
             return PositionType.NONE; // 数据不足,无法生成信号
@@ -107,17 +109,49 @@
         // 多头开仓条件检查
         if (isLongEntryCondition(macdResult, closePrices, volatility.getValue())) {
             // 执行开多
-            this.entryPrice = latestPrice;
-            this.entryTime = System.currentTimeMillis();
-            return PositionType.LONG;
+            log.info( "多头开仓信号,价格:{}", latestPrice);
+            return PositionType.LONG_BUY;
         }
 
         // 空头开仓条件检查
         if (isShortEntryCondition(macdResult, closePrices, volatility.getValue())) {
             // 执行开空
-            this.entryPrice = latestPrice;
-            this.entryTime = System.currentTimeMillis();
-            return PositionType.SHORT;
+             log.info( "空头开仓信号,价格:{}", latestPrice);
+            return PositionType.SHORT_SELL;
+        }
+        // 无信号
+        return PositionType.NONE;
+
+    }
+
+    /**
+     * 分析最新价格数据并生成交易信号
+     *
+     * @param closePrices 收盘价序列
+     * @return 生成的交易信号(LONG、SHORT或NONE)
+     */
+    public PositionType analyzeClose(List<BigDecimal> closePrices) {
+        // 数据检查:确保有足够的数据点进行计算
+        if (closePrices == null || closePrices.size() < 34) {
+            return PositionType.NONE; // 数据不足,无法生成信号
+        }
+
+        // 1. 计算MACD指标
+        MACDResult macdResult = MACDCalculator.calculateMACD(
+                closePrices, shortPeriod, longPeriod, signalPeriod);
+
+        // 最新收盘价
+        BigDecimal latestPrice = closePrices.get(closePrices.size() - 1);
+
+        if (isLongExitCondition(macdResult, latestPrice)) {
+            // 执行平多
+            log.info( "多头平仓信号,价格:{}", latestPrice);
+            return PositionType.LONG_SELL;
+        }
+        if (isShortExitCondition(macdResult, latestPrice)) {
+            // 执行平空
+            log.info( "空头平仓信号,价格:{}", latestPrice);
+            return PositionType.SHORT_BUY;
         }
 
         // 无信号
@@ -157,16 +191,31 @@
      * @param historicalPrices 历史价格序列
      * @return 交易指令(包含side和posSide),如果没有交易信号则返回null
      */
-    public TradingOrder generateTradingOrder(List<BigDecimal> historicalPrices) {
-        PositionType signal = analyze(historicalPrices);
+    public TradingOrder generateTradingOrder(List<BigDecimal> historicalPrices,String operation) {
+        PositionType signal =  null;
 
+        if ( operation == OperationType.open.name()){
+
+            signal = analyzeOpen(historicalPrices);
+
+        }else  if ( operation == OperationType.close.name()){
+
+            analyzeClose(historicalPrices);
+
+        }
         // 根据信号和当前持仓状态生成交易指令
-        if (signal == PositionType.LONG) {
+        if (signal == PositionType.LONG_BUY) {
             // 开多:买入开多(side 填写 buy; posSide 填写 long )
             return new TradingOrder("buy", "long");
-        } else if (signal == PositionType.SHORT) {
+        } else if (signal == PositionType.LONG_SELL) {
+            // 开空:卖出开空(side 填写 sell; posSide 填写 short )
+            return new TradingOrder("sell", "long");
+        } else if (signal == PositionType.SHORT_SELL) {
             // 开空:卖出开空(side 填写 sell; posSide 填写 short )
             return new TradingOrder("sell", "short");
+        } else if (signal == PositionType.SHORT_BUY) {
+            // 开空:卖出开空(side 填写 sell; posSide 填写 short )
+            return new TradingOrder("buy", "short");
         }
         // 没有交易信号
         return null;
@@ -181,72 +230,110 @@
      * @return 是否满足多头开仓条件
      */
     private boolean isLongEntryCondition(MACDResult macdResult, List<BigDecimal> closePrices, BigDecimal volatility) {
-        // 1. EMA金叉检查(简化为只检查当前短期EMA > 当前长期EMA)
-        List<PriceData> macdData = macdResult.getMacdData();
-        if (macdData.size() < 1) {
-            return false;
+
+        // 2. MACD金叉且柱状线扩张检查
+        boolean isMacdFavorable = isMacdGoldenCrossAndExpanding(macdResult);
+        
+        // 3. MACD柱状线必须为正
+        boolean macdPositive = isMacdPositive(macdResult);
+        
+        // 4. 波动率过滤(必须在合理范围内)
+        boolean volatilityFilter = isVolatilityInRange(volatility);
+        
+        if (macdPositive && volatilityFilter && isMacdFavorable) {
+            log.info("多头信号形成, MACD有利状态: {}, 柱状线为正: {}, 波动率过滤: {}",
+                    isMacdFavorable, macdPositive, volatilityFilter);
         }
-        boolean bullishSignalFormed = BullishSignalDetector.isBullishSignalFormed(macdResult, closePrices);
-        boolean isExpanding = isExpanding(macdResult);
-
-        PriceData latest = macdData.get(macdData.size() - 1);
-        // 2. MACD柱状线为正
-        boolean macdPositive = latest.getMacdHist().compareTo(BigDecimal.ZERO) > 0;
-
-        // 3. 简化的波动率检查
-        boolean volatilityFilter = volatility.compareTo(BigDecimal.ZERO) > 0;
-
-        if ( bullishSignalFormed  && macdPositive && volatilityFilter){
-            log.info( "EMA金叉: {},扩张:{}", bullishSignalFormed,isExpanding);
-            log.info( "MACD柱状线为正: {}" ,macdPositive);
-            log.info( "波动率过滤: {}" ,volatilityFilter);
-        }
-        // 只需要EMA短期在长期上方、MACD柱状线为正且波动率大于0
-        return bullishSignalFormed && macdPositive && isExpanding && volatilityFilter;
+        
+        // 所有条件必须同时满足
+        return macdPositive && volatilityFilter && isMacdFavorable;
     }
 
     /**
      * 空头开仓条件检查
-     *
+     * 
      * @param macdResult MACD计算结果
      * @param closePrices 收盘价序列
      * @param volatility 当前波动率
      * @return 是否满足空头开仓条件
      */
-    private boolean isShortEntryCondition(MACDResult macdResult, List<BigDecimal> closePrices,
-                                          BigDecimal volatility) {
-        List<PriceData> macdData = macdResult.getMacdData();
-        if (macdData.size() < 1) {
-            return false;
-        }
-        boolean bearishSignalFormed = BearishSignalDetector.isBearishSignalFormed(macdResult, closePrices);
-        // 2. MACD柱状线收缩+死叉检查
-        boolean isContracting = isContracting(macdResult);
-
-        // 2. MACD柱状线为负
-        PriceData latest = macdData.get(macdData.size() - 1);
-        boolean macdPositive = latest.getMacdHist().compareTo(BigDecimal.ZERO) < 0;
-
-
-        // 4. 波动率过滤检查(0.5% ~ 5%)
+    private boolean isShortEntryCondition(MACDResult macdResult, List<BigDecimal> closePrices, BigDecimal volatility) {
+        // 2. MACD死叉且柱状线收缩检查
+        boolean isMacdFavorable = isMacdDeathCrossAndContracting(macdResult);
+        
+        // 3. MACD柱状线必须为负
+        boolean macdNegative = isMacdNegative(macdResult);
+        
+        // 4. 波动率过滤(必须在合理范围内)
         boolean volatilityFilter = isVolatilityInRange(volatility);
-        if ( isContracting&& volatilityFilter){
-            log.info( "MACD柱状线死叉: {},收缩: {}", bearishSignalFormed,isContracting);
-            log.info( "MACD柱状线为负: {}" ,macdPositive);
-            log.info( "波动率过滤: {}", volatilityFilter);
+        
+        if (macdNegative && volatilityFilter && isMacdFavorable) {
+            log.info("空头信号形成, MACD有利状态: {}, 柱状线为负: {}, 波动率过滤: {}",
+                    isMacdFavorable, macdNegative, volatilityFilter);
         }
-
+        
         // 所有条件必须同时满足
-        return isContracting && volatilityFilter && macdPositive && bearishSignalFormed;
+        return macdNegative && volatilityFilter && isMacdFavorable;
     }
+    
+    /**
+     * 多头平仓条件检查
+     * 
+     * @param macdResult MACD计算结果
+     * @param currentPrice 当前价格
+     * @return 是否满足多头平仓条件
+     */
+    private boolean isLongExitCondition(MACDResult macdResult, BigDecimal currentPrice) {
+        // 1. MACD柱状线由正转负(动量转变)
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() >= 2) {
+            PriceData latest = macdData.get(macdData.size() - 1);
+            PriceData previous = macdData.get(macdData.size() - 2);
 
+            boolean momentumShift = previous.getMacdHist().compareTo(BigDecimal.ZERO) >= 0 && 
+                                   latest.getMacdHist().abs().compareTo(previous.getMacdHist().abs()) < 0;
+            if (momentumShift) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    /**
+     * 空头平仓条件检查
+     * 
+     * @param macdResult MACD计算结果
+     * @param currentPrice 当前价格
+     * @return 是否满足空头平仓条件
+     */
+    private boolean isShortExitCondition(MACDResult macdResult, BigDecimal currentPrice) {
+        // 1. MACD柱状线由负转正(动量转变)
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() >= 2) {
+            PriceData latest = macdData.get(macdData.size() - 1);
+            PriceData previous = macdData.get(macdData.size() - 2);
+            
+            boolean momentumShift = previous.getMacdHist().compareTo(BigDecimal.ZERO) <= 0 &&
+                                latest.getMacdHist().abs().compareTo(previous.getMacdHist().abs()) < 0;
+            if (momentumShift) {
+                return true;
+            }
+        }
+        
+        return false;
+    }
+    
     /**
      * MACD金叉且柱状线扩张检查
-     *
+     * <p>
+     * 条件:
+     * 1. DIF线从下往上穿过DEA线(金叉)
+     * 2. MACD柱状线绝对值增大且为正值(动量增强)
+     * 
      * @param macdResult MACD计算结果
-     * @return 是否形成MACD金叉且柱状线扩张
+     * @return 是否形成MACD金叉或柱状线扩张
      */
-    private boolean isExpanding(MACDResult macdResult) {
+    private boolean isMacdGoldenCrossAndExpanding(MACDResult macdResult) {
         List<PriceData> macdData = macdResult.getMacdData();
         if (macdData.size() < 3) {
             return false;
@@ -254,21 +341,82 @@
 
         PriceData latest = macdData.get(macdData.size() - 1);
         PriceData previous = macdData.get(macdData.size() - 2);
+        PriceData prevPrev = macdData.get(macdData.size() - 3);
+        
+        // 金叉判断:DIF从下往上穿过DEA
+        boolean isGoldenCross = prevPrev.getDif().compareTo(prevPrev.getDea()) <= 0 && 
+                              previous.getDif().compareTo(previous.getDea()) > 0;
+        
+        // 柱状线扩张判断:连续正值且绝对值增大
+        boolean isExpanding = latest.getMacdHist().compareTo(BigDecimal.ZERO) > 0 && 
+                            previous.getMacdHist().compareTo(BigDecimal.ZERO) > 0 &&
+                            previous.getMacdHist().abs().compareTo(latest.getMacdHist().abs()) < 0;
+        
+        // 金叉或柱状线扩张任一满足即可
+        return isGoldenCross && isExpanding;
+    }
+    
+    /**
+     * MACD柱状线扩张检查
+     * <p>
+     * 条件:当前MACD柱状线绝对值大于前一根
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否扩张
+     */
+    private boolean isExpanding(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() < 2) {
+            return false;
+        }
 
-
-        // 2. MACD柱状线扩张检查
-        boolean histogramExpanding =
-                previous.getMacdHist().compareTo(latest.getMacdHist()) < 0 &&
-                latest.getMacdHist().compareTo(BigDecimal.ZERO) > 0;
-
-        return histogramExpanding;
+        PriceData latest = macdData.get(macdData.size() - 1);
+        PriceData previous = macdData.get(macdData.size() - 2);
+        
+        // MACD柱状线扩张:当前绝对值大于前一根
+        return latest.getMacdHist().abs().compareTo(previous.getMacdHist().abs()) > 0;
     }
 
     /**
      * MACD死叉且柱状线收缩检查
-     *
+     * <p>
+     * 条件:
+     * 1. DIF线从上往下穿过DEA线(死叉)
+     * 2. MACD柱状线绝对值减小且为负值(动量减弱)
+     * 
      * @param macdResult MACD计算结果
-     * @return 是否形成MACD死叉且柱状线收缩
+     * @return 是否形成MACD死叉或柱状线收缩
+     */
+    private boolean isMacdDeathCrossAndContracting(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() < 3) {
+            return false;
+        }
+
+        PriceData latest = macdData.get(macdData.size() - 1);
+        PriceData previous = macdData.get(macdData.size() - 2);
+        PriceData prevPrev = macdData.get(macdData.size() - 3);
+        
+        // 死叉判断:DIF从上往下穿过DEA
+        boolean isDeathCross = prevPrev.getDif().compareTo(prevPrev.getDea()) >= 0 && 
+                             previous.getDif().compareTo(previous.getDea()) < 0;
+        
+        // 柱状线收缩判断:连续负值且绝对值减小
+        boolean isContracting = latest.getMacdHist().compareTo(BigDecimal.ZERO) < 0 && 
+                              previous.getMacdHist().compareTo(BigDecimal.ZERO) < 0 &&
+                              previous.getMacdHist().abs().compareTo(latest.getMacdHist().abs()) > 0;
+        
+        // 死叉或柱状线收缩任一满足即可
+        return isDeathCross && isContracting;
+    }
+    
+    /**
+     * MACD柱状线收缩检查
+     * <p>
+     * 条件:前一根MACD柱状线绝对值大于当前
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否收缩
      */
     private boolean isContracting(MACDResult macdResult) {
         List<PriceData> macdData = macdResult.getMacdData();
@@ -278,14 +426,37 @@
 
         PriceData latest = macdData.get(macdData.size() - 1);
         PriceData previous = macdData.get(macdData.size() - 2);
-
-        // 2. MACD柱状线收缩检查(绝对值减小)
-        boolean histogramContracting =
-                previous.getMacdHist().abs().compareTo(
-                        latest.getMacdHist().abs()) < 0 &&
-                latest.getMacdHist().compareTo(BigDecimal.ZERO) < 0;
-
-        return histogramContracting;
+        
+        // MACD柱状线收缩:前一根绝对值大于当前
+        return previous.getMacdHist().abs().compareTo(latest.getMacdHist().abs()) > 0;
+    }
+    
+    /**
+     * 检查MACD柱状线是否为正值
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否为正值
+     */
+    private boolean isMacdPositive(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.isEmpty()) {
+            return false;
+        }
+        return macdData.get(macdData.size() - 1).getMacdHist().compareTo(BigDecimal.ZERO) > 0;
+    }
+    
+    /**
+     * 检查MACD柱状线是否为负值
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否为负值
+     */
+    private boolean isMacdNegative(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.isEmpty()) {
+            return false;
+        }
+        return macdData.get(macdData.size() - 1).getMacdHist().compareTo(BigDecimal.ZERO) < 0;
     }
 
     /**
@@ -302,22 +473,4 @@
                 volatility.compareTo(maxVolatility) <= 0;
     }
 
-
-    /**
-     * 获取开仓价格
-     *
-     * @return 开仓价格
-     */
-    public BigDecimal getEntryPrice() {
-        return entryPrice;
-    }
-
-    /**
-     * 获取开仓时间戳
-     *
-     * @return 开仓时间戳
-     */
-    public long getEntryTime() {
-        return entryTime;
-    }
 }
\ No newline at end of file

--
Gitblit v1.9.1