From 830dd7a3c9c496348b5434f881913d6bca01ba3b Mon Sep 17 00:00:00 2001
From: Administrator <15274802129@163.com>
Date: Wed, 17 Dec 2025 09:57:19 +0800
Subject: [PATCH] refactor(okx): 调整账户与仓位初始化逻辑

---
 src/main/java/com/xcong/excoin/modules/okxNewPrice/celue/CaoZuoServiceImpl.java |  518 +++++++++++++++++++++++++++++++++++++++------------------
 1 files changed, 351 insertions(+), 167 deletions(-)

diff --git a/src/main/java/com/xcong/excoin/modules/okxNewPrice/celue/CaoZuoServiceImpl.java b/src/main/java/com/xcong/excoin/modules/okxNewPrice/celue/CaoZuoServiceImpl.java
index a4a8a4a..fe1037b 100644
--- a/src/main/java/com/xcong/excoin/modules/okxNewPrice/celue/CaoZuoServiceImpl.java
+++ b/src/main/java/com/xcong/excoin/modules/okxNewPrice/celue/CaoZuoServiceImpl.java
@@ -1,12 +1,11 @@
 package com.xcong.excoin.modules.okxNewPrice.celue;
 
+import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.core.util.StrUtil;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.AccountWs;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.InstrumentsWs;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.PositionsWs;
-import com.xcong.excoin.modules.okxNewPrice.okxWs.TradeOrderWs;
+import com.xcong.excoin.modules.okxNewPrice.okxWs.*;
 import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.CoinEnums;
 import com.xcong.excoin.modules.okxNewPrice.okxWs.enums.OrderParamEnums;
+import com.xcong.excoin.modules.okxNewPrice.utils.WsMapBuild;
 import com.xcong.excoin.modules.okxNewPrice.wangge.WangGeQueue;
 import com.xcong.excoin.modules.okxNewPrice.wangge.WangGeService;
 import com.xcong.excoin.rabbit.pricequeue.AscBigDecimal;
@@ -17,6 +16,7 @@
 import org.springframework.stereotype.Service;
 
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.util.concurrent.PriorityBlockingQueue;
 
 /**
@@ -30,94 +30,107 @@
 @RequiredArgsConstructor
 public class CaoZuoServiceImpl implements CaoZuoService {
 
-    private final RedisUtils redisUtils;
     private final WangGeService wangGeService;
-
-
-    // 构造Redis键名
-    final String coinCode = CoinEnums.HE_YUE.getCode();
-    final String instrumentsStateKey = InstrumentsWs.INSTRUMENTSWS_CHANNEL + ":" + coinCode + ":state";
-    final String instrumentsOutKey = InstrumentsWs.INSTRUMENTSWS_CHANNEL+":" + coinCode+":out";
-    final String positionsMarkPxKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":markPx";
-    final String positionsAvgPxKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":avgPx";
-    final String positionsOrderPriceKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":orderPrice";
-    final String positionsUplKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":upl";
-    final String positionsRealizedPnlKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":realizedPnl";
-    final String positionsImrKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":imr";
-    final String positionsPosKey = PositionsWs.POSITIONSWS_CHANNEL + ":" + coinCode + ":pos";
 
     /**
      * 执行主要的操作逻辑,包括读取合约状态、获取市场价格信息,
      * 并根据当前持仓均价和标记价格决定是否执行买卖操作。
      *
-     * @return 返回操作类型字符串(如买入BUY、卖出SELL等)
+     * @return 返回操作类型字符串(如买入BUY、卖出SELL等),如果无有效操作则返回null
      */
     @Override
