zj
2025-10-05 fc68aa452e2fd56441128d1d5a4b32f254c6191d
src/main/java/project/contract/job/ContractOrderCalculationServiceImpl.java
@@ -1,10 +1,15 @@
package project.contract.job;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import kernel.util.StringUtils;
import kernel.web.ApplicationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -14,6 +19,11 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.ObjectUtils;
import project.contract.ContractLock;
import project.contract.ContractOrder;
@@ -27,6 +37,7 @@
import project.wallet.Wallet;
import project.wallet.WalletRedisKeys;
import project.wallet.WalletService;
import project.wallet.consumer.WalletDao;
import project.wallet.consumer.WalletMessage;
public class ContractOrderCalculationServiceImpl implements ContractOrderCalculationService, ApplicationContextAware {
@@ -36,6 +47,7 @@
   private ContractOrderService contractOrderService;
   private DataService dataService;
   private WalletService walletService;
   private WalletDao walletDao;
//   private RedisHandler redisHandler;
   private AssetService assetService;
   public final static String STATE_SUBMITTED = "submitted";
@@ -72,7 +84,6 @@
            /*
             * 0 买涨
             */
            logger.info("当前价格:"+close+"---------价格:"+Arith.add(order.getTrade_avg_price(), order.getPips()));
            if (close >= Arith.add(order.getTrade_avg_price(), order.getPips())) {
               settle(order, "profit", close);
            }
@@ -98,6 +109,9 @@
   }
   private static final Lock lock = new ReentrantLock(); // 全局锁,避免重复执行
   private static final long SLEEP_TIME = 500; // 重试间隔
   /**
    * 盈亏计算
    *
@@ -109,8 +123,6 @@
      double mul = Arith.mul(order.getDeposit_open(), order.getLever_rate());//仓位
      double div = Arith.div(mul, order.getTrade_avg_price());//持有币的数量
      double amount = Arith.mul(div, Arith.sub(currentPrice, order.getTrade_avg_price()));
      logger.info("---------盈亏金额:"+amount);
      logger.info("---------盈亏:"+profit_loss);
      RedisHandler redisHandler = getRedisHandler();
      if ("profit".equals(profit_loss)) {
         /**
@@ -161,7 +173,6 @@
            if(residueMoney > 0){
               wallet.setMoney(residueMoney);
               redisHandler.setSync(WalletRedisKeys.WALLET_PARTY_ID + wallet.getPartyId().toString(), wallet);
               redisHandler.pushAsyn(WalletRedisKeys.WALLET_QUEUE_UPDATE, new WalletMessage(order.getPartyId().toString(), amount));
            }
         }
      }
@@ -249,44 +260,19 @@
             * 触发全仓强平
             */
            this.contractOrderService.saveClose(order.getPartyId().toString(), order.getOrder_no());
            ThreadUtils.sleep(100);
            for (int i = 0; i < list.size(); i++) {
               ContractOrder close_line = list.get(i);
               if (!order.getOrder_no().equals(close_line.getOrder_no())) {
                  try {
                     while (true) {
                        if (ContractLock.add(close_line.getOrder_no())) {
                           this.contractOrderService.saveClose(close_line.getPartyId().toString(),
                                 close_line.getOrder_no());
                           /**
                            * 处理完退出
                            */
                           break;
                        }
                        ThreadUtils.sleep(500);
                     }
                  } catch (Exception e) {
                     logger.error("error:", e);
                  } finally {
                     ContractLock.remove(close_line.getOrder_no());
                     ThreadUtils.sleep(100);
                  }
               synchronized (close_line.getOrder_no()){
                  this.contractOrderService.saveClose(close_line.getPartyId().toString(),
                        close_line.getOrder_no());
               }
            }
            //钱包归零
            extracted(order, wallet, redisHandler);
         }
      } else {
         logger.info("---------进入单个持仓----------------");
         logger.info("---------order.getProfit()----------------"+order.getProfit());
         logger.info("---------order.getDeposit()----------------"+order.getDeposit());
         logger.info("---------order_close_line----------------"+order_close_line);
         if (order.getProfit() < 0 && (Arith.div(order.getDeposit(), Math.abs(order.getProfit())) <= Arith
               .div(order_close_line, 100))) {
            logger.info("---------进入强平了----------------");
            /**
             * 低于系统默认平仓线,进行强平
             */
@@ -294,8 +280,41 @@
            return;
         }
      }
   }
   private void extracted(ContractOrder order, Wallet wallet, RedisHandler redisHandler) {
      DataSourceTransactionManager transactionManager = ApplicationUtil.getBean(DataSourceTransactionManager.class);
      JdbcTemplate jdbcTemplate = ApplicationUtil.getBean(JdbcTemplate.class);
      TransactionStatus status = null;
      try {
         // 开启事务
         status = transactionManager.getTransaction(new DefaultTransactionDefinition());
         wallet.setMoney(0);
         redisHandler.setSync(WalletRedisKeys.WALLET_PARTY_ID + wallet.getPartyId().toString(), wallet);
         // 更新数据库
         int update = jdbcTemplate.update("UPDATE T_WALLET SET MONEY=ROUND(?,8) WHERE PARTY_ID=?", 0, wallet.getPartyId().toString());
         // 保存钱包信息
         Wallet ww = this.walletService.saveWalletByPartyId(order.getPartyId().toString());
         // 更新 redis
         redisHandler.setSync("PARTY_ID_MONEY_" + wallet.getPartyId().toString(), wallet.getMoney());
         // 提交事务
         transactionManager.commit(status);
      } catch (Exception e) {
         // 回滚事务
         if (status != null) {
            transactionManager.rollback(status);
         }
         logger.error("更新钱包时发生错误:", e);
         throw e;
      }
   }
   public void setDataService(DataService dataService) {
      this.dataService = dataService;
   }