jack
2024-04-02 4046f94a57f0c10e9509a49ad0d37d701aeb8186
src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
@@ -1,9 +1,8 @@
package com.nq.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.nq.dao.*;
import com.nq.enums.EStockType;
import com.nq.enums.EUserAssets;
import com.nq.pojo.*;
import com.nq.service.*;
import com.github.pagehelper.PageHelper;
@@ -11,14 +10,13 @@
import com.google.common.collect.Lists;
import com.nq.common.ServerResponse;
import com.nq.utils.*;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.BuyAndSellUtils;
import com.nq.utils.stock.GeneratePosition;
import com.nq.utils.stock.GetStayDays;
import com.nq.utils.stock.pinyin.GetPyByChinese;
import com.nq.utils.stock.sina.StockApi;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.vo.agent.AgentIncomeVO;
import com.nq.vo.foreigncurrency.ExchangeVO;
import com.nq.vo.position.AdminPositionVO;
import com.nq.vo.position.AgentPositionVO;
import com.nq.vo.position.PositionProfitVO;
@@ -33,6 +31,7 @@
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
@@ -44,11 +43,14 @@
    private static final Logger log = LoggerFactory.getLogger(UserPositionServiceImpl.class);
    @Autowired
    @Resource
    UserPositionMapper userPositionMapper;
    @Autowired
    IUserService iUserService;
    @Autowired
    IUserAssetsServices userAssetsServices;
    @Autowired
    ISiteSettingService iSiteSettingService;
@@ -59,16 +61,16 @@
    @Autowired
    IStockService iStockService;
    @Autowired
    @Resource
    UserMapper userMapper;
    @Autowired
    @Resource
    UserCashDetailMapper userCashDetailMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    @Resource
    AgentUserMapper agentUserMapper;
    @Autowired
    @Resource
    SiteTaskLogMapper siteTaskLogMapper;
    @Autowired
    StockMapper stockMapper;
@@ -83,9 +85,9 @@
    FundsApplyMapper fundsApplyMapper;
    @Autowired
    UserStockSubscribeMapper userStockSubscribeMapper;
    @Autowired
    @Resource
    StockSubscribeMapper stockSubscribeMapper;
    @Autowired
    @Resource
    UserIndexPositionMapper userIndexPositionMapper;
    @Autowired
