From 212e20fa6e9d0cc69d7f70339ecd47d4ec286533 Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Sun, 04 Jan 2026 11:03:41 +0800
Subject: [PATCH] feat(okxNewPrice): 优化MACD策略交易判断逻辑

---
 src/main/java/com/xcong/excoin/modules/okxNewPrice/indicator/macdAndMatrategy/MacdMaStrategy.java |  800 ++++++++++++++++++++++++++++++++------------------------
 1 files changed, 451 insertions(+), 349 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 e70ffa1..a335dd8 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
@@ -1,378 +1,480 @@
+/**
+ * MACD和MA组合交易策略实现类
+ * 基于15分钟K线数据生成交易信号并确定持仓方向
+ *
+ * 该策略综合考虑了EMA指标、MACD指标、价格突破信号和波动率因素,
+ * 形成了一套完整的开仓、平仓和持仓管理机制。
+ */
 package com.xcong.excoin.modules.okxNewPrice.indicator.macdAndMatrategy;
 
-import com.xcong.excoin.modules.okxNewPrice.indicator.*;
+import lombok.extern.slf4j.Slf4j;
+
 import java.math.BigDecimal;
 import java.util.List;
 
 /**
- * MACD+MA复合交易策略实现类
- * 
- * 【策略核心思想】
- * 结合移动平均线(MA)的趋势判断能力和MACD指标的动量分析能力,构建一个兼顾趋势跟踪和入场时机的复合交易策略。
- * 
- * 【策略主要特点】
- * 1. **趋势导向**:以长期MA(100日)作为ETH市场趋势的主要判断依据
- * 2. **精确入场**:利用MACD指标的动量变化和短期MA(30日)的支撑/阻力作用确定最佳入场点
- * 3. **风险控制**:通过RSI和波动率指标过滤掉风险较高的交易信号,并设置明确的止损止盈
- * 4. **分层离场**:结合技术指标、移动平均线和风险控制构建多重离场机制
- * 5. **动态调整**:MACD周期根据市场波动率自动调整,适应ETH高波动特性
- * 
- * 【核心交易逻辑】
- * 1. **趋势判断**:当前价格高于长期MA(100日)判定为牛市,低于则为熊市
- * 2. **入场条件**:
- *    - 牛市:MACD多头信号(DIF>DEA) 且 价格>短期MA(30日) 且 MACD柱状图>0 且 RSI在合理区间
- *    - 熊市:MACD空头信号(DIF<DEA) 且 价格<短期MA(30日) 且 MACD柱状图<0 且 RSI在合理区间
- * 3. **离场条件**:
- *    - 牛市多头持仓:MACD空头信号(DIF<DEA) 或 价格跌破短期MA 或 触及止损/止盈
- *    - 熊市空头持仓:MACD多头信号(DIF>DEA) 或 价格突破短期MA 或 触及止损/止盈
- * 4. **过滤条件**:
- *    - 高风险过滤:RSI>65时不追多,RSI<35时不追空
- *    - 低波动过滤:波动率<0.5%或>5%时不进行交易
- * 
- * 【适用场景】
- * 专为ETH合约设计,适用于ETH高波动、24/7交易的市场环境,适合中短线趋势交易。
- * 
- * 【风险提示】
- * 1. 策略需要至少200个价格数据点才能有效运行
- * 2. 在极端市场条件下(如黑天鹅事件)可能会产生较大亏损
- * 3. 建议结合其他风险控制手段(如止损设置)使用
+ * MACD和MA组合交易策略实现
+ * <p>
+ * 该策略利用EMA交叉、MACD指标、价格突破信号和波动率过滤,
+ * 为15分钟K线级别交易提供综合决策支持。
  */