-    public String caoZuo() {
-        log.info("开始执行操作CaoZuoServiceImpl......");
-
-        // 获取合约执行操作状态
-        String state = (String) redisUtils.get(instrumentsStateKey);
-        String outStr = (String) redisUtils.get(instrumentsOutKey);
-        if (OrderParamEnums.OUT_YES.getValue().equals(outStr) && OrderParamEnums.STATE_3.getValue().equals(state)){
-            log.error("止损过了......冷静一下,等待下次入场......");
+    public String caoZuo(String accountName) {
+        String posSide = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.POSSIDE.name());
+        if (CoinEnums.POSSIDE_LONG.getCode().equals(posSide)){
+            return caoZuoLong(accountName);
+        }else if (CoinEnums.POSSIDE_SHORT.getCode().equals(posSide)){
+            return caoZuoShort(accountName);
+        }else{
+            log.error("账户未设置持仓方向......");
             return null;
         }
-        if (OrderParamEnums.STATE_4.getValue().equals(state)) {
-            log.error("操作下单中,等待......");
-            return OrderParamEnums.ORDERING.getValue();
-        }
-        if (OrderParamEnums.STATE_3.getValue().equals(state)){
-            log.error("持仓盈亏超过下单总保证金,冷静止损......");
-            redisUtils.set(instrumentsOutKey, OrderParamEnums.OUT_YES.getValue(), 0);
-            return OrderParamEnums.OUT.getValue();
-        }
-        if (OrderParamEnums.STATE_2.getValue().equals(state)){
-            log.error("持仓盈亏抗压......");
-            return OrderParamEnums.HOLDING.getValue();
-        }
-        if (OrderParamEnums.STATE_0.getValue().equals(state)){
-            log.error("请检查系统参数,不允许开仓......");
-            return OrderParamEnums.HOLDING.getValue();
-        }
+    }
 
-        String pos = (String) redisUtils.get(positionsPosKey);
-        if (StrUtil.isBlank(pos) || BigDecimal.ZERO.compareTo( new BigDecimal(pos)) >= 0) {
-            log.error("未获取到持仓数量");
-            return OrderParamEnums.INIT.getValue();
+    @Override
+    public String caoZuoLong(String accountName) {
+        log.info("开始看涨执行操作CaoZuoServiceImpl......");
+        String accountReadyState = AccountWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name());
+        if (!CoinEnums.READY_STATE_YES.getCode().equals(accountReadyState)) {
+            log.info("账户通道未就绪,取消发送");
+            return null;
         }
+        BigDecimal positionsReadyState = PositionsWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name()) == null
+                ? BigDecimal.ZERO : PositionsWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name());
+        if (WsMapBuild.parseBigDecimalSafe(CoinEnums.READY_STATE_YES.getCode()).compareTo(positionsReadyState) != 0) {
+            log.info("仓位通道未就绪,取消发送");
+            return null;
+        }
+        // 系统设置的开关,等于冷静中,则代表不开仓
+        String outStr = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.OUT.name());
+        if (OrderParamEnums.OUT_YES.getValue().equals(outStr)){
+            log.error("冷静中,不允许下单......");
+            return null;
+        }
+        BigDecimal cashBal = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get("cashBal"));
 
-        String uplStr = (String) redisUtils.get(positionsUplKey);
-        if (StrUtil.isBlank(uplStr)){
-            return OrderParamEnums.INIT.getValue();
+        // 判断账户余额是否充足
+        if (cashBal.compareTo(BigDecimal.ZERO) <= 0){
+            log.error("账户没有钱,请充值......");
+            return null;
         }
-        //可使用的总保证金
-        String cashBalStrKey = AccountWs.ACCOUNTWS_CHANNEL + ":" + CoinEnums.USDT.getCode() + ":cashBalStr";
-        String cashBalStr = (String) redisUtils.get(cashBalStrKey);
-        BigDecimal upl = new BigDecimal(uplStr);
-        if (BigDecimal.ZERO.compareTo(upl) >= 0){
-            upl = upl.multiply(new BigDecimal("-1"));
-            BigDecimal bigDecimal = new BigDecimal(cashBalStr).multiply(new BigDecimal(OrderParamEnums.ZHI_SUN.getValue()));
-            if (upl.compareTo(bigDecimal) >= 0) {
-                log.error("持仓盈亏超过下单总保证金,止损冷静一天......");
+        /**
+         * 判断止损抗压
+         */
+        // 实际亏损金额
+        BigDecimal realKuiSunAmount = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get("upl"));
+        log.info("未实现盈亏: {}", realKuiSunAmount);
+        String zhiSunPercent = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.ZHI_SUN.name());
+        BigDecimal zhiSunAmount = cashBal.multiply(new BigDecimal(zhiSunPercent));
+        log.info("预期亏损金额: {}", zhiSunAmount);
+        String kangYaPercent = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.KANG_CANG.name());
+        BigDecimal  kangYaAmount = cashBal.multiply(new BigDecimal(kangYaPercent));
+        log.info("预期抗仓金额: {}", kangYaAmount);
+
+        if (realKuiSunAmount.compareTo(BigDecimal.ZERO) < 0){
+            realKuiSunAmount = realKuiSunAmount.multiply(new BigDecimal("-1"));
+            // 账户预期亏损金额比这个还小时,立即止损
+            if (realKuiSunAmount.compareTo(zhiSunAmount) > 0){
+                log.error("账户冷静止损......");
+                WsMapBuild.saveStringToMap(InstrumentsWs.getAccountMap(accountName), CoinEnums.OUT.name(),  OrderParamEnums.OUT_YES.getValue());
                 return OrderParamEnums.OUT.getValue();
+            }
+            // 判断抗压
+            if (realKuiSunAmount.compareTo(kangYaAmount) > 0 && realKuiSunAmount.compareTo(zhiSunAmount) <= 0){
+                log.error("账户紧张扛仓......");
+                return OrderParamEnums.HOLDING.getValue();
             }
         }
 