@@ -94,17 +96,18 @@
    IStockCoinService iStockCoinService;
    @Autowired
    CurrencyUtils currencyUtils;
    @Autowired
    @Resource
    StockDzMapper stockDzMapper;
    @Autowired
    IUserAssetsServices iUserAssetsServices;
    @Autowired
    TradingHourServiceImpl tradingHourService;
    @Transactional
    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) throws Exception {
        // 判断周末不能买
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        User user = this.iUserService.getCurrentRefreshUser(request);
@@ -112,11 +115,11 @@
            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
        }
        log.info("用户 {} 下单,股票id = {} ,数量 = {} , 方向 = {} , 杠杆 = {}", user
                .getId(), stockId, buyNum, buyType, lever);
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("Order failed, account has been locked");
        }
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("下单出错,网站设置表不存在");
@@ -124,111 +127,38 @@
        }
        Stock stock = stockMapper.selectByPrimaryKey(stockId);
        log.info("当前股票信息  {}", new Gson().toJson(stock));
        if (stock == null) {
            return ServerResponse.createByErrorMsg("Order failed, stock code error");
        }
        BigDecimal userEnableAmt;
        if (stock.getStockType().equals(EStockType.US.getCode())) {
            userEnableAmt = user.getEnableIndexAmt();
        } else {
            userEnableAmt = user.getEnableAmt();
        }
        if (Objects.equals(stock.getStockType(), EStockType.US.getCode())) {
            if (buyNum < siteSetting.getDzMinByCount()) {
                return ServerResponse.createByErrorMsg("Minimum purchase for bulk commodities " + siteSetting.getDzMinByCount());
            }
            String am_begin = siteSetting.getTransAmBeginUs();
            String am_end = siteSetting.getTransAmEndUs();
            String pm_begin = siteSetting.getTransPmBeginUs();
            String pm_end = siteSetting.getTransPmEndUs();
            boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
            boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
            log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}", Boolean.valueOf(am_flag), Boolean.valueOf(pm_flag));
            if (!am_flag && !pm_flag) {
                return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
            }
        } else {
            String am_begin = siteSetting.getTransAmBegin();
            String am_end = siteSetting.getTransAmEnd();
            String pm_begin = siteSetting.getTransPmBegin();
            String pm_end = siteSetting.getTransPmEnd();
            boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
            boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
            log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}", Boolean.valueOf(am_flag), Boolean.valueOf(pm_flag));
            if (!am_flag && !pm_flag) {
                return ServerResponse.createByErrorMsg("Order failed, out of trading hours");
            }
            if (siteProduct.getHolidayDisplay()) {
                return ServerResponse.createByErrorMsg("No trading on weekends or holidays!");
            }
        //判断股票是否在可交易时间段
        Boolean b = tradingHourService.timeCheck();
        if (!b) {
            return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
        }
        if (stock.getIsLock().intValue() != 0) {
        if (stock.getIsLock() != 0) {
            return ServerResponse.createByErrorMsg("Order failed, shares cannot be traded at present");
        }
        List dbPosition = findPositionByStockCodeAndTimes(siteSetting.getBuySameTimes().intValue(), stock
                .getStockCode(), user.getId());
        if (dbPosition.size() >= siteSetting.getBuySameNums().intValue()) {
            return ServerResponse.createByErrorMsg("Frequent trading," + siteSetting.getBuySameTimes() + "Hold no more than one stock within a minute" + siteSetting
                    .getBuySameNums() + "article");
        }
        Integer transNum = findPositionNumByTimes(siteSetting.getBuyNumTimes().intValue(), user.getId());
        if (transNum.intValue() / 100 >= siteSetting.getBuyNumLots().intValue()) {
            return ServerResponse.createByErrorMsg("Frequent trading," + siteSetting
                    .getBuyNumTimes() + "Hold no more than one stock within a minute" + siteSetting.getBuyNumLots() + "hand");
        }
        if (buyNum.intValue() < siteSetting.getBuyMinNum().intValue()) {
            return ServerResponse.createByErrorMsg("Order failed, purchase quantity is less than" + siteSetting
                    .getBuyMinNum() + "股");
        }
        if (buyNum.intValue() > siteSetting.getBuyMaxNum().intValue()) {
            return ServerResponse.createByErrorMsg("Order failed, purchase quantity is greater than于" + siteSetting
                    .getBuyMaxNum() + "stocks");
        }
        BigDecimal now_price;
        StockListVO stockListVO = new StockListVO();
        StockCoin stockCoin = new StockCoin();
        //股票类型 现价 数据源的处理
        stockListVO = StockApi.getStockRealTime(stock);
        StockListVO  stockListVO = StockApi.getStockRealTime(stock);
        now_price = new BigDecimal(stockListVO.getNowPrice());
        if (now_price.compareTo(new BigDecimal("0")) == 0) {
            return ServerResponse.createByErrorMsg("Quote 0, please try again later");
        }
        BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum));
        BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum.intValue()));
        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
        int compareInt = buy_amt_autual.compareTo(new BigDecimal(siteSetting.getBuyMinAmt().intValue()));
        if (compareInt == -1) {
            return ServerResponse.createByErrorMsg("Order failed, purchase amount is less than" + siteSetting
                    .getBuyMinAmt());
        }
        BigDecimal max_buy_amt = userEnableAmt.multiply(siteSetting.getBuyMaxAmtPercent());
        int compareCwInt = buy_amt_autual.compareTo(max_buy_amt);
        if (compareCwInt == 1) {
            return ServerResponse.createByErrorMsg("Order failed, cannot exceed available funds." + siteSetting
                    .getBuyMaxAmtPercent().multiply(new BigDecimal("100")) + "%");
        }
        int compareUserAmtInt = userEnableAmt.compareTo(buy_amt_autual);
        log.info("用户可用金额 = {}  实际购买金额 =  {}", userEnableAmt, buy_amt_autual);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
        if (compareUserAmtInt == -1) {
            return ServerResponse.createByErrorMsg("下单失败,融资可用金额小于" + buy_amt_autual + "元");
        UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(),user.getId());
        if(userAssets.getAvailableBalance().compareTo(buy_amt)<0){
            return ServerResponse.createByErrorMsg("Order failed,Insufficient balance");
        }
        if (user.getUserIndexAmt().compareTo(new BigDecimal("0")) == -1) {
            return ServerResponse.createByErrorMsg("Failure, index total funds less than");
        }
        UserPosition userPosition = new UserPosition();
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
@@ -259,31 +189,19 @@
        userPosition.setIsLock(Integer.valueOf(0));
        userPosition.setOrderLever(lever);
        userPosition.setOrderTotalPrice(buy_amt);
        //递延费特殊处理