+@Slf4j
 public class MacdMaStrategy {
-    /**
-     * 策略使用的技术指标实例(适配ETH合约特点)
-     */
-    // MACD指标:用于判断价格动量和趋势变化
-    private final MACD macd = new MACD();
-    // 30日移动平均线:ETH波动较大,使用更短的周期捕捉趋势变化
-    private final MovingAverage ma30 = new MovingAverage(30);
-    // 100日移动平均线:ETH作为高波动资产,长期趋势判断使用更短周期
-    private final MovingAverage ma100 = new MovingAverage(100);
-    // RSI指标(10周期):ETH波动快,使用更短周期提高响应速度
-    private final RSI rsi = new RSI(10);
-    // 波动率指标(15周期):ETH波动频繁,使用更短周期捕捉市场变化
-    private final Volatility volatility = new Volatility(15);
+
+    /** 持仓状态枚举 */
+    public enum OperationType {
+        /** 开仓平仓 */
+        open,
+        close
+    }
+
+    /** 持仓状态枚举 */
+    public enum PositionType {
+        /** 多头持仓 */
+        LONG_BUY,
+        LONG_SELL,
+        /** 空头持仓 */
+        SHORT_SELL,
+        SHORT_BUY,
+        /** 空仓 */
+        NONE
+    }
+
+    // 策略参数
+    private int shortPeriod;      // 短期EMA周期
+    private int longPeriod;       // 长期EMA周期
+    private int signalPeriod;     // MACD信号线周期
+    private int volatilityPeriod; // 波动率计算周期
+    private BigDecimal stopLossRatio;   // 止损比例
+    private BigDecimal takeProfitRatio; // 止盈比例
 
     /**
-     * 策略配置参数(适配ETH合约特点)
+     * 默认构造函数,使用标准MACD参数
+     * 短期周期=12, 长期周期=26, 信号线周期=9, 波动率周期=20
+     * 止损比例=1%, 止盈比例=2%
      */
-    // 止损比例(ETH波动较大,设置2.5%)
-    private final BigDecimal stopLossRatio = new BigDecimal("0.025");
-    // 止盈比例(ETH趋势明显,设置6%)
-    private final BigDecimal takeProfitRatio = new BigDecimal("0.06");
-    // 账户初始余额(USD)
-    private BigDecimal accountBalance = new BigDecimal("10000");
-    // 每次交易风险比例(ETH合约风险较高,设置0.8%)
-    private final BigDecimal riskPerTrade = new BigDecimal("0.008");
-    // 杠杆倍数(ETH合约建议使用3-5倍,这里使用4倍)
-    private final int leverage = 4;
+    public MacdMaStrategy() {
+        this(12, 26, 9, 20, new BigDecimal("0.01"), new BigDecimal("0.02"));
+    }
+
+    /**
+     * 自定义参数构造函数
+     *
+     * @param shortPeriod 短期EMA周期
+     * @param longPeriod 长期EMA周期
+     * @param signalPeriod MACD信号线周期
+     * @param volatilityPeriod 波动率计算周期
+     * @param stopLossRatio 止损比例
+     * @param takeProfitRatio 止盈比例
+     */
+    public MacdMaStrategy(int shortPeriod, int longPeriod, int signalPeriod, int volatilityPeriod,
+                          BigDecimal stopLossRatio, BigDecimal takeProfitRatio) {
+        this.shortPeriod = shortPeriod;
+        this.longPeriod = longPeriod;
+        this.signalPeriod = signalPeriod;
+        this.volatilityPeriod = volatilityPeriod;
+        this.stopLossRatio = stopLossRatio;
+        this.takeProfitRatio = takeProfitRatio;
+
+    }
+
+    /**
+     * 分析最新价格数据并生成交易信号
+     *
+     * @param closePrices 收盘价序列
+     * @return 生成的交易信号(LONG、SHORT或NONE)
+     */
+    public PositionType analyzeOpen(List<BigDecimal> closePrices) {
+        // 数据检查:确保有足够的数据点进行计算
+        if (closePrices == null || closePrices.size() < 34) {
+            return PositionType.NONE; // 数据不足,无法生成信号
+        }
+
+        // 1. 计算MACD指标
+        MACDResult macdResult = MACDCalculator.calculateMACD(
+                closePrices, shortPeriod, longPeriod, signalPeriod);
+
+        // 2. 计算波动率
+        Volatility volatility = new Volatility(volatilityPeriod);
+        for (int i = Math.max(0, closePrices.size() - volatilityPeriod);
+             i < closePrices.size(); i++) {
+            volatility.addPrice(closePrices.get(i));
+        }
+        volatility.calculate();
+
+        // 最新收盘价
+        BigDecimal latestPrice = closePrices.get(closePrices.size() - 1);
+
+        // 3. 检查开平仓条件
+        // 多头开仓条件检查
+        if (isLongEntryCondition(macdResult, closePrices, volatility.getValue())) {
+            // 执行开多
+            log.info( "多头开仓信号,价格:{}", latestPrice);
+            return PositionType.LONG_BUY;
+        }
+
+        // 空头开仓条件检查
+        if (isShortEntryCondition(macdResult, closePrices, volatility.getValue())) {
+            // 执行开空
+             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;
+        }
+
+        // 无信号
+        return PositionType.NONE;
+
+    }
+
+    /**
+     * 交易指令类,封装side和posSide的组合
+     */
+    public static class TradingOrder {
+        private String side;    // buy或sell
+        private String posSide; // long或short
+
+        public TradingOrder(String side, String posSide) {
+            this.side = side;
+            this.posSide = posSide;
+        }
+
+        public String getSide() {
+            return side;
+        }
+
+        public String getPosSide() {
+            return posSide;
+        }
+
+        @Override
+        public String toString() {
+            return String.format("TradingOrder{side='%s', posSide='%s'}", side, posSide);
+        }
+    }
+
+    /**
+     * 分析历史价格数据并生成交易指令
+     *
+     * @param historicalPrices 历史价格序列
+     * @return 交易指令(包含side和posSide),如果没有交易信号则返回null
+     */
+    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()){
+
+            signal = analyzeClose(historicalPrices);
+
+        }
+        // 根据信号和当前持仓状态生成交易指令
+        if (signal == PositionType.LONG_BUY) {
+            // 开多:买入开多(side 填写 buy; posSide 填写 long )
+            return new TradingOrder("buy", "long");
+        } 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;
+    }
+
+    /**
+     * 多头开仓条件检查
+     *
+     * @param macdResult MACD计算结果
+     * @param closePrices 收盘价序列
+     * @param volatility 当前波动率
+     * @return 是否满足多头开仓条件
+     */
+    private boolean isLongEntryCondition(MACDResult macdResult, List<BigDecimal> closePrices, BigDecimal volatility) {
+
+        // 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);
+        }
+        
+        // 所有条件必须同时满足
+        return macdPositive && volatilityFilter && isMacdFavorable;
+    }
+
+    /**
+     * 空头开仓条件检查
+     * 
+     * @param macdResult MACD计算结果
+     * @param closePrices 收盘价序列
+     * @param volatility 当前波动率
+     * @return 是否满足空头开仓条件
+     */
+    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 (macdNegative && volatilityFilter && isMacdFavorable) {
+            log.info("空头信号形成, MACD有利状态: {}, 柱状线为负: {}, 波动率过滤: {}",
+                    isMacdFavorable, macdNegative, volatilityFilter);
+        }
+        
+        // 所有条件必须同时满足
+        return macdNegative && volatilityFilter && isMacdFavorable;
+    }
     
     /**
-     * 策略运行状态变量
-     */
-    // 当前持仓状态:空仓/多头/空头
-    private PositionStatus position = PositionStatus.FLAT;
-    // 最新价格:用于策略判断
-    private BigDecimal lastPrice;
-    // 当前市场趋势:牛市/熊市
-    private TrendDirection trend;
-    // 持仓均价:用于计算盈亏和止损止盈
-    private BigDecimal entryPrice;
-    // 止损价格:根据止损比例计算
-    private BigDecimal stopLossPrice;
-    // 止盈价格:根据止盈比例计算
-    private BigDecimal takeProfitPrice;
-    // 当前持仓数量(ETH)
-    private BigDecimal positionSize = BigDecimal.ZERO;
-    // 已用保证金(USD)
-    private BigDecimal usedMargin = BigDecimal.ZERO;
-
-    /**
-     * 策略执行的主入口方法
+     * 多头平仓条件检查
      * 
-     * @param prices 历史价格数据列表
-     * @throws IllegalArgumentException 如果价格数据不足200个
+     * @param macdResult MACD计算结果
+     * @param currentPrice 当前价格
+     * @return 是否满足多头平仓条件
      */
