1
zj
2024-04-29 de4c1a5257dfaa7ab26265f474b7176f6b55524d
src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
@@ -33,6 +33,9 @@
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -54,6 +57,9 @@
    @Autowired
    IUserAssetsServices userAssetsServices;
    @Autowired
    UserAssetsMapper userAssetsMapper;
    @Autowired
    ISiteSettingService iSiteSettingService;
@@ -114,6 +120,7 @@
    @Autowired
    IStockConfigServices iStockConfigServices;
    @Transactional
    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) {
@@ -147,21 +154,20 @@
            return ServerResponse.createByErrorMsg("最低购买数量"+mainBuyConfig.getCValue(), request);
        }
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
        StockConfig maxBuyConfig =  iStockConfigServices.queryByKey(EConfigKey.MAX_BUY.getCode());
        if(buyNum<Integer.parseInt(mainBuyConfig.getCValue())){
            return ServerResponse.createByErrorMsg("最高购买数量"+maxBuyConfig.getCValue(), request);
        }
        //
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        if (stock.getIsLock() != 0) {
            return ServerResponse.createByErrorMsg("订单失败,股票被锁定", request);
        }
        if (!priceServices.isLimitUpBuy(stock.getStockCode())) {
            return ServerResponse.createByErrorMsg("股票涨停,无法购买", request);
            return ServerResponse.createByErrorMsg("暂无配额", request);
        }
        //股票类型 现价 数据源的处理
@@ -174,11 +180,10 @@
        BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(buyNum)).divide(new BigDecimal(lever));
        BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
        BigDecimal   fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
        BigDecimal availableBalance =  fundratio.multiply(userAssets.getAvailableBalance());
        if (availableBalance.compareTo(buyAmt.add(orderFree)) < 0) {
            return ServerResponse.createByErrorMsg("订单失败,余额不足", request);
            return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
        }
        UserPosition userPosition = new UserPosition();
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
@@ -317,11 +322,27 @@
    public ServerResponse sell(String positionSn, int doType, HttpServletRequest request) {
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
        // 手续费率
        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.BUY_HANDLING_CHARGE.getCode()).getCValue()) ;
        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
        UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                .eq(UserAssets::getUserId, userPosition.getUserId())
                .eq(UserAssets::getAccectType, "IN")
        );
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
        if (!b) {
            return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
        }
        if(userPosition.getPositionType() == 3){
            StockDz stockDz = stockDzMapper.selectOne(new LambdaQueryWrapper<StockDz>().eq(StockDz::getStockCode, userPosition.getStockCode()));
            LocalDateTime buyOrderLocalDateTime = LocalDateTime.ofInstant(userPosition.getBuyOrderTime().toInstant(), ZoneId.systemDefault());
            // 计算天数差
            long daysBetween = ChronoUnit.DAYS.between(buyOrderLocalDateTime, LocalDateTime.now());
            if(daysBetween < stockDz.getPeriod()){
                return ServerResponse.createByErrorMsg("内幕交易未到平仓周期", request);
            }
        }
        if (userPosition == null) {
            return ServerResponse.createByErrorMsg("平仓失败,订单不存在", request);
@@ -1155,12 +1176,12 @@
        if (userStockSubscribe == null) {
            return ServerResponse.createByErrorMsg("无该申购记录");
        }
        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("code", userStockSubscribe.getNewCode()));
        StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new QueryWrapper<StockSubscribe>().eq("code", userStockSubscribe.getNewCode()).eq("type",userStockSubscribe.getType()));
        if (userStockSubscribe == null) {
            return ServerResponse.createByErrorMsg("该新股不存在");
        }
        if (userStockSubscribe.getStatus() == 4 || userStockSubscribe.getStatus() == 3 && stockSubscribe.getType() == 2) {
            Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockSpell, userStockSubscribe.getNewCode()));
            Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, userStockSubscribe.getNewCode()));
            if(null == stock){
                return ServerResponse.createByErrorMsg("该新股不存在");
            }
