1
zyy
2025-09-15 b08c3ca89f463f5a6775d77107d91cadce8bdf05
src/main/java/com/nq/service/impl/UserIndexPositionServiceImpl.java
@@ -9,8 +9,7 @@
import com.google.common.collect.Lists;
import com.nq.common.ServerResponse;
import com.nq.utils.CurrencyUtils;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.KeyUtils;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.stock.BuyAndSellUtils;
import com.nq.vo.agent.AgentIncomeVO;
@@ -25,6 +24,7 @@
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
@@ -38,7 +38,7 @@
public class UserIndexPositionServiceImpl implements IUserIndexPositionService {
    private static final Logger log = LoggerFactory.getLogger(UserIndexPositionServiceImpl.class);
    @Autowired
    @Resource
    UserIndexPositionMapper userIndexPositionMapper;
    @Autowired
@@ -50,199 +50,24 @@
    @Autowired
    ISiteIndexSettingService iSiteIndexSettingService;
    @Autowired
    @Resource
    UserMapper userMapper;
    @Autowired
    UserCashDetailMapper userCashDetailMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    @Resource
    AgentUserMapper agentUserMapper;
    @Autowired
    ISiteProductService iSiteProductService;
    @Autowired
    IUserIndexPositionService iUserIndexPositionService;
    @Autowired
    @Resource
    SiteTaskLogMapper siteTaskLogMapper;
    @Autowired
    CurrencyUtils currencyUtils;
    @Transactional
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse buyIndex(Integer indexId, Integer buyNum, Integer buyType, Integer lever,BigDecimal profitTarget,BigDecimal stopTarget, HttpServletRequest request) throws Exception {
        if (indexId == null || buyNum == null || buyType == null) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
        User user = this.iUserService.getCurrentRefreshUser(request);
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
            return ServerResponse.createByErrorMsg("下单失败,请先实名认证");
        }
        if(siteProduct.getHolidayDisplay()){
            return ServerResponse.createByErrorMsg("周末或节假日不能交易!");
        }
        log.info("用户 {} 下单, 指数id = {} ,数量 = {} 手 , 方向 = {} , 杠杆 = {}", new Object[]{user
                .getId(), indexId, buyNum, buyType, lever});
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("下单失败,账户已被锁定");
        }
        SiteIndexSetting siteIndexSetting = this.iSiteIndexSettingService.getSiteIndexSetting();
        if (siteIndexSetting == null) {
            log.error("下单出错,指数设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
        StockIndex stockIndex = this.iStockIndexService.selectIndexById(indexId);
        if (stockIndex.getIndexGid().contains("us")){
            String am_begin = siteIndexSetting.getTransAmBeginUs();
            String am_end = siteIndexSetting.getTransAmEndUs();
            String pm_begin = siteIndexSetting.getTransPmBeginUs();
            String pm_end = siteIndexSetting.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("下单失败,不在交易时段内");
            }
        }else if(stockIndex.getIndexGid().contains("hk")){
            String am_begin = siteIndexSetting.getTransAmBeginhk();
            String am_end = siteIndexSetting.getTransAmEndhk();
            String pm_begin = siteIndexSetting.getTransPmBeginhk();
            String pm_end = siteIndexSetting.getTransPmEndhk();
            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("下单失败,不在交易时段内");
            }
        }else {
            String am_begin = siteIndexSetting.getTransAmBegin();
            String am_end = siteIndexSetting.getTransAmEnd();
            String pm_begin = siteIndexSetting.getTransPmBegin();
            String pm_end = siteIndexSetting.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("下单失败,不在交易时段内");
            }
        }
        if (stockIndex == null) {
            return ServerResponse.createByErrorMsg("指数不存在");
        }
        if (1 != stockIndex.getTransState().intValue()) {
            return ServerResponse.createByErrorMsg("该指数不能交易");
        }
        //保证金= 指数保证金*数量/杠杆倍数
        BigDecimal all_deposit_amt = (new BigDecimal(stockIndex.getDepositAmt().intValue())).multiply(new BigDecimal(buyNum.intValue())).divide(new BigDecimal(lever)).setScale(4,2);
        if (user.getEnableIndexAmt().compareTo(all_deposit_amt) == -1) {
            return ServerResponse.createByErrorMsg("指数账户资金不足");
        }
        BigDecimal max_buy_amt = user.getEnableIndexAmt().multiply(siteIndexSetting.getBuyMaxPercent());
        if (max_buy_amt.compareTo(all_deposit_amt) == -1) {
            return ServerResponse.createByErrorMsg("不能超过最大购买比例");
        }
        if (user.getUserAmt().compareTo(new BigDecimal("0")) == -1) {
            return ServerResponse.createByErrorMsg("失败,融资总资金小于0");
        }
        if (user.getUserFutAmt().compareTo(new BigDecimal("0")) == -1) {
            return ServerResponse.createByErrorMsg("失败,期货总资金小于0");
        }
        MarketVO marketVO = this.iStockIndexService.querySingleIndex(stockIndex.getIndexGid());
        log.info("当前指数行情 = {}", JsonUtil.obj2StringPretty(marketVO));
        BigDecimal increaseRate = new BigDecimal(marketVO.getIncreaseRate());
        if (increaseRate.compareTo(new BigDecimal("0")) == 1) {
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) == -1 && buyType
                    .intValue() == 0) {
                return ServerResponse.createByErrorMsg("当前指数涨幅:" + increaseRate + ",不能买涨");
            }
        } else {
            increaseRate = increaseRate.negate();
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) == -1 && buyType
                    .intValue() == 1) {
                return ServerResponse.createByErrorMsg("当前指数跌幅:" + increaseRate + ",不能买跌");
            }
        }
        BigDecimal reckon_enable = user.getEnableIndexAmt().subtract(all_deposit_amt);
        user.setEnableIndexAmt(reckon_enable);
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        if (updateUserCount > 0) {
            log.info("【用户交易指数下单】修改用户金额成功");
        } else {
            log.error("用户交易指数下单】修改用户金额出错");
            throw new Exception("用户交易指数下单】修改用户金额出错");
        }
        UserIndexPosition userIndexPosition = new UserIndexPosition();
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
            userIndexPosition.setProfitTargetPrice(profitTarget);
        }
        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
            userIndexPosition.setStopTargetPrice(stopTarget);
        }
        BigDecimal buyPrice = new BigDecimal("0");
        if (stockIndex.getIndexGid().contains("hk")){
            buyPrice = currencyUtils.getNowIndexPrice(stockIndex.getIndexGid(),"HKD");
        }else if (stockIndex.getIndexGid().contains("us")){
            buyPrice = currencyUtils.getNowIndexPrice(stockIndex.getIndexGid(),"USD");
        }else {
            buyPrice = new BigDecimal(marketVO.getNowPrice());
        }
        userIndexPosition.setPositionType(user.getAccountType());
        userIndexPosition.setPositionSn(KeyUtils.getUniqueKey());
        userIndexPosition.setUserId(user.getId());
        userIndexPosition.setRealName(user.getRealName());
        userIndexPosition.setAgentId(user.getAgentId());
        userIndexPosition.setIndexName(stockIndex.getIndexName());
        userIndexPosition.setIndexCode(stockIndex.getIndexCode());
        userIndexPosition.setIndexGid(stockIndex.getIndexGid());
        userIndexPosition.setBuyOrderTime(new Date());
        userIndexPosition.setBuyOrderPrice(buyPrice);
        userIndexPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
        userIndexPosition.setOrderNum(buyNum);
        userIndexPosition.setIsLock(Integer.valueOf(0));
        userIndexPosition.setAllDepositAmt(all_deposit_amt);
        userIndexPosition.setOrderFee((new BigDecimal(stockIndex.getTransFee().intValue()))
                .multiply(new BigDecimal(buyNum.intValue())));
        userIndexPosition.setOrderStayDays(Integer.valueOf(0));
        userIndexPosition.setEachPoint(new BigDecimal(stockIndex.getEachPoint().intValue()));
        userIndexPosition.setProfitAndLose(new BigDecimal("0"));
        userIndexPosition.setAllProfitAndLose(new BigDecimal("0"));
        userIndexPosition.setOrderLever(lever);
        int insertPositionCount = this.userIndexPositionMapper.insert(userIndexPosition);
        if (insertPositionCount > 0) {
            log.info("【用户交易指数下单】保存持仓记录成功");
        } else {
            log.error("用户交易指数下单】保存持仓记录出错");
            throw new Exception("用户交易指数下单】保存持仓记录出错");
        }
        return ServerResponse.createBySuccess("Order successful");
    }