-    public void execute(List<BigDecimal> prices) {
-        // 验证输入数据完整性:策略需要至少200个价格数据点
-        if (prices.size() < 200) {
-            throw new IllegalArgumentException("至少需要200个价格数据点才能运行该策略");
-        }
+    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);
 
-        // 第一步:更新所有技术指标
-        updateIndicators(prices);
-
-        // 第二步:确定当前市场趋势
-        determineTrend(prices);
-
-        // 第三步:检查是否需要跳过当前交易
-        if (shouldSkipTrade()) {
-            return;
-        }
-
-        // 第四步:根据持仓状态执行相应的交易逻辑
-        if (position == PositionStatus.FLAT) {
-            // 空仓状态下检查入场信号
-            checkEntrySignal();
-        } else {
-            // 持仓状态下检查离场信号
-            checkExitSignal();
-        }
-    }
-
-    /**
-     * 更新所有技术指标的计算结果
-     * 
-     * @param prices 历史价格数据列表
-     */
-    private void updateIndicators(List<BigDecimal> prices) {
-        // 先计算波动率指标,因为MACD需要用它来动态调整周期
-        volatility.calculate(prices);
-        // 计算MACD指标并传入波动率参数,实现动态周期调整
-        macd.calculate(prices, volatility.getValue());
-        // 计算移动平均线指标
-        ma30.calculate(prices);      // 计算30日移动平均线
-        ma100.calculate(prices);     // 计算100日移动平均线
-        // 计算RSI指标
-        rsi.calculate(prices);
-        // 更新最新价格
-        lastPrice = prices.get(prices.size()-1);
-    }
-
-    /**
-     * 确定当前市场趋势(牛市/熊市)
-     * 
-     * @param prices 历史价格数据列表
-     */
-    private void determineTrend(List<BigDecimal> prices) {
-        BigDecimal currentMa100 = ma100.getMa(); // 获取当前100日移动平均线
-        // 根据最新价格与100日MA的关系判断趋势:价格高于100日MA为牛市,否则为熊市
-        trend = lastPrice.compareTo(currentMa100) > 0 ?
-                TrendDirection.BULLISH : TrendDirection.BEARISH;
-    }
-
-    /**
-     * 检查是否需要跳过当前交易
-     * 
-     * @return true表示需要跳过交易,false表示可以进行交易
-     */
-    private boolean shouldSkipTrade() {
-        // 波动率过滤:当波动率小于1%时,市场活跃度不足,跳过交易
-        if (volatility.getValue().compareTo(new BigDecimal("0.01")) < 0) {
-            return true;
-        }
-
-        // RSI极端值过滤:
-        // 1. 牛市中RSI>65表示超买,避免追高
-        // 2. 熊市中RSI<35表示超卖,避免追空
-        if (trend == TrendDirection.BULLISH && rsi.getRsi().compareTo(new BigDecimal(65)) > 0) {
-            return true;
-        }
-        if (trend == TrendDirection.BEARISH && rsi.getRsi().compareTo(new BigDecimal(35)) < 0) {
-            return true;
+            boolean momentumShift = previous.getMacdHist().compareTo(BigDecimal.ZERO) >= 0 && 
+                                   latest.getMacdHist().abs().compareTo(previous.getMacdHist().abs()) < 0;
+            if (momentumShift) {
+                return true;
+            }
         }
         return false;
     }