@@ -1225,7 +1246,12 @@
            int ret = 0;
            ret = this.userPositionMapper.insert(userPosition);
            UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), userPosition.getUserId());
            if(null == userAssets){
                return ServerResponse.createByErrorMsg("新股转持仓失败");
            }
            userAssets.setFreezeMoney(userAssets.getFreezeMoney().add(userPosition.getOrderTotalPrice()));
            userAssetsMapper.updateById(userAssets);
            if (ret > 0) {
                userStockSubscribe.setStatus(5);
                userStockSubscribeMapper.update1(userStockSubscribe);
@@ -1514,11 +1540,15 @@
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        User user = this.iUserService.getCurrentRefreshUser(request);
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
        if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
        }
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("Order failed, account has been locked");
        }
        UserAssets userAssets = userAssetsServices.assetsByTypeAndUserId("IN", user.getId());
        if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
            return ServerResponse.createByErrorMsg("请先缴清待补资金", request);
        }
        StockDz stockDz = this.stockDzMapper.selectOne(new QueryWrapper<StockDz>().eq("stock_code", stockCode));
        if (!Objects.equals(stockDz.getPassword(), password)) {
@@ -1531,7 +1561,7 @@
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockDz.getStockCode()));
        if(stockDz.getStartTime().getTime() > new Date().getTime() || stockDz.getEndTime().getTime() < new Date().getTime()){
            return ServerResponse.createByErrorMsg("不在大宗交易所时间之内", request);
            return ServerResponse.createByErrorMsg("不在内幕交易时间之内", request);
        }
        BigDecimal nowPrice = priceServices.getNowPrice(stockCode).multiply(stockDz.getDiscount());
@@ -1542,11 +1572,10 @@
            return ServerResponse.createByErrorMsg("最小购买数据" + stockDz.getStockNum(), request);
        }
        BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(num.intValue()));
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
        BigDecimal   fundratio = new BigDecimal(user.getFundRatio()).divide(new BigDecimal(100));
        BigDecimal availableBalance =  fundratio.multiply(userAssets.getAvailableBalance());
        if (buyAmt.compareTo(availableBalance) > 0) {
            return ServerResponse.createByErrorMsg("订单失败,余额不足", request);
            return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
        }
        UserPosition userPosition = new UserPosition();
        userPosition.setPositionType(3);
@@ -1598,21 +1627,23 @@
    @Transactional
    public void stockConstraint(List<UserPosition> list) {
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        BigDecimal siteBuyFee = siteSetting.getBuyFee();
        for (UserPosition position : list) {
            UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
                    .eq(UserAssets::getUserId, position.getUserId())
                    .eq(UserAssets::getAccectType, "IN")
            );
            if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
                continue;
            }
            //平仓检查
            Result result = getResult(position);
            if (result == null) continue;
            //利润为0不需要进行强制平仓
            if(result.signum == 0){
                continue;
            }
            boolean liquidation = false;
            Integer liquidation = 0;
            liquidation = isLiquidation(position, result.signum, result.profit, liquidation);
            if(liquidation){
                extracted(position, result.nowPrice, result.stock);
            if(liquidation != 0){
                extracted(position, result.nowPrice, result.stock,liquidation);
            }
        }
    }
@@ -1632,10 +1663,10 @@
        }
        // 检查是否在交易时间内
        if (!tradingHourService.timeCheck(position.getStockCode())) {
            log.info("不在交易时间之内,订单id: {}", position.getId());
            return null;
        }
//        if (!tradingHourService.timeCheck(position.getStockCode())) {
//            log.info("不在交易时间之内,订单id: {}", position.getId());
//            return null;
//        }
        //判断订单
        if (1 == position.getIsLock().intValue()) {
@@ -1645,17 +1676,17 @@
        // 检查股票是否垫停
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
            log.info("股票跌停,无法平仓,订单id: {}", position.getId());
            return null;
        }
//        if (!priceServices.isLimitDownSell(stock.getStockCode())) {
//            log.info("股票跌停,无法平仓,订单id: {}", position.getId());
//            return null;
//        }
        //最新报价
        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
        if (nowPrice.compareTo(BigDecimal.ZERO) <= 0) {
            log.info("报价0,平仓失败,订单id: {}", position.getId());
            return null;
        }