//            BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
//            BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
        BigDecimal allStayFee = BigDecimal.valueOf(0);
        userPosition.setOrderStayFee(allStayFee);
        userPosition.setOrderStayDays(1);
        BigDecimal buy_fee_amt = BigDecimal.valueOf(0);
//            BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
        log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
        userPosition.setOrderFee(buy_fee_amt);
        BigDecimal buy_yhs_amt = BigDecimal.valueOf(0);
//            BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
        log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
        userPosition.setOrderSpread(buy_yhs_amt);
//            SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stock.getStockCode(), now_price);
        BigDecimal spread_rate_amt = new BigDecimal("0");
//            if (siteSpread != null) {
//                spread_rate_amt = buy_amt.multiply(siteSpread.getSpreadRate()).setScale(2, 4);
//                log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", siteSpread.getSpreadRate(), spread_rate_amt);
//            } else {
//                log.info("用户购买点差费(配资后总资金 * 百分比{}) = {}", "设置异常", spread_rate_amt);
//            }
        userPosition.setSpreadRatePrice(spread_rate_amt);
        BigDecimal profit_and_lose = new BigDecimal("0");
@@ -292,40 +210,8 @@
        userPosition.setAllProfitAndLose(all_profit_and_lose);
        userPosition.setOrderStayDays(Integer.valueOf(0));
        userPosition.setOrderStayFee(new BigDecimal("0"));
        int insertPositionCount = 0;
        this.userPositionMapper.insert(userPosition);
        insertPositionCount = userPosition.getId();
        if (insertPositionCount > 0) {
            if (stock.getStockType().equals(EStockType.US.getCode())) {
                BigDecimal reckon_enable = userEnableAmt.subtract(buy_amt_autual);
                user.setUserIndexAmt(reckon_enable);
                int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
                if (updateUserCount > 0) {
                    log.info("【用户交易下单】修改用户金额成功");
                } else {
                    log.error("用户交易下单】修改用户金额出错");
                    throw new Exception("用户交易下单】修改用户金额出错");
                }
            } else {
                BigDecimal reckon_enable = userEnableAmt.subtract(buy_amt_autual);
                user.setEnableAmt(reckon_enable);
                int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
                if (updateUserCount > 0) {
                    log.info("【用户交易下单】修改用户金额成功");
                } else {
                    log.error("用户交易下单】修改用户金额出错");
                    throw new Exception("用户交易下单】修改用户金额出错");
                }
            }
            //核算代理收入-入仓手续费
//                iAgentAgencyFeeService.AgencyFeeIncome(1, userPosition.getPositionSn());
            log.info("【用户交易下单】保存持仓记录成功");
        } else {
            log.error("用户交易下单】保存持仓记录出错");
            throw new Exception("用户交易下单】保存持仓记录出错");
        }
        iUserAssetsServices.availablebalanceChange(stock.getStockType(),user.getId(), EUserAssets.BUY,buy_amt.negate(),"","");
        return ServerResponse.createBySuccessMsg("Order successful");
    }