-
+    
     /**
-     * 检查是否满足入场信号条件
-     */
-    private void checkEntrySignal() {
-        BigDecimal currentMa30 = ma30.getMa(); // 获取当前30日移动平均线
-
-        // 获取MACD的最新值用于判断动量方向
-        BigDecimal currentDif = macd.getDif();
-        BigDecimal currentDea = macd.getDea();
-        BigDecimal macdBar = macd.getMacdBar(); // 获取MACD柱状图值
-        
-        // 获取RSI的最新值
-        BigDecimal currentRsi = rsi.getRsi();
-        // 获取波动率的最新值
-        BigDecimal currentVolatility = volatility.getValue();
-
-        // 根据市场趋势判断入场条件
-        if (trend == TrendDirection.BULLISH) {
-            // 牛市入场条件增强:
-            // 1. MACD多头信号(DIF>DEA)
-            // 2. MACD柱状图为正(确认多头力量)
-            // 3. 价格在30日MA之上且有一定偏离(避免假突破)
-            // 4. RSI处于合理区间(40-65),避免在超买区域入场
-            // 5. 波动率适中(>0.5%且<5%),避免极端波动环境
-            boolean macdBull = currentDif.compareTo(currentDea) > 0;
-            boolean macdBarPositive = macdBar.compareTo(BigDecimal.ZERO) > 0;
-            BigDecimal priceMaDiff = lastPrice.subtract(currentMa30);
-            boolean priceAboveMAWithStrength = priceMaDiff.compareTo(currentMa30.multiply(new BigDecimal("0.005"))) > 0;
-            boolean rsiInRange = currentRsi.compareTo(new BigDecimal(40)) > 0 && currentRsi.compareTo(new BigDecimal(65)) < 0;
-            boolean volatilityModerate = currentVolatility.compareTo(new BigDecimal("0.005")) > 0 && 
-                                         currentVolatility.compareTo(new BigDecimal("0.05")) < 0;
-            
-            if (macdBull && macdBarPositive && priceAboveMAWithStrength && rsiInRange && volatilityModerate) {
-                enterLong();
-            }
-        } else {
-            // 熊市入场条件增强:
-            // 1. MACD空头信号(DIF<DEA)
-            // 2. MACD柱状图为负(确认空头力量)
-            // 3. 价格在30日MA之下且有一定偏离(避免假突破)
-            // 4. RSI处于合理区间(35-60),避免在超卖区域入场
-            // 5. 波动率适中(>0.5%且<5%),避免极端波动环境
-            boolean macdBear = currentDif.compareTo(currentDea) < 0;
-            boolean macdBarNegative = macdBar.compareTo(BigDecimal.ZERO) < 0;
-            BigDecimal priceMaDiff = currentMa30.subtract(lastPrice);
-            boolean priceBelowMAWithStrength = priceMaDiff.compareTo(currentMa30.multiply(new BigDecimal("0.005"))) > 0;
-            boolean rsiInRange = currentRsi.compareTo(new BigDecimal(35)) > 0 && currentRsi.compareTo(new BigDecimal(60)) < 0;
-            boolean volatilityModerate = currentVolatility.compareTo(new BigDecimal("0.005")) > 0 && 
-                                         currentVolatility.compareTo(new BigDecimal("0.05")) < 0;
-            
-            if (macdBear && macdBarNegative && priceBelowMAWithStrength && rsiInRange && volatilityModerate) {
-                enterShort();
-            }
-        }
-    }
-
-    /**
-     * 检查是否满足离场信号条件
-     */
-    private void checkExitSignal() {
-        BigDecimal currentMa30 = ma30.getMa(); // 获取当前30日移动平均线
-
-        // 获取MACD的最新值用于判断动量变化
-        BigDecimal currentDif = macd.getDif();
-        BigDecimal currentDea = macd.getDea();
-
-        if (position == PositionStatus.LONG) {
-            // 多头持仓离场条件:
-            // 1. MACD转为空头信号(DIF<DEA)
-            // 2. 价格跌破30日MA
-            // 3. 价格触及止损价格
-            // 4. 价格触及止盈价格
-            boolean macdExit = currentDif.compareTo(currentDea) < 0;
-            boolean priceExit = lastPrice.compareTo(currentMa30) < 0;
-            boolean stopLossExit = lastPrice.compareTo(stopLossPrice) <= 0;
-            boolean takeProfitExit = lastPrice.compareTo(takeProfitPrice) >= 0;
-            
-            if (macdExit || priceExit || stopLossExit || takeProfitExit) {
-                if (stopLossExit) {
-                    System.out.println("触发止损 - ");
-                } else if (takeProfitExit) {
-                    System.out.println("触发止盈 - ");
-                }
-                exitPosition();
-            }
-        } else {
-            // 空头持仓离场条件:
-            // 1. MACD转为多头信号(DIF>DEA)
-            // 2. 价格突破30日MA
-            // 3. 价格触及止损价格
-            // 4. 价格触及止盈价格
-            boolean macdExit = currentDif.compareTo(currentDea) > 0;
-            boolean priceExit = lastPrice.compareTo(currentMa30) > 0;
-            boolean stopLossExit = lastPrice.compareTo(stopLossPrice) >= 0;
-            boolean takeProfitExit = lastPrice.compareTo(takeProfitPrice) <= 0;
-            
-            if (macdExit || priceExit || stopLossExit || takeProfitExit) {
-                if (stopLossExit) {
-                    System.out.println("触发止损 - ");
-                } else if (takeProfitExit) {
-                    System.out.println("触发止盈 - ");
-                }
-                exitPosition();
-            }
-        }
-    }
-
-    /**
-     * 计算基于风险的仓位大小
+     * 空头平仓条件检查
      * 
-     * @return 计算得到的仓位大小(ETH数量)
+     * @param macdResult MACD计算结果
+     * @param currentPrice 当前价格
+     * @return 是否满足空头平仓条件
      */