@@ -257,13 +82,13 @@
     * @return
     * @throws Exception
     */
    @Transactional
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse buyIndexOrder(Integer indexId, Integer buyNum, Integer buyType, Integer lever,BigDecimal profitTarget,BigDecimal stopTarget,Integer userId) throws Exception {
        if (indexId == null || buyNum == null || buyType == null) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }
        User user = this.userMapper.selectByPrimaryKey(userId);
        User user = this.userMapper.selectById(userId);
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (siteProduct.getRealNameDisplay() && (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard()))) {
@@ -327,107 +152,6 @@
        //保证金= 指数保证金*数量/杠杆倍数
        BigDecimal all_deposit_amt = (new BigDecimal(stockIndex.getDepositAmt().intValue())).multiply(new BigDecimal(buyNum.intValue())).divide(new BigDecimal(lever)).setScale(4,2);
        if (user.getEnableIndexAmt().compareTo(all_deposit_amt) == -1) {
            log.error("用户 {} 余额不足", user.getId());
            return ServerResponse.createByErrorMsg("指数账户资金不足");
        }
        BigDecimal max_buy_amt = user.getEnableIndexAmt().multiply(siteIndexSetting.getBuyMaxPercent());
        if (max_buy_amt.compareTo(all_deposit_amt) == -1) {
            log.error("不能超过最大购买比例");
            return ServerResponse.createByErrorMsg("不能超过最大购买比例");
        }
        if (user.getUserAmt().compareTo(new BigDecimal("0")) == -1) {
            log.error("用户 {} 余额不足", user.getId());
            return ServerResponse.createByErrorMsg("失败,融资总资金小于0");
        }
//        if (user.getUserFutAmt().compareTo(new BigDecimal("0")) == -1) {
//            return ServerResponse.createByErrorMsg("失败,期货总资金小于0");
//        }
        MarketVO marketVO = this.iStockIndexService.querySingleIndex(stockIndex.getIndexGid());
        log.info("当前指数行情 = {}", JsonUtil.obj2StringPretty(marketVO));
        BigDecimal increaseRate = new BigDecimal(marketVO.getIncreaseRate());
        if (increaseRate.compareTo(new BigDecimal("0")) == 1) {
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) == -1 && buyType
                    .intValue() == 0) {
                return ServerResponse.createByErrorMsg("当前指数涨幅:" + increaseRate + ",不能买涨");
            }
        } else {
            increaseRate = increaseRate.negate();
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) == -1 && buyType
                    .intValue() == 1) {
                return ServerResponse.createByErrorMsg("当前指数跌幅:" + increaseRate + ",不能买跌");
            }
        }
        BigDecimal reckon_enable = user.getEnableIndexAmt().subtract(all_deposit_amt);
        user.setEnableIndexAmt(reckon_enable);
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        if (updateUserCount > 0) {
            log.info("【用户交易指数下单】修改用户金额成功");
        } else {
            log.error("用户交易指数下单】修改用户金额出错");
            throw new Exception("用户交易指数下单】修改用户金额出错");
        }
        UserIndexPosition userIndexPosition = new UserIndexPosition();
        if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
            userIndexPosition.setProfitTargetPrice(profitTarget);
        }
        if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
            userIndexPosition.setStopTargetPrice(stopTarget);
        }
        BigDecimal buyPrice = new BigDecimal("0");
        if (stockIndex.getIndexGid().contains("hk")){
            buyPrice = currencyUtils.getNowIndexPrice(stockIndex.getIndexGid(),"HKD");
        }else if (stockIndex.getIndexGid().contains("us")){
            buyPrice = currencyUtils.getNowIndexPrice(stockIndex.getIndexGid(),"USD");
        }else {
            buyPrice = new BigDecimal(marketVO.getNowPrice());
        }
        userIndexPosition.setPositionType(user.getAccountType());
        userIndexPosition.setPositionSn(KeyUtils.getUniqueKey());
        userIndexPosition.setUserId(user.getId());
        userIndexPosition.setRealName(user.getRealName());
        userIndexPosition.setAgentId(user.getAgentId());
        userIndexPosition.setIndexName(stockIndex.getIndexName());
        userIndexPosition.setIndexCode(stockIndex.getIndexCode());
        userIndexPosition.setIndexGid(stockIndex.getIndexGid());
        userIndexPosition.setBuyOrderTime(new Date());
        userIndexPosition.setBuyOrderPrice(buyPrice);
        userIndexPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
        userIndexPosition.setOrderNum(buyNum);
        userIndexPosition.setIsLock(Integer.valueOf(0));
        userIndexPosition.setAllDepositAmt(all_deposit_amt);
        userIndexPosition.setOrderFee((new BigDecimal(stockIndex.getTransFee().intValue()))
                .multiply(new BigDecimal(buyNum.intValue())));
        userIndexPosition.setOrderStayDays(Integer.valueOf(0));
        userIndexPosition.setEachPoint(new BigDecimal(stockIndex.getEachPoint().intValue()));
        userIndexPosition.setProfitAndLose(new BigDecimal("0"));
        userIndexPosition.setAllProfitAndLose(new BigDecimal("0"));
        userIndexPosition.setOrderLever(lever);
        int insertPositionCount = this.userIndexPositionMapper.insert(userIndexPosition);
        if (insertPositionCount > 0) {
            log.info("【用户交易指数下单】保存持仓记录成功");
        } else {
            log.error("用户交易指数下单】保存持仓记录出错");
            throw new Exception("用户交易指数下单】保存持仓记录出错");
        }
        return ServerResponse.createBySuccess("Order successful");
    }