//        if (nowPrice.compareTo(BigDecimal.ZERO) <= 0) {
//            log.info("报价0,平仓失败,订单id: {}", position.getId());
//            return null;
//        }
        //判断订单是否已到强制平仓价格
        BigDecimal purchaseAmount = position.getBuyOrderPrice().multiply(new BigDecimal(position.getOrderNum()));// 买入价总额
@@ -1682,24 +1713,49 @@
    }
    //判断平仓
    private static boolean isLiquidation(UserPosition position, int signum, BigDecimal profit, boolean liquidation) {
    private Integer isLiquidation(UserPosition position, int signum, BigDecimal profit, Integer liquidation) {
        //-1强平 0未触发 1止损强平 2止盈强平
        //最新报价
        BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
        if(position.getOrderDirection().equals("买涨")){
            //判断亏损金额是否达到保证金金额
            BigDecimal negate = profit.negate();
            //如果买涨 signum 为-1则表示亏损
            if(signum == -1){
                //判断亏损金额是否达到保证金金额
                BigDecimal negate = profit.negate();
                if (negate.compareTo(position.getOrderTotalPrice()) >= 0){
                //止损
                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) <= 0){
                    //强制平仓
                    liquidation = true;
                    return liquidation = 1;
                }
                if (negate.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                    //强制平仓
                    return liquidation = -1;
                }
            }else{
                //止盈
                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) >= 0){
                    //强制平仓
                    return liquidation = 2;
                }
            }
        }else{
            //买跌 signum
            if(signum == 1){
                //判断亏损金额是否达到保证金金额
                if (profit.compareTo(position.getOrderTotalPrice()) >= 0){
                //止损
                if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) >= 0){
                    //强制平仓
                    liquidation = true;
                    return liquidation = 1;
                }
                //判断亏损金额是否达到保证金金额
                if (profit.compareTo(position.getOrderTotalPrice()) >= 0){//亏平强平
                    //强制平仓
                    return liquidation = -1;
                }
            }else{
                //止盈
                if(null != position.getProfitTargetPrice() && nowPrice.compareTo(position.getProfitTargetPrice()) <= 0){
                    //强制平仓
                    return liquidation = 2;
                }
            }
        }
@@ -1707,21 +1763,32 @@
    }
    //平仓
    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock) {
    private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock,Integer liquidation) {
        //-1强平 0未触发 1止损强平 2止盈强平
        BigDecimal siitteBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.SELL_HANDLING_CHARGE.getCode()).getCValue()) ;
        BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(position.getOrderNum()));
        BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);//手续费
        // 更新订单信息
        position.setSellOrderId(GeneratePosition.getPositionId());
        position.setSellOrderPrice(nowPrice);
        position.setSellOrderTime(new Date());
        userPositionMapper.updateById(position);
        if(liquidation == -1){
            userAssetsServices.availablebalanceChange(stock.getStockType(),
                    position.getUserId(),
                    EUserAssets.CONSTRAINT_CLOSE_POSITION,
                    position.getOrderTotalPrice(), "", "");
        }else if(liquidation == 1 || liquidation == 2){
            userAssetsServices.availablebalanceChange(stock.getStockType(),
                    position.getUserId(), EUserAssets.HANDLING_CHARGE,
                    xsPrice, "", "");
            PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(position, priceServices.getNowPrice(position.getStockCode()));
            userAssetsServices.availablebalanceChange(stock.getStockType(), position.getUserId(), EUserAssets.CLOSE_POSITION,
                    profitVO.getAllProfitAndLose(), "", "");
        }
        // 计算手续费等
        BigDecimal handlingFee = BigDecimal.ZERO;
        //更新用户资产
        userAssetsServices.availablebalanceChange(stock.getStockType(),
                position.getUserId(),
                EUserAssets.CONSTRAINT_CLOSE_POSITION,
                position.getOrderTotalPrice(), "", "");
        log.info("强制平仓成功,订单id: {}", position.getId());
    }