-    private BigDecimal calculatePositionSize() {
-        // 计算每次交易可承受的最大风险金额
-        BigDecimal maxRiskAmount = accountBalance.multiply(riskPerTrade);
-        // 计算单合约风险金额(价格波动 * 数量)
-        BigDecimal priceRisk = entryPrice.subtract(stopLossPrice).abs();
-        // 计算基础仓位大小(不考虑杠杆)
-        BigDecimal basePositionSize = maxRiskAmount.divide(priceRisk, 6, BigDecimal.ROUND_HALF_UP);
-        // 应用杠杆计算实际仓位大小
-        BigDecimal leveragedPositionSize = basePositionSize.multiply(new BigDecimal(leverage))
-                                                           .setScale(4, BigDecimal.ROUND_DOWN);
-        return leveragedPositionSize;
-    }
-
-    /**
-     * 执行开多仓操作
-     */
-    private void enterLong() {
-        position = PositionStatus.LONG; // 更新持仓状态为多头
-        entryPrice = lastPrice; // 记录入场价格
-        // 多头止损价格 = 入场价格 * (1 - 止损比例)
-        stopLossPrice = entryPrice.multiply(BigDecimal.ONE.subtract(stopLossRatio))
-                                  .setScale(2, BigDecimal.ROUND_HALF_UP);
-        // 多头止盈价格 = 入场价格 * (1 + 止盈比例)
-        takeProfitPrice = entryPrice.multiply(BigDecimal.ONE.add(takeProfitRatio))
-                                    .setScale(2, BigDecimal.ROUND_HALF_UP);
-        
-        // 计算仓位大小
-        positionSize = calculatePositionSize();
-        // 计算已用保证金(不考虑手续费)
-        usedMargin = positionSize.multiply(entryPrice).divide(new BigDecimal(leverage), 2, BigDecimal.ROUND_HALF_UP);
-        
-        // 实际交易中,这里会执行买入操作
-        System.out.println("开多仓 @ " + lastPrice + ", 止损价格: " + stopLossPrice + ", 止盈价格: " + takeProfitPrice);
-        System.out.println("仓位大小: " + positionSize + " ETH, 已用保证金: " + usedMargin + " USD, 账户余额: " + accountBalance + " USD");
-    }
-
-    /**
-     * 执行开空仓操作
-     */
-    private void enterShort() {
-        position = PositionStatus.SHORT; // 更新持仓状态为空头
-        entryPrice = lastPrice; // 记录入场价格
-        // 空头止损价格 = 入场价格 * (1 + 止损比例)
-        stopLossPrice = entryPrice.multiply(BigDecimal.ONE.add(stopLossRatio))
-                                  .setScale(2, BigDecimal.ROUND_HALF_UP);
-        // 空头止盈价格 = 入场价格 * (1 - 止盈比例)
-        takeProfitPrice = entryPrice.multiply(BigDecimal.ONE.subtract(takeProfitRatio))
-                                    .setScale(2, BigDecimal.ROUND_HALF_UP);
-        
-        // 计算仓位大小
-        positionSize = calculatePositionSize();
-        // 计算已用保证金(不考虑手续费)
-        usedMargin = positionSize.multiply(entryPrice).divide(new BigDecimal(leverage), 2, BigDecimal.ROUND_HALF_UP);
-        
-        // 实际交易中,这里会执行卖出操作
-        System.out.println("开空仓 @ " + lastPrice + ", 止损价格: " + stopLossPrice + ", 止盈价格: " + takeProfitPrice);
-        System.out.println("仓位大小: " + positionSize + " ETH, 已用保证金: " + usedMargin + " USD, 账户余额: " + accountBalance + " USD");
-    }
-
-    /**
-     * 执行平仓操作
-     */
-    private void exitPosition() {
-        // 计算交易盈亏
-        BigDecimal profitLoss;
-        if (position == PositionStatus.LONG) {
-            // 多头盈亏 = (平仓价格 - 入场价格) * 持仓数量
-            profitLoss = lastPrice.subtract(entryPrice).multiply(positionSize);
-        } else {
-            // 空头盈亏 = (入场价格 - 平仓价格) * 持仓数量
-            profitLoss = entryPrice.subtract(lastPrice).multiply(positionSize);
+    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;
+            }
         }
         