-        log.info(OrderParamEnums.getNameByValue(state));
-
-        // 获取标记价格和平均持仓价格
-        String markPxObj = (String) redisUtils.get(positionsMarkPxKey);
-        String avgPxObj = (String) redisUtils.get(positionsAvgPxKey);
-
-        if (StrUtil.isBlank(markPxObj)  || StrUtil.isBlank(avgPxObj)) {
-            return OrderParamEnums.INIT.getValue();
+        if (PositionsWs.getAccountMap(accountName).get("pos") == null){
+            log.error("没有获取到持仓信息,等待初始化......");
+            return null;
+        }
+        BigDecimal pos = PositionsWs.getAccountMap(accountName).get("pos");
+        if (BigDecimal.ZERO.compareTo( pos) >= 0) {
+            log.error("持仓数量为零,进行初始化订单");
+            return null;
+        }
+        // 判断是否保证金超标
+        if (PositionsWs.getAccountMap(accountName).get("imr") == null){
+            log.error("没有获取到持仓信息,等待初始化......");
+            return null;
+        }
+        BigDecimal ordFrozImr = PositionsWs.getAccountMap(accountName).get("imr");
+        BigDecimal totalOrderUsdt = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get(CoinEnums.TOTAL_ORDER_USDT.name()));
+        if (ordFrozImr.compareTo(totalOrderUsdt) >= 0){
+            log.error("已满仓......");
+            return OrderParamEnums.HOLDING.getValue();
         }
 
         try {
-            BigDecimal markPx = new BigDecimal( markPxObj);
-            BigDecimal avgPx = new BigDecimal( avgPxObj);
-
+            // 获取标记价格和平均持仓价格
+            BigDecimal markPx = PositionsWs.getAccountMap(accountName).get("markPx");
+            BigDecimal avgPx = PositionsWs.getAccountMap(accountName).get("avgPx");
             log.info("开仓价格: {}, 当前价格:{},匹配队列中......", avgPx, markPx);
 
             // 初始化网格队列
@@ -126,91 +139,74 @@
             PriorityBlockingQueue<AscBigDecimal> queuePingCang = wangGeService.initPingCang(avgPx, queueAsc);
 
             // 处理订单价格在队列中的情况
-            String orderPrice = (String) redisUtils.get(positionsOrderPriceKey);
+            String orderPrice = OrderInfoWs.getAccountMap(accountName).get("orderPrice");
             handleOrderPriceInQueues(orderPrice, queueKaiCang, queuePingCang);
-
-            String side = OrderParamEnums.HOLDING.getValue();
-
             // 判断是加仓还是减仓
             if (avgPx.compareTo(markPx) > 0) {
                 log.info("开始加仓...");
                 if (queueKaiCang.isEmpty()) {
                     // 队列为空
-                    log.info("开始加仓,但是超出了网格设置...");
-                    return side;
+//                    log.info("开始加仓,但是超出了网格设置...");
+                    return OrderParamEnums.HOLDING.getValue();
                 }
                 DescBigDecimal kaiCang = queueKaiCang.peek();
                 if (kaiCang != null && markPx.compareTo(kaiCang.getValue()) <= 0 && avgPx.compareTo(kaiCang.getValue()) >= 0) {
                     log.info("开始加仓...开仓队列价格大于当前价格{}>{}", kaiCang.getValue(), markPx);
-                    side = OrderParamEnums.BUY.getValue();
-                    redisUtils.set(positionsOrderPriceKey, String.valueOf(kaiCang.getValue()), 0);
-                } else {
-                    //判断是否加仓(当前持仓过小,可以加仓)
-                    boolean isAddCang = doAddCang();
-                    log.info("加仓过程中发现持仓过小 :{}",isAddCang);
-                    if (isAddCang){
-                        log.info("触发加仓......,持仓过小");
+                    WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                    boolean buyCntTimeFlag = buyCntTimeLongEvent(accountName, avgPx, markPx);
+                    if (buyCntTimeFlag){
+                        log.info("加仓参数准备成功......");
                         return OrderParamEnums.BUY.getValue();
+                    }else{
+                        log.error("加仓参数准备失败......");
+                        return null;
                     }
+                } else {
                     log.info("未触发加仓......,等待");
+                    return OrderParamEnums.HOLDING.getValue();
                 }
             } else if (avgPx.compareTo(markPx) < 0) {
                 log.info("开始减仓...");
                 if (queuePingCang.isEmpty()) {
                     // 队列为空
                     log.info("开始减仓,但是超出了网格设置...");
-                    return side;
+                    return OrderParamEnums.HOLDING.getValue();
                 }
                 AscBigDecimal pingCang = queuePingCang.peek();
-                if (pingCang != null && markPx.compareTo(pingCang.getValue()) >= 0 && avgPx.compareTo(pingCang.getValue()) < 0) {
-                    log.info("开始减仓...平仓队列价格小于当前价格{}<={}", pingCang.getValue(), markPx);
-                    //判断当前是否盈利
-                    String uplstr = (String) redisUtils.get(positionsUplKey);
-                    String realizedPnl = (String) redisUtils.get(positionsRealizedPnlKey);
-                    String imr = (String) redisUtils.get(positionsImrKey);
-                    if (uplstr != null && realizedPnl != null && imr != null) {
-                        BigDecimal uplValue = new BigDecimal(uplstr);
-                        BigDecimal realizedPnlValue = new BigDecimal(realizedPnl);
-                        BigDecimal imrValue = new BigDecimal(imr).multiply(new BigDecimal(OrderParamEnums.PING_CANG_SHOUYI.getValue()));
-                        if (realizedPnlValue.compareTo(BigDecimal.ZERO) <= 0) {
-                            BigDecimal realizedPnlValueZheng = realizedPnlValue.multiply(new BigDecimal("-1"));
-                            if (uplValue.compareTo(realizedPnlValue) > 0 && uplValue.compareTo(imrValue.add(realizedPnlValueZheng))  >= 0) {
-                                log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue);
-                                redisUtils.set(positionsOrderPriceKey, String.valueOf(pingCang.getValue()), 0);
-                                return OrderParamEnums.SELL.getValue();
-                            }else{
-                                //判断是否加仓(当前持仓过小,可以加仓)
-                                boolean isAddCang = doAddCang();
-                                log.info("减仓过程中发现持仓过小 :{}",isAddCang);
-                                if (isAddCang){
-                                    log.info("触发加仓......,持仓过小");
-                                    return OrderParamEnums.BUY.getValue();
-                                }
-                                log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue);
-                                redisUtils.set(positionsOrderPriceKey, String.valueOf(pingCang.getValue()), 0);
-                                return OrderParamEnums.HOLDING.getValue();
-                            }
+                if (pingCang != null && avgPx.compareTo(pingCang.getValue()) < 0) {
+                    log.info("开始减仓...平仓队列价格大于当前价格{}<={}", pingCang.getValue(), avgPx);
+                    // 手续费
+                    BigDecimal feeValue = PositionsWs.getAccountMap(accountName).get("fee").multiply(new BigDecimal("2"));
+                    //未实现收益
+                    BigDecimal uplValue = PositionsWs.getAccountMap(accountName).get("upl");
+                    //已实现收益
+                    BigDecimal realizedPnlValue = PositionsWs.getAccountMap(accountName).get("realizedPnl");
+                    realizedPnlValue = realizedPnlValue.add(feeValue);
 
-                        }else {
-                            if (uplValue.compareTo(imrValue)  >= 0) {
-                                log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue);
-                                redisUtils.set(positionsOrderPriceKey, String.valueOf(pingCang.getValue()), 0);
-                                return OrderParamEnums.SELL.getValue();
-                            }else{
-                                //判断是否加仓(当前持仓过小,可以加仓)
-                                boolean isAddCang = doAddCang();
-                                log.info("减仓过程中发现持仓过小 :{}",isAddCang);
-                                if (isAddCang){
-                                    log.info("触发加仓......,持仓过小");
-                                    return OrderParamEnums.BUY.getValue();
-                                }
-                                log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue);
-                                redisUtils.set(positionsOrderPriceKey, String.valueOf(pingCang.getValue()), 0);
-                                return OrderParamEnums.HOLDING.getValue();
-                            }
-                         }
+                    //持仓保证金
+                    BigDecimal imr = PositionsWs.getAccountMap(accountName).get("imr");
+                    String pingCangImr = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.PING_CANG_SHOUYI.name());
+                    BigDecimal imrValue = imr.multiply(new BigDecimal(pingCangImr));
+
+                    if (realizedPnlValue.compareTo(BigDecimal.ZERO) <= 0) {
+                        BigDecimal realizedPnlValueZheng = realizedPnlValue.multiply(new BigDecimal("-1"));
+                        if (uplValue.compareTo(realizedPnlValue) > 0 && uplValue.compareTo(imrValue.add(realizedPnlValueZheng))  >= 0) {
+                            log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue.add(realizedPnlValueZheng));
+                            WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                            return OrderParamEnums.SELL.getValue();
+                        }else{
+                            log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue.add(realizedPnlValueZheng));
+                            return OrderParamEnums.HOLDING.getValue();
+                        }
                     }else {
-                        return OrderParamEnums.HOLDING.getValue();
+                        if (uplValue.compareTo(imrValue.add(feeValue))  >= 0) {
+                            WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                            log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue.add(feeValue));
+                            return OrderParamEnums.SELL.getValue();
+                        }else{
+                            log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue.add(feeValue));
+                            return OrderParamEnums.HOLDING.getValue();
+                        }
                     }
                 } else {
                     log.info("未触发减仓......,等待");
@@ -218,20 +214,207 @@
             } else {
                 log.info("价格波动较小......,等待");
             }