@@ -448,14 +172,13 @@
        for (int i = 0; i < userIdList.size(); i++) {
            log.info("=====================");
            Integer userId = (Integer)userIdList.get(i);
            User user = this.userMapper.selectByPrimaryKey(userId);
            User user = this.userMapper.selectById(userId);
            if(user == null){
                continue;
            }
            List<UserIndexPosition> userindexPositions = this.iUserIndexPositionService.findIndexPositionByUserIdAndSellPriceIsNull(userId);
            log.info("用户id = {} 姓名 = {} 指数持仓中订单数: {}", new Object[] { userId, user.getRealName(), Integer.valueOf(userindexPositions.size()) });
            BigDecimal enable_user_amt = user.getEnableAmt();
            BigDecimal all_freez_amt = new BigDecimal("0");
            for (UserIndexPosition userIndexPosition : userindexPositions) {
@@ -470,13 +193,10 @@
                    try {
                        this.iUserIndexPositionService.sellIndex(userIndexPosition.getPositionSn(), 0);
                        User user1 = this.userMapper.selectByPrimaryKey(userId);
                        BigDecimal enable_user_amt1 = user1.getEnableAmt();
                        User user1 = this.userMapper.selectById(userId);
                        SiteTaskLog siteTaskLog = new SiteTaskLog();
                        siteTaskLog.setTaskType("指数止盈止损强平任务-指数持仓");
                        String accountType = (user.getAccountType().intValue() == 0) ? "正式用户" : "模拟用户";
                        String taskcnt = accountType + "-" + user.getRealName() + "被强平[达到目标盈亏] 用户id = " + user.getId() + ", 扣款可用资金 = " + enable_user_amt + "扣款后可用资金 = " + enable_user_amt1 + ",现价"+nowPrice+ ", 目标止盈价格:" + userIndexPosition.getProfitTargetPrice()+ ", 目标止损价格:" + userIndexPosition.getStopTargetPrice();
                        siteTaskLog.setTaskCnt(taskcnt);
                        String tasktarget = "此次强平订单号为:" + userIndexPosition.getPositionSn();
                        siteTaskLog.setTaskTarget(tasktarget);
                        siteTaskLog.setAddTime(new Date());
@@ -521,177 +241,9 @@
        return ServerResponse.createByErrorMsg("删除失败");
    }
    @Transactional
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse sellIndex(String positionSn, int doType) throws Exception {
        log.info("【用户交易平仓指数】 positionSn = {} , dotype = {}", positionSn, Integer.valueOf(doType));
        SiteIndexSetting siteIndexSetting = this.iSiteIndexSettingService.getSiteIndexSetting();
        if (siteIndexSetting == null) {
            log.error("平仓出错,网站指数设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败,系统设置错误");
        }
        UserIndexPosition userIndexPosition = this.userIndexPositionMapper.selectIndexPositionBySn(positionSn);
        if (doType != 0) {
            if (userIndexPosition.getIndexGid().contains("us")){
                String am_begin = siteIndexSetting.getTransAmBeginUs();
                String am_end = siteIndexSetting.getTransAmEndUs();
                String pm_begin = siteIndexSetting.getTransPmBeginUs();
                String pm_end = siteIndexSetting.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("平仓失败,不在交易时段内");
                }
            }else if(userIndexPosition.getIndexGid().contains("hk")){
                String am_begin = siteIndexSetting.getTransAmBeginhk();
                String am_end = siteIndexSetting.getTransAmEndhk();
                String pm_begin = siteIndexSetting.getTransPmBeginhk();
                String pm_end = siteIndexSetting.getTransPmEndhk();
                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("下单失败,不在交易时段内");
                }
            }else {
                String am_begin = siteIndexSetting.getTransAmBegin();
                String am_end = siteIndexSetting.getTransAmEnd();
                String pm_begin = siteIndexSetting.getTransPmBegin();
                String pm_end = siteIndexSetting.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("平仓失败,不在交易时段内");
                }
            }
        }
        if (userIndexPosition == null) {
            return ServerResponse.createByErrorMsg("平仓失败,指数持仓不存在");
        }
        User user = this.userMapper.selectByPrimaryKey(userIndexPosition.getUserId());
        /*实名认证开关开启*/
        SiteProduct siteProduct = iSiteProductService.getProductSetting();
        if (siteProduct.getRealNameDisplay() && user.getIsLock().intValue() == 1) {
            return ServerResponse.createByErrorMsg("平仓失败,用户已被锁定");
        }
        if(siteProduct.getHolidayDisplay()){
            return ServerResponse.createByErrorMsg("周末或节假日不能交易!");
        }
        if (userIndexPosition.getSellOrderPrice() != null) {
            return ServerResponse.createByErrorMsg("平仓失败,此订单已平仓");
        }
        if (1 == userIndexPosition.getIsLock().intValue()) {
            return ServerResponse.createByErrorMsg("平仓失败 " + userIndexPosition.getLockMsg());
        }
        MarketVO marketVO = this.iStockIndexService.querySingleIndex(userIndexPosition.getIndexGid());
        log.info("当前指数行情 = {}", JsonUtil.obj2StringPretty(marketVO));
        BigDecimal increaseRate = new BigDecimal(marketVO.getIncreaseRate());
        if (increaseRate.compareTo(new BigDecimal("0")) == 1) {
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) != 1 && "买跌"
                    .equals(userIndexPosition.getOrderDirection())) {
                return ServerResponse.createByErrorMsg("当前指数涨幅:" + increaseRate + ",不能卖出");
            }
        } else {
            increaseRate = increaseRate.negate();
            if (siteIndexSetting.getRiseLimit().multiply(new BigDecimal("100"))
                    .compareTo(increaseRate) == -1 && "买涨"
                    .equals(userIndexPosition.getOrderDirection())) {
                return ServerResponse.createByErrorMsg("当前指数跌幅:" + increaseRate + ",不能卖出");
            }
        }
        BigDecimal buyPrice = new BigDecimal("0");
        if (userIndexPosition.getIndexGid().contains("hk")){
            buyPrice = currencyUtils.getNowIndexPrice(userIndexPosition.getIndexGid(),"HKD");
        }else if (userIndexPosition.getIndexGid().contains("us")){
            buyPrice = currencyUtils.getNowIndexPrice(userIndexPosition.getIndexGid(),"USD");
        }else {
            buyPrice = new BigDecimal(marketVO.getNowPrice());
        }
        userIndexPosition.setSellOrderPrice((buyPrice));
        userIndexPosition.setSellOrderTime(new Date());
        BigDecimal point_sub = userIndexPosition.getSellOrderPrice().subtract(userIndexPosition.getBuyOrderPrice());
        BigDecimal profit_and_lose = point_sub.multiply(userIndexPosition.getEachPoint()).multiply(new BigDecimal(userIndexPosition.getOrderNum().intValue()));
        if ("买跌".equals(userIndexPosition.getOrderDirection())) {
            profit_and_lose = profit_and_lose.negate();
        }
        userIndexPosition.setProfitAndLose(profit_and_lose);
        BigDecimal all_profit = profit_and_lose.subtract(userIndexPosition.getOrderFee());
        userIndexPosition.setAllProfitAndLose(all_profit);
        int updateIndexPositionCount = this.userIndexPositionMapper.updateByPrimaryKeySelective(userIndexPosition);
        if (updateIndexPositionCount > 0) {
            log.info("【用户平仓指数】修改浮动盈亏记录成功");
        } else {
            log.error("【用户平仓指数】修改浮动盈亏记录出错");
            throw new Exception("用户平仓指数】修改浮动盈亏记录出错");
        }
        BigDecimal before_user_amt = user.getUserIndexAmt();
        BigDecimal before_enable_amt = user.getEnableIndexAmt();
        log.info("用户平仓之前 的 总资金  = {} , 可用资金 = {}", before_user_amt, before_enable_amt);
        BigDecimal user_index_amt = before_user_amt.add(all_profit);
        BigDecimal enable_index_amt = before_enable_amt.add(all_profit).add(userIndexPosition.getAllDepositAmt());
        log.info("用户平仓后的总资金  = {} , 可用资金 = {}", user_index_amt, enable_index_amt);
        user.setUserIndexAmt(user_index_amt);
        user.setEnableIndexAmt(enable_index_amt);
        int updateUserCount = this.userMapper.updateByPrimaryKeySelective(user);
        if (updateUserCount > 0) {
            log.info("【用户平仓指数】修改用户金额成功");
        } else {
            log.error("【用户平仓指数】修改用户金额出错");
            throw new Exception("【用户平仓指数】修改用户金额出错");
        }
        UserCashDetail ucd = new UserCashDetail();
        ucd.setPositionId(userIndexPosition.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("卖出指数," + userIndexPosition.getIndexName() + "/" + userIndexPosition
                .getIndexCode() + ",总盈亏:" + all_profit);
        ucd.setAddTime(new Date());
        ucd.setIsRead(Integer.valueOf(0));
        int insertSxfCount = this.userCashDetailMapper.insert(ucd);
        if (insertSxfCount > 0) {
            log.info("【用户平仓指数】保存明细记录成功");
        } else {
            log.error("【用户平仓指数】保存明细记录出错");
            throw new Exception("【用户平仓指数】保存明细记录出错");
        }
        return ServerResponse.createBySuccessMsg("Closed position successfully!");
    }