@@ -373,9 +259,9 @@
    }
    public ServerResponse sell(String positionSn, int doType) throws Exception {
        log.info("【用户交易平仓】 positionSn = {} , dotype = {}", positionSn, Integer.valueOf(doType));
    @Transactional
    public ServerResponse sell(String positionSn, int doType) throws Exception  {
        SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
        if (siteSetting == null) {
            log.error("平仓出错,网站设置表不存在");
@@ -384,29 +270,34 @@
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
        if (doType != 0) {
            if (userPosition.getStockGid().contains(EStockType.US.getCode())) {
                String am_begin = siteSetting.getTransAmBeginUs();
                String am_end = siteSetting.getTransAmEndUs();
                String pm_begin = siteSetting.getTransPmBeginUs();
                String pm_end = siteSetting.getTransPmEndUs();
                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
                if (!am_flag && !pm_flag) {
                    return ServerResponse.createByErrorMsg("平仓失败,不在交易时段内");
                }
            } else {
                String am_begin = siteSetting.getTransAmBegin();
                String am_end = siteSetting.getTransAmEnd();
                String pm_begin = siteSetting.getTransPmBegin();
                String pm_end = siteSetting.getTransPmEnd();
                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
                if (!am_flag && !pm_flag) {
                    return ServerResponse.createByErrorMsg("Order failed,Out of trading hours");
                }
            }
            if (siteProduct.getHolidayDisplay()) {
                return ServerResponse.createByErrorMsg("No trading on weekends or holidays!");
//            if (userPosition.getStockGid().contains(EStockType.US.getCode())) {
//                String am_begin = siteSetting.getTransAmBeginUs();
//                String am_end = siteSetting.getTransAmEndUs();
//                String pm_begin = siteSetting.getTransPmBeginUs();
//                String pm_end = siteSetting.getTransPmEndUs();
//                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
//                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
//                if (!am_flag && !pm_flag) {
//                    return ServerResponse.createByErrorMsg("平仓失败,不在交易时段内");
//                }
//            } else {
//                String am_begin = siteSetting.getTransAmBegin();
//                String am_end = siteSetting.getTransAmEnd();
//                String pm_begin = siteSetting.getTransPmBegin();
//                String pm_end = siteSetting.getTransPmEnd();
//                boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
//                boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
//                if (!am_flag && !pm_flag) {
//                    return ServerResponse.createByErrorMsg("Order failed,Out of trading hours");
//                }
//            }
//            if (siteProduct.getHolidayDisplay()) {
//                return ServerResponse.createByErrorMsg("No trading on weekends or holidays!");
//            }
            //判断股票是否在可交易时间段
            Boolean b = tradingHourService.timeCheck();
            if (!b) {
                return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
            }
        }
@@ -416,7 +307,7 @@
            return ServerResponse.createByErrorMsg("Closing failed, order does not exist");
        }
        User user = this.userMapper.selectByPrimaryKey(userPosition.getUserId());
        User user = this.userMapper.selectById(userPosition.getUserId());
        if (user == null) {
            return ServerResponse.createByErrorMsg("Closed position failed, user does not exist");
        }
@@ -436,20 +327,11 @@
        if (1 == userPosition.getIsLock().intValue()) {
            return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
        }
//
//        if (!DateTimeUtil.isCanSell(userPosition.getBuyOrderTime(), siteSetting.getCantSellTimes().intValue())) {
//            return ServerResponse.createByErrorMsg(siteSetting.getCantSellTimes() + "分钟内不能平仓");
//        }
//        if (DateTimeUtil.sameDate(DateTimeUtil.getCurrentDate(),userPosition.getBuyOrderTime())) {
//            return ServerResponse.createByErrorMsg("当天入仓的股票需要隔天才能出仓");
//        }
        BigDecimal now_price;
        StockListVO stockListVO = new StockListVO();
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
        //股票卖出的 价格 数据源
        stockListVO = StockApi.getStockRealTime(stock);
        StockListVO    stockListVO = StockApi.getStockRealTime(stock);
        now_price = new BigDecimal(stockListVO.getNowPrice());
        if (stockListVO.getNowPrice() == null) {
            return ServerResponse.createByErrorMsg("Failed to close position, failed to obtain stock information");
@@ -458,138 +340,39 @@
            log.error("股票 = {} 收到报价 = {}", userPosition.getStockName(), now_price);
            return ServerResponse.createByErrorMsg("Quote 0, closing failed, please try again later");
        }
        double stock_crease = stockListVO.getHcrate().doubleValue();
        BigDecimal zsPrice = new BigDecimal(stockListVO.getPreclose_px());
        BigDecimal ztPrice = zsPrice.multiply(new BigDecimal("0.1")).add(zsPrice);
        ztPrice = ztPrice.setScale(2, 4);
        BigDecimal chaPrice = ztPrice.subtract(zsPrice);
        Integer buy_num = userPosition.getOrderNum();
        BigDecimal all_buy_amt = userPosition.getOrderTotalPrice();
        //BigDecimal all_sell_amt = now_price.multiply(new BigDecimal(buy_num.intValue())).divide(new BigDecimal(userPosition.getOrderLever())).setScale(2,4);
        BigDecimal all_sell_amt = now_price.multiply(new BigDecimal(buy_num.intValue()));
        BigDecimal profitLoss = new BigDecimal("0");
        if ("买涨".equals(userPosition.getOrderDirection())) {
            log.info("买卖方向:{}", "涨");
            profitLoss = all_sell_amt.subtract(all_buy_amt);
        } else {
            log.info("买卖方向:{}", "跌");
            profitLoss = all_buy_amt.subtract(all_sell_amt);
        }
        log.info("买入总金额 = {} , 卖出总金额 = {} , 盈亏 = {}", new Object[]{all_buy_amt, all_sell_amt, profitLoss});
        BigDecimal userAllAmt;
        BigDecimal userEnableAmt;
        if (EStockType.US.getCode().equals(userPosition.getStockGid())) {
            userAllAmt = user.getUserIndexAmt();
            userEnableAmt = user.getEnableIndexAmt();
            log.info("美股账号原本资金 = {} , 可用 = {}", userAllAmt, userEnableAmt);
        } else {
            userAllAmt = user.getUserAmt();
            userEnableAmt = user.getEnableAmt();
            log.info("印度账户用户原本总资金 = {} , 可用 = {}", userAllAmt, userEnableAmt);
        }
        BigDecimal buy_fee_amt = BigDecimal.ZERO;
        BigDecimal orderSpread = BigDecimal.ZERO;
        BigDecimal orderStayFee = BigDecimal.ZERO;
        BigDecimal spreadRatePrice = BigDecimal.ZERO;
        BigDecimal sell_fee_amt = BigDecimal.ZERO;
//        BigDecimal buy_fee_amt = userPosition.getOrderFee();
//        log.info("买入手续费 = {}", buy_fee_amt);
//
//        BigDecimal orderSpread = userPosition.getOrderSpread();
//        log.info("印花税 = {}", orderSpread);
//
//        BigDecimal orderStayFee = userPosition.getOrderStayFee();
//        log.info("递延费 = {}", orderStayFee);
//
//        BigDecimal spreadRatePrice = userPosition.getSpreadRatePrice();
//        log.info("点差费 = {}", spreadRatePrice);
//
//        BigDecimal sell_fee_amt = all_sell_amt.multiply(siteSetting.getSellFee()).setScale(2, 4);
//        log.info("卖出手续费 = {}", sell_fee_amt);
        //总手续费= 买入手续费+卖出手续费+印花税+递延费+点差费
        BigDecimal all_fee_amt = buy_fee_amt.add(sell_fee_amt).add(orderSpread).add(orderStayFee).add(spreadRatePrice);
        log.info("总的手续费费用 = {}", all_fee_amt);
        userPosition.setSellOrderId(GeneratePosition.getPositionId());
        userPosition.setSellOrderPrice(now_price);
        userPosition.setSellOrderTime(new Date());
        userPositionMapper.updateById(userPosition);
        userAssetsServices.availablebalanceChange(stock.getStockType(),userPosition.getUserId(),EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
                userPosition.getOrderTotalPrice(),"","");
        userAssetsServices.availablebalanceChange(stock.getStockType(),userPosition.getUserId(),EUserAssets.CLOSE_POSITION,
                userPosition.getProfitAndLose() ,"","");
        return ServerResponse.createBySuccessMsg("Closed position successfully!");
    }
        BigDecimal order_fee_all = buy_fee_amt.add(sell_fee_amt);
        userPosition.setOrderFee(order_fee_all);
        userPosition.setProfitAndLose(profitLoss);
        BigDecimal all_profit = profitLoss.subtract(all_fee_amt);
        userPosition.setAllProfitAndLose(all_profit);
        int updatePositionCount = this.userPositionMapper.updateByPrimaryKeySelective(userPosition);
        if (updatePositionCount > 0) {
            log.info("【用户平仓】修改浮动盈亏记录成功");
        } else {
            log.error("用户平仓】修改浮动盈亏记录出错");
            throw new Exception("用户平仓】修改浮动盈亏记录出错");
    @Transactional
    @Override
    public ServerResponse allSell(HttpServletRequest request,String stockType) throws Exception{
        //判断股票是否在可交易时间段
        Boolean b = tradingHourService.timeCheck();
        if (!b) {
            return ServerResponse.createByErrorMsg("Order failed, not in the  stock trading session");
        }
        BigDecimal freez_amt = all_buy_amt.divide(new BigDecimal(userPosition.getOrderLever().intValue()), 2, 4);
        //BigDecimal freez_amt = all_buy_amt;
        BigDecimal reckon_all = userAllAmt.add(all_profit);
        //修改用户可用余额=当前可用余额+总盈亏+买入总金额+追加保证金
        BigDecimal reckon_enable = userEnableAmt.add(all_profit).add(freez_amt).add(userPosition.getMarginAdd());
        if (EStockType.US.getCode().equals(userPosition.getStockGid())) {
            user.setUserIndexAmt(reckon_all);
            user.setEnableIndexAmt(reckon_enable);
            log.info("美股用户平仓后的总资金  = {} , 可用资金 = {}", reckon_all, reckon_enable);
        } else {
            user.setUserAmt(reckon_all);
            user.setEnableAmt(reckon_enable);
            log.info("印度股用户平仓后的总资金  = {} , 可用资金 = {}", reckon_all, reckon_enable);
        User user =    iUserService.getCurrentUser(request);
        if(user == null){
            return ServerResponse.createByErrorMsg("Please login");
        }
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        if (updateUserCount > 0) {
            log.info("【用户平仓】修改用户金额成功");
        } else {
            log.error("用户平仓】修改用户金额出错");
            throw new Exception("用户平仓】修改用户金额出错");
        QueryWrapper<UserPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        queryWrapper.eq("stock_gid",stockType);
        queryWrapper.isNull("sell_order_id");
        List<UserPosition> userPositionList = userPositionMapper.selectList(queryWrapper);
        for (int i = 0; i < userPositionList.size(); i++) {
            sell(userPositionList.get(i).getPositionSn(),0);
        }
        UserCashDetail ucd = new UserCashDetail();
        ucd.setPositionId(userPosition.getId());
        ucd.setAgentId(user.getAgentId());
        ucd.setAgentName(user.getAgentName());
        ucd.setUserId(user.getId());
        ucd.setUserName(user.getRealName());
        ucd.setDeType("总盈亏");
        ucd.setDeAmt(all_profit);
        ucd.setDeSummary("卖出股票," + userPosition.getStockCode() + "/" + userPosition.getStockName() + ",占用本金:" + freez_amt + ",总手续费:" + all_fee_amt + ",递延费:" + orderStayFee + ",印花税:" + orderSpread + ",盈亏:" + profitLoss + ",总盈亏:" + all_profit);
        ucd.setAddTime(new Date());
        ucd.setIsRead(Integer.valueOf(0));
        int insertSxfCount = this.userCashDetailMapper.insert(ucd);
        if (insertSxfCount > 0) {
            //核算代理收入-平仓手续费
            iAgentAgencyFeeService.AgencyFeeIncome(2, userPosition.getPositionSn());
            //核算代理收入-分红
            iAgentAgencyFeeService.AgencyFeeIncome(4, userPosition.getPositionSn());
            log.info("【用户平仓】保存明细记录成功");
        } else {
            log.error("用户平仓】保存明细记录出错");
            throw new Exception("用户平仓】保存明细记录出错");
        }
        return ServerResponse.createBySuccessMsg("Closed position successfully!");
    }
@@ -604,16 +387,6 @@
        }
        if (doType != 0) {
            /*String am_begin = siteSetting.getTransAmBegin();
            String am_end = siteSetting.getTransAmEnd();
            String pm_begin = siteSetting.getTransPmBegin();
            String pm_end = siteSetting.getTransPmEnd();
            boolean am_flag = BuyAndSellUtils.isTransTime(am_begin, am_end);
            boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin, pm_end);
            log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}", Boolean.valueOf(am_flag), Boolean.valueOf(pm_flag));
            if (!am_flag && !pm_flag) {
                return ServerResponse.createByErrorMsg("追加失败,不在交易时段内");
            }*/
        }
        UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
@@ -621,7 +394,7 @@
            return ServerResponse.createByErrorMsg("追加失败,订单不存在");
        }
        User user = this.userMapper.selectByPrimaryKey(userPosition.getUserId());
        User user = this.userMapper.selectById(userPosition.getUserId());
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (!siteProduct.getStockMarginDisplay()) {
@@ -640,8 +413,8 @@
            return ServerResponse.createByErrorMsg("追加失败 " + userPosition.getLockMsg());
        }
        BigDecimal user_all_amt = user.getUserAmt();
        BigDecimal user_enable_amt = user.getEnableAmt();
        BigDecimal user_all_amt = BigDecimal.ZERO;
        BigDecimal user_enable_amt = BigDecimal.ZERO;
        int compareUserAmtInt = user_enable_amt.compareTo(marginAdd);
        log.info("用户可用金额 = {}  追加金额 =  {}", user_enable_amt, marginAdd);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
@@ -664,8 +437,7 @@
        BigDecimal reckon_enable = user_enable_amt.subtract(marginAdd);
        log.info("用户追加保证金后的总资金  = {} , 可用资金 = {}", user_all_amt, reckon_enable);
        user.setEnableAmt(reckon_enable);
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        int updateUserCount = this.userMapper.updateById(user);
        if (updateUserCount > 0) {
            log.info("【用户平仓】修改用户金额成功");
        } else {
@@ -1000,7 +772,7 @@
        }
        User user = this.userMapper.selectByPrimaryKey(userId);
        User user = this.userMapper.selectById(userId);
        if (user == null) {
            log.info("用户不存在");
            return ServerResponse.createByErrorMsg("用户不存在");
@@ -1030,26 +802,9 @@
        }
        BigDecimal user_enable_amt = user.getEnableAmt();
        BigDecimal buy_amt = (new BigDecimal(buyPrice)).multiply(new BigDecimal(buyNum.intValue()));
        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever.intValue()), 2, 4);
        int compareUserAmtInt = user_enable_amt.compareTo(buy_amt_autual);
        log.info("用户可用金额 = {}  实际购买金额 =  {}", user_enable_amt, buy_amt_autual);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
        if (compareUserAmtInt == -1) {
            log.info("下单失败,用户可用金额小于" + buy_amt_autual + "元");
            return ServerResponse.createByErrorMsg("下单失败,用户可用金额小于" + buy_amt_autual + "元");
        }
        if (user.getUserIndexAmt().compareTo(new BigDecimal("0")) == -1) {
            log.info("失败,指数总资金小于0");
            return ServerResponse.createByErrorMsg("失败,指数总资金小于0");
        }
        UserPosition userPosition = new UserPosition();
@@ -1147,9 +902,7 @@
        } else {
            log.error("【创建持仓】保存记录出错");
        }
        BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual);
        user.setEnableAmt(reckon_enable);
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        int updateUserCount = this.userMapper.updateById(user);
        if (updateUserCount > 0) {
            log.info("【用户交易下单】修改用户金额成功");
        } else {
@@ -1588,8 +1341,7 @@
                userStockSubscribe.setStatus(5);
                userStockSubscribeMapper.update1(userStockSubscribe);
                if (userStockSubscribe.getType() == 1 || userStockSubscribe.getType() == 2) {
                    User user = userMapper.selectByPrimaryKey(userStockSubscribe.getUserId());
                    user.setDjzj(user.getDjzj().subtract(userStockSubscribe.getBond()));
                    User user = userMapper.selectById(userStockSubscribe.getUserId());
                    ret = userMapper.updateByPrimaryKey(user);
                }
                if (ret > 0) {
@@ -1625,7 +1377,6 @@
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
            return ServerResponse.createByErrorMsg("下单失败,请先实名认证");
        }
        BigDecimal user_enable_amt = user.getEnableAmt();
        log.info("用户 {} 下单,股票id = {} ,数量 = {} , 方向 = {} , 杠杆 = {}", new Object[]{user
                .getId(), stockCode, buyNum, buyType, lever});
@@ -1639,15 +1390,11 @@
            log.error("下单出错,网站设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
//        if (siteSetting.getVipQcMaxAmt().compareTo(user_enable_amt) > 0) {
//            return ServerResponse.createByErrorMsg("下单失败,可用余额小于"+siteSetting.getVipQcMaxAmt());
//        }
        Stock stock = null;
        ServerResponse stock_res = this.iStockService.findStockByCode(stockCode);
        if (!stock_res.isSuccess()) {
            return ServerResponse.createByErrorMsg("下单失败,股票代码错误");
        }
        stock = (Stock) stock_res.getData();
        Stock stock = (Stock) stock_res.getData();
        String am_begin = siteSetting.getTransAmBegin();
        String am_end = siteSetting.getTransAmEnd();
@@ -1808,21 +1555,6 @@
        }
        BigDecimal max_buy_amt = user_enable_amt.multiply(siteSetting.getBuyMaxAmtPercent());
        int compareCwInt = buy_amt_autual.compareTo(max_buy_amt);
        if (compareCwInt == 1) {
            return ServerResponse.createByErrorMsg("下单失败,不能超过可用资金的" + siteSetting
                    .getBuyMaxAmtPercent().multiply(new BigDecimal("100")) + "%");
        }
        int compareUserAmtInt = user_enable_amt.compareTo(buy_amt_autual);
        log.info("用户可用金额 = {}  实际购买金额 =  {}", user_enable_amt, buy_amt_autual);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
        if (compareUserAmtInt == -1) {
            return ServerResponse.createByErrorMsg("下单失败,可用金额小于" + buy_amt_autual + "元");
        }
//        if (user.getUserIndexAmt().compareTo(new BigDecimal("0")) == -1) {
//            return ServerResponse.createByErrorMsg("失败,指数总资金小于0");
//        }
@@ -1913,9 +1645,7 @@
            //修改用户可用余额= 当前余额-下单金额-买入手续费-印花税-点差费
            //BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual).subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
            //修改用户可用余额= 当前余额-下单总金额
            BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual);
            user.setEnableAmt(reckon_enable);
            int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
            int updateUserCount = this.userMapper.updateById(user);
            if (updateUserCount > 0) {
                log.info("【用户交易下单】修改用户金额成功");
            } else {
@@ -1951,7 +1681,6 @@
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
            return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
        }
        BigDecimal user_enable_amt = user.getEnableAmt();
        log.info("用户 {} 下单,股票code = {} ,数量 = {}", new Object[]{user
                .getId(), stockCode, num});
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
@@ -2062,21 +1791,6 @@
        }
        BigDecimal max_buy_amt = user_enable_amt.multiply(siteSetting.getBuyMaxAmtPercent());
        int compareCwInt = buy_amt_autual.compareTo(max_buy_amt);
        if (compareCwInt == 1) {
            return ServerResponse.createByErrorMsg("Order failed, purchase amount is less than" + siteSetting
                    .getBuyMaxAmtPercent().multiply(new BigDecimal("100")) + "%");
        }
        int compareUserAmtInt = user_enable_amt.compareTo(buy_amt_autual);
        log.info("用户可用金额 = {}  实际购买金额 =  {}", user_enable_amt, buy_amt_autual);
        log.info("比较 用户金额 和 实际 购买金额 =  {}", Integer.valueOf(compareUserAmtInt));
        if (compareUserAmtInt == -1) {
            return ServerResponse.createByErrorMsg("Order failed, the amount of financing available is less than" + buy_amt_autual);
        }
        UserPosition userPosition = new UserPosition();
        userPosition.setPositionType(3);
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
@@ -2145,9 +1859,7 @@
            //修改用户可用余额= 当前余额-下单金额-买入手续费-印花税-点差费
            //BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual).subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
            //修改用户可用余额= 当前余额-下单总金额
            BigDecimal reckon_enable = user_enable_amt.subtract(buy_amt_autual);
            user.setEnableAmt(reckon_enable);
            int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
            int updateUserCount = this.userMapper.updateById(user);
            if (updateUserCount > 0) {
                log.info("【用户交易下单】修改用户金额成功");
            } else {