-        // 更新账户余额
-        accountBalance = accountBalance.add(profitLoss).setScale(2, BigDecimal.ROUND_HALF_UP);
+        return false;
+    }
+    
+    /**
+     * MACD金叉且柱状线扩张检查
+     * <p>
+     * 条件:
+     * 1. DIF线从下往上穿过DEA线(金叉)
+     * 2. MACD柱状线绝对值增大且为正值(动量增强)
+     * 
+     * @param macdResult MACD计算结果
+     * @return 是否形成MACD金叉或柱状线扩张
+     */
+    private boolean isMacdGoldenCrossAndExpanding(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);
         
-        // 实际交易中,这里会执行平仓操作
-        System.out.println("平仓 @ " + lastPrice + ", 盈亏: " + profitLoss.setScale(2, BigDecimal.ROUND_HALF_UP) + " USD");
-        System.out.println("最新账户余额: " + accountBalance + " USD");
+        // 金叉判断:DIF从下往上穿过DEA
+        boolean isGoldenCross = prevPrev.getDif().compareTo(prevPrev.getDea()) <= 0 && 
+                              previous.getDif().compareTo(previous.getDea()) > 0;
+
+        boolean isUp = latest.getDif().compareTo(BigDecimal.ZERO) > 0 && latest.getDea().compareTo(BigDecimal.ZERO) > 0;
         