-
-            return side;
+            return null;
         } catch (NumberFormatException e) {
             log.error("解析价格失败,请检查Redis中的值是否合法", e);
-            return OrderParamEnums.HOLDING.getValue();
+            return null;
         }
     }
 
-    private boolean doAddCang() {
-        String imr = (String) redisUtils.get(positionsImrKey);
-        BigDecimal imrValue = new BigDecimal(StrUtil.isBlank(imr) ? "0" : imr);
-        String everyTimeUsdt = (String) redisUtils.get(AccountWs.ACCOUNTWS_CHANNEL + ":" + CoinEnums.USDT.getCode() + ":everyTimeUsdt");
-        BigDecimal everyTimeUsdtValue = new BigDecimal(everyTimeUsdt);
-        return everyTimeUsdtValue.compareTo(imrValue) >= 0;
+    @Override
+    public String caoZuoShort(String accountName) {
+
+        log.info("开始看空执行操作CaoZuoServiceImpl......");
+        String accountReadyState = AccountWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name());
+        if (!CoinEnums.READY_STATE_YES.getCode().equals(accountReadyState)) {
+            log.info("账户通道未就绪,取消发送");
+            return null;
+        }
+        BigDecimal positionsReadyState = PositionsWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name()) == null
+                ? BigDecimal.ZERO : PositionsWs.getAccountMap(accountName).get(CoinEnums.READY_STATE.name());
+        if (WsMapBuild.parseBigDecimalSafe(CoinEnums.READY_STATE_YES.getCode()).compareTo(positionsReadyState) != 0) {
+            log.info("仓位通道未就绪,取消发送");
+            return null;
+        }
+        // 系统设置的开关,等于冷静中,则代表不开仓
+        String outStr = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.OUT.name());
+        if (OrderParamEnums.OUT_YES.getValue().equals(outStr)){
+            log.error("冷静中,不允许下单......");
+            return null;
+        }
+        BigDecimal cashBal = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get("cashBal"));
+
+        // 判断账户余额是否充足
+        if (cashBal.compareTo(BigDecimal.ZERO) <= 0){
+            log.error("账户没有钱,请充值......");
+            return null;
+        }
+        /**
+         * 判断止损抗压
+         */
+        // 实际亏损金额
+        BigDecimal realKuiSunAmount = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get("upl"));
+        log.info("未实现盈亏: {}", realKuiSunAmount);
+        String zhiSunPercent = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.ZHI_SUN.name());
+        BigDecimal zhiSunAmount = cashBal.multiply(new BigDecimal(zhiSunPercent));
+        log.info("预期亏损金额: {}", zhiSunAmount);
+        String kangYaPercent = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.KANG_CANG.name());
+        BigDecimal  kangYaAmount = cashBal.multiply(new BigDecimal(kangYaPercent));
+        log.info("预期抗仓金额: {}", kangYaAmount);
+
+        if (realKuiSunAmount.compareTo(BigDecimal.ZERO) < 0){
+            realKuiSunAmount = realKuiSunAmount.multiply(new BigDecimal("-1"));
+            // 账户预期亏损金额比这个还小时,立即止损
+            if (realKuiSunAmount.compareTo(zhiSunAmount) > 0){
+                log.error("账户冷静止损......");
+                WsMapBuild.saveStringToMap(InstrumentsWs.getAccountMap(accountName), CoinEnums.OUT.name(),  OrderParamEnums.OUT_YES.getValue());
+                return OrderParamEnums.OUT.getValue();
+            }
+            // 判断抗压
+            if (realKuiSunAmount.compareTo(kangYaAmount) > 0 && realKuiSunAmount.compareTo(zhiSunAmount) <= 0){
+                log.error("账户紧张扛仓......");
+                return OrderParamEnums.HOLDING.getValue();
+            }
+        }
+
+        if (PositionsWs.getAccountMap(accountName).get("pos") == null){
+            log.error("没有获取到持仓信息,等待初始化......");
+            return null;
+        }
+        BigDecimal pos = PositionsWs.getAccountMap(accountName).get("pos");
+        if (BigDecimal.ZERO.compareTo( pos) >= 0) {
+            log.error("持仓数量为零,进行初始化订单");
+            return null;
+        }
+        // 判断是否保证金超标
+        if (PositionsWs.getAccountMap(accountName).get("imr") == null){
+            log.error("没有获取到持仓信息,等待初始化......");
+            return null;
+        }
+        BigDecimal ordFrozImr = PositionsWs.getAccountMap(accountName).get("imr");
+        BigDecimal totalOrderUsdt = WsMapBuild.parseBigDecimalSafe(AccountWs.getAccountMap(accountName).get(CoinEnums.TOTAL_ORDER_USDT.name()));
+        if (ordFrozImr.compareTo(totalOrderUsdt) >= 0){
+            log.error("已满仓......");
+            return OrderParamEnums.HOLDING.getValue();
+        }
+
+        try {
+            // 获取标记价格和平均持仓价格
+            BigDecimal markPx = PositionsWs.getAccountMap(accountName).get("markPx");
+            BigDecimal avgPx = PositionsWs.getAccountMap(accountName).get("avgPx");
+            log.info("开仓价格: {}, 当前价格:{},匹配队列中......", avgPx, markPx);
+
+            // 初始化网格队列
+            PriorityBlockingQueue<AscBigDecimal> queueAsc = WangGeQueue.getQueueAsc();
+            PriorityBlockingQueue<DescBigDecimal> queueKaiCang = wangGeService.initKaiCang(avgPx, queueAsc);
+            PriorityBlockingQueue<AscBigDecimal> queuePingCang = wangGeService.initPingCang(avgPx, queueAsc);
+
+            // 处理订单价格在队列中的情况
+            String orderPrice = OrderInfoWs.getAccountMap(accountName).get("orderPrice");
+            handleOrderPriceInQueues(orderPrice, queueKaiCang, queuePingCang);
+            // 判断是加仓还是减仓
+            if (avgPx.compareTo(markPx) > 0) {
+                log.info("开始减仓...");
+                if (queueKaiCang.isEmpty()) {
+                    // 队列为空
+//                    log.info("开始加仓,但是超出了网格设置...");
+                    return OrderParamEnums.HOLDING.getValue();
+                }
+                DescBigDecimal kaiCang = queueKaiCang.peek();
+                if (kaiCang != null && avgPx.compareTo(kaiCang.getValue()) >= 0) {
+                    log.info("开始减仓...减仓队列价格小于开仓价格{}>{}", kaiCang.getValue(), avgPx);
+
+                    // 手续费
+                    BigDecimal feeValue = PositionsWs.getAccountMap(accountName).get("fee").multiply(new BigDecimal("2"));
+                    //未实现收益
+                    BigDecimal uplValue = PositionsWs.getAccountMap(accountName).get("upl");
+                    //已实现收益
+                    BigDecimal realizedPnlValue = PositionsWs.getAccountMap(accountName).get("realizedPnl");
+                    realizedPnlValue = realizedPnlValue.add(feeValue);
+
+                    //持仓保证金
+                    BigDecimal imr = PositionsWs.getAccountMap(accountName).get("imr");
+                    String pingCangImr = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.PING_CANG_SHOUYI.name());
+                    BigDecimal imrValue = imr.multiply(new BigDecimal(pingCangImr));
+
+                    if (realizedPnlValue.compareTo(BigDecimal.ZERO) <= 0) {
+                        BigDecimal realizedPnlValueZheng = realizedPnlValue.multiply(new BigDecimal("-1"));
+                        if (uplValue.compareTo(realizedPnlValue) > 0 && uplValue.compareTo(imrValue.add(realizedPnlValueZheng))  >= 0) {
+                            log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue.add(realizedPnlValueZheng));
+                            WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                            return OrderParamEnums.BUY.getValue();
+                        }else{
+                            log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue.add(realizedPnlValueZheng));
+                            return OrderParamEnums.HOLDING.getValue();
+                        }
+                    }else {
+                        if (uplValue.compareTo(imrValue.add(feeValue))  >= 0) {
+                            WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                            log.info("当前未实现盈亏:{}大于预计收益>{},赚钱咯", uplValue, imrValue.add(feeValue));
+                            return OrderParamEnums.BUY.getValue();
+                        }else{
+                            log.info("当前未实现盈亏:{}没有大于预计收益>{},钱在路上了", uplValue, imrValue.add(feeValue));
+                            return OrderParamEnums.HOLDING.getValue();
+                        }
+                    }
+                } else {
+                    log.info("未触发减仓......,等待");
+                    return OrderParamEnums.HOLDING.getValue();
+                }
+            } else if (avgPx.compareTo(markPx) < 0) {
+                log.info("开始加仓...");
+                if (queuePingCang.isEmpty()) {
+                    // 队列为空
+                    log.info("开始加仓,但是超出了网格设置...");
+                    return OrderParamEnums.HOLDING.getValue();
+                }
+                AscBigDecimal pingCang = queuePingCang.peek();
+                if (pingCang != null && markPx.compareTo(pingCang.getValue()) >= 0 && avgPx.compareTo(pingCang.getValue()) < 0) {
+                    log.info("开始加仓...加仓队列价格小于当前价格{}<={}", pingCang.getValue(), markPx);
+                    WsMapBuild.saveStringToMap(OrderInfoWs.getAccountMap(accountName), "orderPrice", String.valueOf(markPx));
+                    boolean buyCntTimeFlag = buyCntTimeShortEvent(accountName, avgPx, markPx);
+                    if (buyCntTimeFlag){
+                        log.info("加仓参数准备成功......");
+                        return OrderParamEnums.SELL.getValue();
+                    }else{
+                        log.error("加仓参数准备失败......");
+                        return null;
+                    }
+                } else {
+                    log.info("未触发加仓......,等待");
+                }
+            } else {
+                log.info("价格波动较小......,等待");
+            }
+            return null;
+        } catch (NumberFormatException e) {
+            log.error("解析价格失败,请检查Redis中的值是否合法", e);
+            return null;
+        }
+    }
+
+    private boolean buyCntTimeLongEvent(String accountName, BigDecimal avgPx, BigDecimal markPx){
+        //判断当前价格和开仓价格直接间隔除以间距,取整,获取的数量是否大于等于0,如果大于0,则下单基础张数*倍数
+        String buyCntTime = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.BUY_CNT_TIME.name());
+        BigDecimal subtract = avgPx.subtract(markPx);
+        BigDecimal divide = subtract.divide(new BigDecimal(buyCntTime), 0, RoundingMode.DOWN);
+        if (divide.compareTo(BigDecimal.ZERO) <= 0){
+            log.warn("加仓次数间隔时间小于0,不加仓");
+            return false;
+        }
+        return WsMapBuild.saveStringToMap(TradeOrderWs.getAccountMap(accountName), "buyCntTime",String.valueOf(divide));
+    }
+
+    private boolean buyCntTimeShortEvent(String accountName, BigDecimal avgPx, BigDecimal markPx){
+        //判断当前价格和开仓价格直接间隔除以间距,取整,获取的数量是否大于等于0,如果大于0,则下单基础张数*倍数
+        String buyCntTime = InstrumentsWs.getAccountMap(accountName).get(CoinEnums.BUY_CNT_TIME.name());
+        BigDecimal subtract = markPx.subtract(avgPx);
+        BigDecimal divide = subtract.divide(new BigDecimal(buyCntTime), 0, RoundingMode.DOWN);
+        if (divide.compareTo(BigDecimal.ZERO) <= 0){
+            log.warn("加仓次数间隔时间小于0,不加仓");
+            return false;
+        }
+        return WsMapBuild.saveStringToMap(TradeOrderWs.getAccountMap(accountName), "buyCntTime",String.valueOf(divide));
     }
 
     /**
@@ -257,38 +440,39 @@
             log.warn("无效的价格格式: {}", orderPrice);
             return;
         }
+
         // 删除比该价格大的数据
         queueKaiCang.removeIf(item -> item.getValue().compareTo(priceDecimal) >= 0);
+
         // 打印开仓队列
-        StringBuilder kaiCangStr = new StringBuilder();
-        kaiCangStr.append("开仓队列: [");
-        boolean first = true;
-        for (DescBigDecimal item : queueKaiCang) {
-            if (!first) {
-                kaiCangStr.append(", ");
-            }
-            kaiCangStr.append(item.getValue());
-            first = false;
-        }
-        kaiCangStr.append("]");
-        log.info(kaiCangStr.toString());
+//        StringBuilder kaiCangStr = new StringBuilder();
+//        kaiCangStr.append("开仓队列: [");
+//        boolean first = true;
+//        for (DescBigDecimal item : queueKaiCang) {
+//            if (!first) {
+//                kaiCangStr.append(", ");
+//            }
+//            kaiCangStr.append(item.getValue());
+//            first = false;
+//        }
+//        kaiCangStr.append("]");
+//        log.info(kaiCangStr.toString());
 
         // 删除比该价格小的数据
         queuePingCang.removeIf(item -> item.getValue().compareTo(priceDecimal) <= 0);
 
         // 打印平仓队列
-        StringBuilder pingCangStr = new StringBuilder();
-        pingCangStr.append("平仓队列: [");
-        first = true;
-        for (AscBigDecimal item : queuePingCang) {
-            if (!first) {
-                pingCangStr.append(", ");
-            }
-            pingCangStr.append(item.getValue());
-            first = false;
-        }
-        pingCangStr.append("]");
-        log.info(pingCangStr.toString());
+//        StringBuilder pingCangStr = new StringBuilder();
+//        pingCangStr.append("平仓队列: [");
+//        first = true;
+//        for (AscBigDecimal item : queuePingCang) {
+//            if (!first) {
+//                pingCangStr.append(", ");
+//            }
+//            pingCangStr.append(item.getValue());
+//            first = false;
+//        }
+//        pingCangStr.append("]");
+//        log.info(pingCangStr.toString());
     }
 }
-

--
Gitblit v1.9.1