新版仿ok交易所-后端
1
zyy
2025-10-20 d6f1a81f8af23e55bcb2a44909efcfbf61cd34fe
1
2 files modified
377 ■■■■■ changed files
trading-order-huobi/src/main/java/com.yami.trading.huobi/data/AdjustmentValueCache.java 10 ●●●● patch | view | raw | blame | history
trading-order-huobi/src/main/java/com.yami.trading.huobi/data/job/AbstractGetDataJob.java 367 ●●●●● patch | view | raw | blame | history
trading-order-huobi/src/main/java/com.yami.trading.huobi/data/AdjustmentValueCache.java
@@ -43,25 +43,19 @@
    //记录当前分配到第几个值
    private static final Map<String, Integer> currentAllocationIndex = new ConcurrentHashMap<>();
    //记录前一个值的波动方向
    private static final Map<String, List<Boolean>> upDownTrend = new ConcurrentHashMap<>();
    public static Map<String, Integer> getFrequency() {
        return frequency;
    }
    public static Map<String, List<BigDecimal>> getPreAllocationList() {
    public static Map<String, List<BigDecimal>> getPreAllocatedAdjustments() {
        return preAllocationList;
    }
    public static Map<String, Integer> getCurrentAllocationIndex() {
    public static Map<String, Integer> getCurrentAdjustmentIndex() {
        return currentAllocationIndex;
    }
    public static Map<String, List<Boolean>> getUpDownTrend() {
        return upDownTrend;
    }
trading-order-huobi/src/main/java/com.yami.trading.huobi/data/job/AbstractGetDataJob.java
@@ -19,7 +19,6 @@
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public abstract class AbstractGetDataJob implements Runnable {
@@ -46,8 +45,6 @@
    public abstract String getName();
    // 在类中定义静态Random实例
    private static final Random random = new Random();
    public abstract void realtimeHandle(String symbols);
@@ -56,175 +53,60 @@
            try {
                String symbol = realtime.getSymbol();
                Integer decimal = itemService.getDecimal(symbol); // 虚拟币通常8位小数,需保留足够精度
                Integer decimal = itemService.getDecimal(symbol);
                Item item = this.itemService.findBySymbol(symbol);
                BigDecimal currentValue = AdjustmentValueCache.getCurrentValue().get(symbol);
                AdjustmentValue delayValue = AdjustmentValueCache.getDelayValue().get(symbol);
                if (delayValue != null) {
                    if (delayValue.getValue().compareTo(BigDecimal.ZERO) == 0 || delayValue.getSecond() <= 0) {
                        cleanUpKLineCache(symbol); // 清理缓存,跳过后续计算
                    if (delayValue.getSecond() < 0) {
                        AdjustmentValueCache.getDelayValue().remove(symbol);
                        AdjustmentValueCache.getPreAllocatedAdjustments().remove(symbol);
                        AdjustmentValueCache.getCurrentAdjustmentIndex().remove(symbol);
                        return;
                    }
                    // K线场景专属参数(可根据周期动态调整)
                    double baseFluctuation = 0.1;
                    int trendConsistencyRate = 70; // 70%概率保持与前一个值的波动方向一致(模拟趋势)
                    int maxAdjacentFluctuation = 5; // 相邻值波动不超过前一个值的5%(避免视觉跳变)
                    int frequency = (int) Arith.div(Arith.mul(delayValue.getSecond(), 1000.0D), this.interval);
                    List<BigDecimal> adjustments = AdjustmentValueCache.getPreAllocatedAdjustments().get(symbol);
                    Integer currentIndex = AdjustmentValueCache.getCurrentAdjustmentIndex().get(symbol);
                    Integer frequency = AdjustmentValueCache.getFrequency().get(symbol);
                    List<BigDecimal> preAllocationList = AdjustmentValueCache.getPreAllocationList().get(symbol);
                    Integer currentIndex = AdjustmentValueCache.getCurrentAllocationIndex().get(symbol);
                    List<Boolean> upDownTrend = AdjustmentValueCache.getUpDownTrend().getOrDefault(symbol, new ArrayList<>());
                    if (frequency == null) {
                        frequency = (int) Arith.div(Arith.mul(delayValue.getSecond(), 1000.0D), this.interval);
                        AdjustmentValueCache.getFrequency().put(symbol, frequency);
                        if (frequency > 1) {
                            preAllocationList = new ArrayList<>(frequency);
                            BigDecimal totalValue = delayValue.getValue(); // 支持正负值
                            // 核心修改1:用绝对值算平均值(避免负数波动范围反向),最后补回原符号
                            BigDecimal totalAbs = totalValue.abs();
                            BigDecimal averageAbs = totalAbs.divide(new BigDecimal(frequency), decimal + 4, RoundingMode.HALF_UP);
                            BigDecimal average = averageAbs.multiply(totalValue.signum() == 1 ? BigDecimal.ONE : BigDecimal.ONE.negate());
                            BigDecimal sum = BigDecimal.ZERO;
                            // 优化1:最后k个值分散偏差(k=频率的2%,最少5个,确保最后一根K线无异常)
                            int lastK = Math.max(5, frequency / 50);
                            int normalCount = frequency - lastK;
                            // 优化2:前n-k个值——模拟真实行情波动(兼容正负)
                            for (int i = 0; i < normalCount; i++) {
                                BigDecimal randomValue;
                                if (i == 0) {
                                    // 第一个值:基于带符号平均值波动,保留原符号
                                    randomValue = generateTruncatedGaussianValue(average, baseFluctuation, decimal + 4);
                                } else {
                                    boolean lastUp = upDownTrend.get(i - 1);
                                    boolean keepTrend = Math.random() * 100 <= trendConsistencyRate;
                                    if (keepTrend) {
                                        // 核心修改2:按前值绝对值算波动幅度,避免负数趋势误判
                                        BigDecimal lastVal = preAllocationList.get(i - 1);
                                        double fluctRange = lastVal.abs().multiply(new BigDecimal(baseFluctuation * 1.2)).doubleValue();
                                        if (lastUp) {
                                            // 前一个上涨(无论正负,比前值大即为涨):波动范围[0, fluctRange]
                                            randomValue = generateDirectionalValue(lastVal, 0.0, fluctRange, decimal + 4);
                                        } else {
                                            // 前一个下跌(比前值小即为跌):波动范围[-fluctRange, 0]
                                            randomValue = generateDirectionalValue(lastVal, -fluctRange, 0.0, decimal + 4);
                                        }
                                    } else {
                                        // 反转趋势:基于带符号平均值波动
                                        randomValue = generateTruncatedGaussianValue(average, baseFluctuation, decimal + 4);
                                    }
                                    // 核心修改3:相邻波动约束——用前值绝对值算最大波动,超限时按符号截断
                                    BigDecimal lastValue = preAllocationList.get(i - 1);
                                    BigDecimal maxAdjacent = lastValue.abs()
                                            .multiply(new BigDecimal(maxAdjacentFluctuation / 100.0))
                                            .setScale(decimal + 4, RoundingMode.HALF_UP);
                                    BigDecimal adjacentDiff = randomValue.subtract(lastValue);
                                    if (adjacentDiff.abs().compareTo(maxAdjacent) > 0) {
                                        randomValue = lastValue.add(
                                                adjacentDiff.signum() == 1 ? maxAdjacent : maxAdjacent.negate()
                                        );
                                    }
                                }
                                preAllocationList.add(randomValue);
                                sum = sum.add(randomValue);
                                // 核心修改4:涨跌趋势改为“与前值对比”(而非平均值),兼容正负
                                boolean currentUp = (i == 0)
                                        ? randomValue.compareTo(average) > 0
                                        : randomValue.compareTo(preAllocationList.get(i - 1)) > 0;
                                upDownTrend.add(currentUp);
                            }
                            // 优化4:最后k个值——兼容负数总和
                            BigDecimal remaining = totalValue.subtract(sum);
                            // 用剩余值绝对值算平均,补回符号
                            BigDecimal remainingAbs = remaining.abs();
                            BigDecimal avgLastKAbs = remainingAbs.divide(new BigDecimal(lastK), decimal + 4, RoundingMode.HALF_UP);
                            BigDecimal avgLastK = avgLastKAbs.multiply(remaining.signum() == 1 ? BigDecimal.ONE : BigDecimal.ONE.negate());
                            for (int i = 0; i < lastK - 1; i++) {
                                BigDecimal smallFluctValue = generateTruncatedGaussianValue(avgLastK, baseFluctuation / 3, decimal + 4);
                                preAllocationList.add(smallFluctValue);
                                sum = sum.add(smallFluctValue);
                                upDownTrend.add(smallFluctValue.compareTo(preAllocationList.get(preAllocationList.size() - 2)) > 0);
                            }
                            // 最后1个值:兼容负数偏差
                            BigDecimal finalValue = totalValue.subtract(sum);
                            BigDecimal maxFinalFluct = avgLastK.abs()
                                    .multiply(new BigDecimal(baseFluctuation / 5))
                                    .setScale(decimal + 4, RoundingMode.HALF_UP);
                            if (finalValue.abs().compareTo(maxFinalFluct) > 0) {
                                // 超限时按符号截断,保留原方向
                                finalValue = maxFinalFluct.multiply(finalValue.signum() == 1 ? BigDecimal.ONE : BigDecimal.ONE.negate());
                                BigDecimal prevLastValue = preAllocationList.get(preAllocationList.size() - 1);
                                preAllocationList.set(preAllocationList.size() - 1, prevLastValue.add(totalValue.subtract(sum).subtract(finalValue)));
                            }
                            preAllocationList.add(finalValue);
                            upDownTrend.add(finalValue.compareTo(preAllocationList.get(preAllocationList.size() - 2)) > 0);
                            // 缓存更新
                            AdjustmentValueCache.getPreAllocationList().put(symbol, preAllocationList);
                            AdjustmentValueCache.getCurrentAllocationIndex().put(symbol, 0);
                            AdjustmentValueCache.getUpDownTrend().put(symbol, upDownTrend);
                            currentIndex = 0;
                        }
                    // 首次执行:生成含正负值的调整序列
                    if (adjustments == null || currentIndex == null) {
                        adjustments = generateRandomAdjustments(delayValue.getValue(), frequency, decimal);
                        currentIndex = 0;
                        AdjustmentValueCache.getPreAllocatedAdjustments().put(symbol, adjustments);
                        AdjustmentValueCache.getCurrentAdjustmentIndex().put(symbol, currentIndex);
                    }
                    // 后续分配逻辑:兼容正负延时值
                    if (frequency <= 1) {
                        // 单次分配:直接用带符号值,避免符号丢失
                        BigDecimal delayVal = delayValue.getValue().setScale(decimal, RoundingMode.HALF_UP);
                    // 分步应用调整值(确保正负交替)
                    if (currentIndex < frequency) {
                        BigDecimal currentAdjust = adjustments.get(currentIndex);
                        // 更新当前值(累加正负调整值)
                        if (currentValue == null) {
                            AdjustmentValueCache.getCurrentValue().put(symbol, delayVal);
                            AdjustmentValueCache.getCurrentValue().put(symbol, currentAdjust.setScale(decimal, RoundingMode.HALF_UP));
                        } else {
                            AdjustmentValueCache.getCurrentValue().put(symbol, currentValue.add(delayVal).setScale(decimal, RoundingMode.HALF_UP));
                            AdjustmentValueCache.getCurrentValue().put(symbol, currentValue.add(currentAdjust).setScale(decimal, RoundingMode.HALF_UP));
                        }
                        if (!item.getAdjustmentValue().equals(AdjustmentValueCache.getCurrentValue().get(symbol))) {
                            item.setAdjustmentValue(AdjustmentValueCache.getCurrentValue().get(symbol));
                        // 更新延时值(剩余值和时间)
                        delayValue.setValue(delayValue.getValue().subtract(currentAdjust).setScale(decimal, RoundingMode.HALF_UP));
                        delayValue.setSecond(Arith.sub(delayValue.getSecond(), Arith.div(this.interval, 1000.0D)));
                        AdjustmentValueCache.getDelayValue().put(symbol, delayValue);
                        // 索引递增,完成后清理缓存
                        int nextIndex = currentIndex + 1;
                        AdjustmentValueCache.getCurrentAdjustmentIndex().put(symbol, nextIndex);
                        if (nextIndex >= frequency) {
                            AdjustmentValueCache.getDelayValue().remove(symbol);
                            AdjustmentValueCache.getPreAllocatedAdjustments().remove(symbol);
                            AdjustmentValueCache.getCurrentAdjustmentIndex().remove(symbol);
                        }
                        // 持久化更新
                        BigDecimal newAdjustValue = AdjustmentValueCache.getCurrentValue().get(symbol);
                        if (!item.getAdjustmentValue().equals(newAdjustValue)) {
                            item.setAdjustmentValue(newAdjustValue);
                            itemService.saveOrUpdate(item);
                        }
                        cleanUpKLineCache(symbol);
                    } else {
                        // 按预分配列表取值(列表已兼容正负)
                        if (preAllocationList != null && currentIndex != null && currentIndex < preAllocationList.size()) {
                            BigDecimal currentValueFrequency = preAllocationList.get(currentIndex).setScale(decimal, RoundingMode.HALF_UP);
                            // 更新当前值:带符号累加
                            if (currentValue == null) {
                                AdjustmentValueCache.getCurrentValue().put(symbol, currentValueFrequency);
                            } else {
                                AdjustmentValueCache.getCurrentValue().put(symbol, currentValue.add(currentValueFrequency).setScale(decimal, RoundingMode.HALF_UP));
                            }
                            // 更新延迟值:带符号减法
                            BigDecimal updatedDelayVal = delayValue.getValue().subtract(currentValueFrequency).setScale(decimal, RoundingMode.HALF_UP);
                            delayValue.setValue(updatedDelayVal);
                            delayValue.setSecond(Arith.sub(delayValue.getSecond(), Arith.div(this.interval, 1000.0D)));
                            AdjustmentValueCache.getDelayValue().put(symbol, delayValue);
                            int nextIndex = currentIndex + 1;
                            AdjustmentValueCache.getCurrentAllocationIndex().put(symbol, nextIndex);
                            if (nextIndex >= frequency) {
                                cleanUpKLineCache(symbol);
                            }
                            if (!item.getAdjustmentValue().equals(AdjustmentValueCache.getCurrentValue().get(symbol))) {
                                item.setAdjustmentValue(AdjustmentValueCache.getCurrentValue().get(symbol));
                                itemService.saveOrUpdate(item);
                            }
                        }
                    }
                }
@@ -288,54 +170,133 @@
    }
    private List<BigDecimal> generateRandomAdjustments(BigDecimal totalValue, int count, int decimal) {
        List<BigDecimal> adjustments = new ArrayList<>(count);
        BigDecimal sum = BigDecimal.ZERO; // 整体累积和
        boolean isOverallUp = totalValue.signum() > 0; // 整体大趋势
    // ------------------------------ 工具方法 ------------------------------
    /**
     * 生成截断正态分布值(限制在平均值±fluctuation范围内,模拟真实小波动)
     */
    private BigDecimal generateTruncatedGaussianValue(BigDecimal average, double fluctuation, int scale) {
        double factor = nextGaussian() * 0.25; // 标准差0.25,99.7%概率在±0.75内(更集中)
        factor = Math.max(-1.0, Math.min(1.0, factor)); // 截断极端值
        BigDecimal fluctuationValue = average.multiply(new BigDecimal(factor * fluctuation))
                .setScale(scale, RoundingMode.HALF_UP);
        return average.add(fluctuationValue);
        // 1. 大幅扩大基础波动幅度(比之前再提高30%+,确保单次波动更剧烈)
        BigDecimal baseFluct = totalValue.abs().multiply(new BigDecimal(isOverallUp ? 0.25 : 0.22)) // 上涨时25%,下跌时22%
                .max(new BigDecimal("0.001")); // 最小波动阈值提高到0.001,避免微小波动
        // 2. 极大放宽累积范围(允许更大中途偏离,给子周期正负波动留空间)
        BigDecimal minPreSum = totalValue.multiply(new BigDecimal("0.5")); // 整体最低允许50%
        BigDecimal maxPreSum = totalValue.multiply(new BigDecimal("1.5")); // 整体最高允许150%
        // 3. 几乎取消“不动”状态(概率1%,突出剧烈波动)
        double flatProbability = 0.01;
        // 4. 子周期配置:每20次为一个子周期,每个子周期随机生成正负趋势
        int subCycleLength = 20; // 子周期长度
        Boolean currentSubCycleUp = null; // 当前子周期的趋势(null表示未初始化)
        BigDecimal subSum = BigDecimal.ZERO; // 当前子周期的累积和
        for (int i = 0; i < count - 1; i++) {
            // 每进入新的子周期(i为0或20的倍数),随机初始化子周期趋势(50%正,50%负)
            if (i % subCycleLength == 0) {
                currentSubCycleUp = Math.random() < 0.5; // 子周期趋势随机正负
                subSum = BigDecimal.ZERO; // 重置子周期累积和
            }
            // 计算当前允许的累积总和范围(动态适配剩余步数)
            BigDecimal remainingCount = new BigDecimal(count - 1 - i);
            BigDecimal minCurrentSum = sum.add(minPreSum.subtract(sum).divide(remainingCount, decimal + 4, RoundingMode.HALF_UP));
            BigDecimal maxCurrentSum = sum.add(maxPreSum.subtract(sum).divide(remainingCount, decimal + 4, RoundingMode.HALF_UP));
            // 极低概率“不动”
            boolean isFlat = Math.random() < flatProbability;
            if (isFlat) {
                BigDecimal adjustment = BigDecimal.ZERO.setScale(decimal, RoundingMode.HALF_UP);
                adjustments.add(adjustment);
                sum = sum.add(adjustment);
                subSum = subSum.add(adjustment); // 累加子周期和
                continue;
            }
            // 5. 动态调整涨跌概率:优先满足“子周期正负交替”,再适配整体趋势
            double upProbability;
            // 子周期内:若子周期趋势为正,80%概率涨;为负,80%概率跌(确保子周期总和有明确正负)
            if (currentSubCycleUp) {
                upProbability = 0.8;
            } else {
                upProbability = 0.2;
            }
            // 二次修正:若子周期累积和已偏离目标(如子周期应为正但当前为负),进一步提高对应概率
            if (currentSubCycleUp && subSum.compareTo(BigDecimal.ZERO) < 0) {
                upProbability = Math.min(0.98, upProbability + 0.2); // 子周期需正但当前负,大幅提高涨概率
            } else if (!currentSubCycleUp && subSum.compareTo(BigDecimal.ZERO) > 0) {
                upProbability = Math.max(0.02, upProbability - 0.2); // 子周期需负但当前正,大幅提高跌概率
            }
            // 三次修正:确保整体累积和不偏离太远(弱于子周期优先级)
            if (sum.compareTo(minPreSum) < 0) {
                upProbability = Math.min(0.98, upProbability + 0.1);
            } else if (sum.compareTo(maxPreSum) > 0) {
                upProbability = Math.max(0.02, upProbability - 0.1);
            }
            boolean isCurrentUp = Math.random() < upProbability;
            // 6. 生成超大随机幅度(0.6~1.2倍baseFluct,跳过中小幅度,直接用大波动)
            double randomRate = 0.6 + Math.random() * 0.6; // 范围:0.6~1.2(确保单次波动至少是baseFluct的60%)
            BigDecimal fluct = baseFluct.multiply(new BigDecimal(randomRate))
                    .setScale(decimal + 4, RoundingMode.HALF_UP);
            // 7. 生成当前调整值(允许接近上限的剧烈波动)
            BigDecimal adjustment;
            if (isCurrentUp) {
                adjustment = fluct.setScale(decimal, RoundingMode.HALF_UP);
                // 超上限时仅截断到上限(不额外缩小,保留大涨幅)
                if (sum.add(adjustment).compareTo(maxCurrentSum) > 0) {
                    adjustment = maxCurrentSum.subtract(sum).setScale(decimal, RoundingMode.HALF_UP);
                }
            } else {
                adjustment = fluct.negate().setScale(decimal, RoundingMode.HALF_UP);
                // 低于下限时仅截断到下限(保留大跌幅)
                if (sum.add(adjustment).compareTo(minCurrentSum) < 0) {
                    adjustment = minCurrentSum.subtract(sum).setScale(decimal, RoundingMode.HALF_UP);
                }
            }
            adjustments.add(adjustment);
            sum = sum.add(adjustment);
            subSum = subSum.add(adjustment); // 累加子周期和
        }
        // 8. 最后一个值:允许极大补平幅度(不超过baseFluct的8倍,适配剧烈波动后的差额)
        BigDecimal lastAdjustment = totalValue.subtract(sum)
                .setScale(decimal, RoundingMode.HALF_UP);
        BigDecimal maxLastAdjust = baseFluct.multiply(new BigDecimal(8)); // 从5倍提高到8倍
        if (lastAdjustment.abs().compareTo(maxLastAdjust) > 0) {
            lastAdjustment = maxLastAdjust.multiply(lastAdjustment.signum() == 1 ? BigDecimal.ONE : BigDecimal.ONE.negate());
            // 微调前一个值分担差额(确保总和准确)
            BigDecimal prevAdjust = adjustments.get(adjustments.size() - 1);
            adjustments.set(adjustments.size() - 1, prevAdjust.add(totalValue.subtract(sum).subtract(lastAdjustment)));
        }
        adjustments.add(lastAdjustment);
        return adjustments;
    }
    /**
     * 生成指定方向的波动值(如[0, +0.1]表示只涨不跌)
     */
    private BigDecimal generateDirectionalValue(BigDecimal average, double minFactor, double maxFactor, int scale) {
        double factor = minFactor + Math.random() * (maxFactor - minFactor);
        BigDecimal fluctuationValue = average.multiply(new BigDecimal(factor))
                .setScale(scale, RoundingMode.HALF_UP);
        return average.add(fluctuationValue);
    public static void main(String[] args) {
        AbstractGetDataJob abstractGetDataJob = new CryptosGetDataJob();
        List<BigDecimal> list = abstractGetDataJob.generateRandomAdjustments(new BigDecimal(0.002), 300, 8);
        BigDecimal sum = BigDecimal.ZERO;
        int num = 0;
        int dmt = 1;
        BigDecimal numd = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            sum = sum.add(list.get(i));
            System.out.println((i+1) + "~                      " + list.get(i));
            System.out.println(sum);
            numd = numd.add(list.get(i));
            num++;
            if (num == 20) {
                System.out.println(dmt+"ddd" + numd);
                dmt++;
                num=0;
                numd=BigDecimal.ZERO;
            }
        }
    }
    /**
     * K线场景专属缓存清理(含波动方向列表)
     */
    private void cleanUpKLineCache(String symbol) {
        AdjustmentValueCache.getDelayValue().remove(symbol);
        AdjustmentValueCache.getFrequency().remove(symbol);
        AdjustmentValueCache.getPreAllocationList().remove(symbol);
        AdjustmentValueCache.getCurrentAllocationIndex().remove(symbol);
        AdjustmentValueCache.getUpDownTrend().remove(symbol); // 新增:清理波动方向缓存
    }
    /**
     * 获取K线周期(根据symbol或配置判断,示例返回1=1min,5=5min等)
     */
    private int getKLineCycle(String symbol) {
        // 实际场景可从配置或symbol后缀获取(如BTC-USDT-1MIN → 1)
        return 1;
    }
    /**
     * 正态分布随机数生成(均值0,标准差1)
     */
    private static double nextGaussian() {
        double u1 = Math.random();
        double u2 = Math.random();
        return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
    }
}