-        // 重置持仓状态
-        position = PositionStatus.FLAT;
-        positionSize = BigDecimal.ZERO;
-        usedMargin = BigDecimal.ZERO;
+        // 柱状线扩张判断:连续正值且绝对值增大
+        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 && isUp;
+    }
+    
+    /**
+     * MACD柱状线扩张检查
+     * <p>
+     * 条件:当前MACD柱状线绝对值大于前一根
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否扩张
+     */
+    private boolean isExpanding(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() < 2) {
+            return false;
+        }
+
+        PriceData latest = macdData.get(macdData.size() - 1);
+        PriceData previous = macdData.get(macdData.size() - 2);
+        
+        // MACD柱状线扩张:当前绝对值大于前一根
+        return latest.getMacdHist().abs().compareTo(previous.getMacdHist().abs()) > 0;
     }
 
-    // 枚举定义
-    enum PositionStatus { FLAT, LONG, SHORT }
-    enum TrendDirection { BULLISH, BEARISH }
-}
+    /**
+     * MACD死叉且柱状线收缩检查
+     * <p>
+     * 条件:
+     * 1. DIF线从上往下穿过DEA线(死叉)
+     * 2. MACD柱状线绝对值减小且为负值(动量减弱)
+     * 
+     * @param macdResult 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 isDown  = latest.getDif().compareTo(BigDecimal.ZERO) < 0 && latest.getDea().compareTo(BigDecimal.ZERO) < 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 && isDown;
+    }
+    
+    /**
+     * MACD柱状线收缩检查
+     * <p>
+     * 条件:前一根MACD柱状线绝对值大于当前
+     * 
+     * @param macdResult MACD计算结果
+     * @return MACD柱状线是否收缩
+     */
+    private boolean isContracting(MACDResult macdResult) {
+        List<PriceData> macdData = macdResult.getMacdData();
+        if (macdData.size() < 2) {
+            return false;
+        }
+
+        PriceData latest = macdData.get(macdData.size() - 1);
+        PriceData previous = macdData.get(macdData.size() - 2);
+        
+        // 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;
+    }
+
+    /**
+     * 波动率过滤检查
+     *
+     * @param volatility 当前波动率
+     * @return 波动率是否在0.5%~5%范围内
+     */
+    private boolean isVolatilityInRange(BigDecimal volatility) {
+        BigDecimal minVolatility = new BigDecimal("0.1"); // 降低最小波动率阈值
+        BigDecimal maxVolatility = new BigDecimal("5.0");
+
+        return volatility.compareTo(minVolatility) >= 0 &&
+                volatility.compareTo(maxVolatility) <= 0;
+    }
+
+}
\ No newline at end of file

--
Gitblit v1.9.1