package com.nq.service.impl; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.nq.common.ServerResponse; import com.nq.dao.*; import com.nq.enums.EStockType; import com.nq.pojo.*; import com.nq.service.*; import com.nq.utils.timeutil.DateTimeUtil; import com.nq.utils.PropertiesUtil; import com.nq.utils.redis.JsonUtil; import com.nq.utils.redis.RedisShardedPoolUtils; import com.nq.utils.stock.sina.StockApi; import com.nq.vo.foreigncurrency.ExchangeVO; import com.nq.vo.position.UserPendingorderVO; import com.nq.vo.stock.MarketVO; import com.nq.vo.stock.StockListVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; /** * @author Administrator * @description 针对表【user_pendingorder】的数据库操作Service实现 * @createDate 2022-11-10 06:10:40 */ @Service @Slf4j public class UserPendingorderServiceImpl extends ServiceImpl implements UserPendingorderService { @Autowired private UserPendingorderMapper userPendingorderMapper; @Autowired private StockMapper stockMapper; @Autowired private IUserService iUserService; @Autowired private IUserPositionService iUserPositionService; @Autowired private SiteTaskLogMapper siteTaskLogMapper; @Autowired private UserMapper userMapper; @Autowired private StockIndexMapper stockIndexMapper; @Autowired private IStockIndexService iStockIndexService; @Autowired private IUserIndexPositionService iUserIndexPositionService; @Autowired private IStockCoinService iStockCoinService; @Autowired private IStockFuturesService iStockFuturesService; @Autowired private ISiteSettingService iSiteSettingService; @Autowired private UserPositionMapper userPositionMapper; @Autowired UserAssetsMapper userAssetsMapper; @Override public ServerResponse addOrder(String stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, BigDecimal targetPrice, HttpServletRequest request) { User user = this.iUserService.getCurrentRefreshUser(request); if (user == null) { return ServerResponse.createByErrorMsg("Please log in first",request); } SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting(); if (buyNum.intValue() < siteSetting.getBuyMinNum().intValue()) { return ServerResponse.createByErrorMsg("The pending order failed, and the purchased quantity was less than" + siteSetting .getBuyMinNum() + "stocks",request); } if (buyNum.intValue() > siteSetting.getBuyMaxNum().intValue()) { return ServerResponse.createByErrorMsg("The pending order failed because the purchased quantity was greater than" + siteSetting .getBuyMaxNum() + "stocks",request); } UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper() .eq(UserAssets::getUserId, user.getId()) .eq(UserAssets::getAccectType, "JP") ); BigDecimal amount = new BigDecimal(buyNum).multiply(targetPrice).setScale(5, RoundingMode.DOWN); if (userAssets.getAvailableBalance().compareTo(amount) < 0) { return ServerResponse.createByErrorMsg("订单失败,余额不足", request); } if(buyNum<100){ return ServerResponse.createByErrorMsg("最低购买数量"+siteSetting.getBuyMinNum(), request); } userAssets.setAvailableBalance(userAssets.getAvailableBalance().add(amount.negate())); userAssets.setFreezeMoney(userAssets.getFreezeMoney().add(amount)); userAssetsMapper.updateById(userAssets); UserPendingorder userPendingorder = new UserPendingorder(); userPendingorder = new UserPendingorder(); userPendingorder.setUserId(user.getId()); userPendingorder.setStockId(stockId); userPendingorder.setBuyNum(buyNum); userPendingorder.setBuyType(buyType); userPendingorder.setLever(lever); userPendingorder.setProfitTarget(profitTarget); userPendingorder.setStopTarget(stopTarget); userPendingorder.setNowPrice(new BigDecimal(0)); userPendingorder.setTargetPrice(targetPrice); userPendingorder.setAddTime(new Date()); userPendingorder.setStatus(0); int ret = userPendingorderMapper.insert(userPendingorder); if (ret > 0) { String lang = request.getHeader("lang"); if(lang.equals("ja")){ String msg = "注文が成功しました。取引時間内に自動的に約定されます。"; return ServerResponse.createBySuccessMsg(msg); }else{ return ServerResponse.createBySuccessMsg("If the pending order is successfully added, the order will be automatically placed if the order conditions are met",request); } } return ServerResponse.createByErrorMsg("Add failure",request); } @Override public ServerResponse orderList(HttpServletRequest request) { String property = PropertiesUtil.getProperty("user.cookie.name"); String header = request.getHeader(property); // log.info("header:{}",header); if (header != null) { String userJson = RedisShardedPoolUtils.get(header); User user = (User) JsonUtil.string2Obj(userJson, User.class); // log.info("user:{}",user); if (user != null) { List userPendingorders = userPendingorderMapper.selectList(new QueryWrapper().eq("user_id", user.getId()).ne("status",1)); List UserPendingorderList = new ArrayList(); for (UserPendingorder userPendingorder : userPendingorders) { UserPendingorderVO userPendingorderVO = new UserPendingorderVO(); //挂单-指数 //挂单-股票 Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId()); StockListVO stockListVO = new StockListVO(); stockListVO = StockApi.getStockRealTime( stock); String nowPrice = stockListVO.getNowPrice(); if (nowPrice == null) { nowPrice = String.valueOf(0); } userPendingorderVO.setNowPrice(new BigDecimal(nowPrice)); userPendingorderVO.setStockName(stock.getStockName()); userPendingorderVO.setStockId(stock.getStockCode()); userPendingorderVO.setBuyNum(userPendingorder.getBuyNum()); userPendingorderVO.setBuyType(userPendingorder.getBuyType()); userPendingorderVO.setLever(userPendingorder.getLever()); userPendingorderVO.setProfitTarget(userPendingorder.getProfitTarget()); userPendingorderVO.setStopTarget(userPendingorder.getStopTarget()); userPendingorderVO.setTargetPrice(userPendingorder.getTargetPrice()); userPendingorderVO.setAddTime(userPendingorder.getAddTime()); userPendingorderVO.setStatus(userPendingorder.getStatus()); userPendingorderVO.setId(userPendingorder.getId()); UserPendingorderList.add(userPendingorderVO); } return ServerResponse.createBySuccess(UserPendingorderList); } } return ServerResponse.createByErrorMsg("数据异常"); } @Override public void orderTask() { List userPendingorders = userPendingorderMapper.selectList(new QueryWrapper().eq("status", 0)); log.info("当前有挂单的用户数量 为 {}", Integer.valueOf(userPendingorders.size())); for (int i = 0; i < userPendingorders.size(); i++) { Integer userId = (Integer) userPendingorders.get(i).getUserId(); User user = this.userMapper.selectById(userId); if (user == null) { continue; } List userPendingorderList = userPendingorderMapper.selectList(new QueryWrapper().eq("user_id", userId).eq("status", 0)); if (userPendingorderList == null) { continue; } log.info("用户id = {} 姓名 = {} 已挂单数: {}", new Object[]{userId, user.getRealName(), Integer.valueOf(userPendingorders.size())}); BigDecimal all_freez_amt = new BigDecimal("0"); String nowPrice = ""; String code = ""; Integer indexId = null; StockListVO stockListVO = new StockListVO(); StockCoin stockCoin = new StockCoin(); for (UserPendingorder userPendingorder : userPendingorderList) { //指数 if (userPendingorder.getStockId().contains("sh") || userPendingorder.getStockId().contains("sz") || userPendingorder.getStockId().contains("hk") || userPendingorder.getStockId().contains("us")) { StockIndex model = stockIndexMapper.selectIndexByCode(userPendingorder.getStockId().replace("sh", "").replace("sz", "").replace("hk", "").replace("us", "")); all_freez_amt = (new BigDecimal(model.getDepositAmt().intValue())).multiply(new BigDecimal(userPendingorder.getBuyNum())).divide(new BigDecimal(userPendingorder.getLever())).setScale(4, 2); // if (){ // // }else { MarketVO marketVO = this.iStockIndexService.querySingleIndex(model.getIndexGid()); nowPrice = marketVO.getNowPrice(); // } indexId = model.getId(); } else { //股票 Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId()); if ("hk".equals(stock.getStockType())) { String hk = RedisShardedPoolUtils.get(stock.getStockGid(), 1); stockListVO = StockApi.otherStockListVO(hk); // stockCoin = iStockCoinService.selectCoinByCode("HKD"); ExchangeVO exchangeVO = this.iStockFuturesService.queryExchangeVO("HKD").getData(); nowPrice = String.valueOf(new BigDecimal(stockListVO.getNowPrice()).multiply(new BigDecimal(exchangeVO.getNowPrice()))); } else if ("us".equals(stock.getStockType())) { String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2); stockListVO = StockApi.otherStockListVO(us); // stockCoin = iStockCoinService.selectCoinByCode("USD"); ExchangeVO exchangeVO = this.iStockFuturesService.queryExchangeVO("USD").getData(); nowPrice = String.valueOf(new BigDecimal(stockListVO.getNowPrice()).multiply(new BigDecimal(exchangeVO.getNowPrice()))); } else { stockListVO = StockApi.getStockRealTime(stock); nowPrice = stockListVO.getNowPrice(); } all_freez_amt = new BigDecimal(nowPrice).multiply(new BigDecimal(userPendingorder.getBuyNum())).divide(new BigDecimal(userPendingorder.getLever()), 2, 4); code = stock.getStockCode(); } if (nowPrice == null) { nowPrice = String.valueOf(0); } if (userPendingorder.getUserId() != null && userPendingorder.getStockId() != null && userPendingorder.getBuyNum() != null && userPendingorder.getBuyType() != null && userPendingorder.getLever() != null && userPendingorder.getTargetPrice() != null) { int ret = userPendingorder.getBuyType().intValue() == 0 ? userPendingorder.getTargetPrice().compareTo(new BigDecimal(nowPrice)) : new BigDecimal(nowPrice).compareTo(userPendingorder.getTargetPrice()); //当前时间String String buyTime = DateTimeUtil.dateToStr(new Date()); if (ret == 0) { if (code != null && !"".equals(code)) { try { this.iUserPositionService.create(userPendingorder.getUserId(), code, nowPrice, buyTime, userPendingorder.getBuyNum(), userPendingorder.getBuyType(), userPendingorder.getLever(), userPendingorder.getProfitTarget(), userPendingorder.getStopTarget()); userPendingorder.setStatus(1); this.userPendingorderMapper.updateById(userPendingorder); SiteTaskLog siteTaskLog = new SiteTaskLog(); siteTaskLog.setTaskType("股票挂单转持仓"); String accountType = (user.getAccountType() == 0) ? "正式用户" : "模拟用户"; String tasktarget = "此次挂单买入id:" + userPendingorder.getId(); siteTaskLog.setTaskTarget(tasktarget); siteTaskLog.setAddTime(new Date()); siteTaskLog.setIsSuccess(0); siteTaskLog.setErrorMsg(""); int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog); if (insertTaskCount > 0) { log.info("挂单task任务成功"); } else { log.info("挂单task任务失败"); } } catch (Exception e) { log.error("股票挂单任务失败..."); userPendingorder.setStatus(2); this.userPendingorderMapper.updateById(userPendingorder); } } else if (indexId != null) { try { this.iUserIndexPositionService.buyIndexOrder(indexId, userPendingorder.getBuyNum(), userPendingorder.getBuyType(), userPendingorder.getLever(), userPendingorder.getProfitTarget(), userPendingorder.getStopTarget(), userPendingorder.getUserId()); userPendingorder.setStatus(1); this.userPendingorderMapper.updateById(userPendingorder); SiteTaskLog siteTaskLog = new SiteTaskLog(); siteTaskLog.setTaskType("指数挂单转持仓"); String accountType = (user.getAccountType() == 0) ? "正式用户" : "模拟用户"; String tasktarget = "此次挂单买入id:" + userPendingorder.getId(); siteTaskLog.setTaskTarget(tasktarget); siteTaskLog.setAddTime(new Date()); siteTaskLog.setIsSuccess(0); siteTaskLog.setErrorMsg(""); int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog); if (insertTaskCount > 0) { log.info("挂单task任务成功"); userPendingorder.setStatus(1); } else { log.info("挂单task任务失败"); } } catch (Exception e) { log.error("指数挂单任务失败..."); userPendingorder.setStatus(2); this.userPendingorderMapper.updateById(userPendingorder); } } } } } } log.info("===========挂单结束=========="); } //删除 @Override public ServerResponse delOrder(Integer id, HttpServletRequest request) { String property = PropertiesUtil.getProperty("user.cookie.name"); String header = request.getHeader(property); if (header != null) { String userJson = RedisShardedPoolUtils.get(header); User user = (User) JsonUtil.string2Obj(userJson, User.class); UserPendingorder userPendingorder = this.userPendingorderMapper.selectById(id); if (userPendingorder == null) { return ServerResponse.createByErrorMsg("The pending order does not exist",request); } if (user.getId().intValue() != userPendingorder.getUserId().intValue()) { return ServerResponse.createByErrorMsg("The pending order does not belong to you",request); } int delCount = this.userPendingorderMapper.deleteById(id); if (delCount > 0) { UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper() .eq(UserAssets::getUserId, user.getId()) .eq(UserAssets::getAccectType, "JP") ); BigDecimal amount = new BigDecimal(userPendingorder.getBuyNum()).multiply(userPendingorder.getTargetPrice()).setScale(5, RoundingMode.DOWN); userAssets.setAvailableBalance(userAssets.getAvailableBalance().add(amount)); userAssets.setFreezeMoney(userAssets.getFreezeMoney().add(amount.negate())); userAssetsMapper.updateById(userAssets); return ServerResponse.createByErrorMsg("Successfully deleted",request); } return ServerResponse.createByErrorMsg("Deletion failure",request); } return ServerResponse.createByErrorMsg("Please log in",request); } @Override public ServerResponse orderListByAdmin(int pageNum, int pageSize, String keywords, Integer status, HttpServletRequest request) { PageHelper.startPage(pageNum, pageSize); QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("buy_type",0); if (keywords != null && !keywords.equals("")) { queryWrapper.like("stock_id", keywords).or().like("user_id", keywords); } if (status != null && !status.equals("")) { queryWrapper.eq("status", status); } queryWrapper.orderByDesc("id"); List stockSubscribeList = this.userPendingorderMapper.selectList(queryWrapper); List UserPendingorderList = new ArrayList(); for (UserPendingorder userPendingorder : stockSubscribeList) { UserPendingorderVO userPendingorderVO = new UserPendingorderVO(); //挂单-股票 Stock stock = stockMapper.findStockByCode(userPendingorder.getStockId()); StockListVO stockListVO = new StockListVO(); if (stock.getStockType().equals("hk")) { String hk = RedisShardedPoolUtils.get(stock.getStockGid(), 1); stockListVO = StockApi.otherStockListVO(hk); } else if (stock.getStockType().equals("us")) { String us = RedisShardedPoolUtils.get(stock.getStockGid(), 2); stockListVO = StockApi.otherStockListVO(us); } else { stockListVO = StockApi.getStockRealTime( stock); } String nowPrice = stockListVO.getNowPrice(); if (nowPrice == null) { nowPrice = String.valueOf(0); } userPendingorderVO.setUserId(userPendingorder.getUserId()); userPendingorderVO.setNowPrice(new BigDecimal(nowPrice)); userPendingorderVO.setStockName(stock.getStockName()); userPendingorderVO.setStockId(stock.getStockCode()); userPendingorderVO.setBuyNum(userPendingorder.getBuyNum()); userPendingorderVO.setBuyType(userPendingorder.getBuyType()); userPendingorderVO.setLever(userPendingorder.getLever()); if(null != userPendingorder.getProfitTarget()){ userPendingorderVO.setProfitTarget(userPendingorder.getProfitTarget()); } if(null != userPendingorder.getStopTarget()){ userPendingorderVO.setStopTarget(userPendingorder.getStopTarget()); } userPendingorderVO.setTargetPrice(userPendingorder.getTargetPrice()); userPendingorderVO.setAddTime(userPendingorder.getAddTime()); userPendingorderVO.setStatus(userPendingorder.getStatus()); userPendingorderVO.setId(userPendingorder.getId()); UserPendingorderList.add(userPendingorderVO); } PageInfo pageInfo = new PageInfo(stockSubscribeList); pageInfo.setList(UserPendingorderList); return ServerResponse.createBySuccess(pageInfo); } @Override public ServerResponse updateOrderByAdmin(UserPendingorder userPendingorder) { if (userPendingorder.getId() == null) { return ServerResponse.createByErrorMsg("id不能为空"); } int updateCount = this.userPendingorderMapper.updateById(userPendingorder); if (updateCount > 0) { return ServerResponse.createBySuccessMsg("修改成功"); } return ServerResponse.createByErrorMsg("修改失败"); } @Override public ServerResponse addOrderByAdmin(String phone, String buyNum, String code, String buyType, String lever, String targetPrice, HttpServletRequest request) { if (StringUtils.isBlank(phone) || StringUtils.isBlank(buyNum) || StringUtils.isBlank(buyType) || StringUtils.isBlank(lever) || StringUtils.isBlank(targetPrice)) { return ServerResponse.createByErrorMsg("参数不能为空"); } User user = this.userMapper.selectOne(new QueryWrapper().eq("phone", phone)); if (user == null) { return ServerResponse.createByErrorMsg("用户不存在"); } Stock stock = stockMapper.findStockByCode(code); if (stock == null) { return ServerResponse.createByErrorMsg("股票不存在"); } UserPendingorder userPendingorder = new UserPendingorder(); userPendingorder.setUserId(user.getId()); userPendingorder.setStockId(code); userPendingorder.setBuyNum(Integer.valueOf(buyNum)); userPendingorder.setBuyType(Integer.valueOf(buyType)); userPendingorder.setLever(Integer.valueOf(lever)); userPendingorder.setTargetPrice(new BigDecimal(targetPrice)); userPendingorder.setAddTime(new Date()); userPendingorder.setStatus(0); userPendingorder.setNowPrice(new BigDecimal(0)); int insert = this.userPendingorderMapper.insert(userPendingorder); if (insert > 0) { return ServerResponse.createBySuccessMsg("添加成功"); } return ServerResponse.createByErrorMsg("添加失败"); } @Override public ServerResponse delOrderByAdmin(Integer id) { if (id == null) { return ServerResponse.createByErrorMsg("id不能为空"); } int delete = this.userPendingorderMapper.deleteById(id); if (delete > 0) { return ServerResponse.createBySuccessMsg("删除成功"); } return ServerResponse.createByErrorMsg("删除失败"); } @Override public ServerResponse examine(Integer id) { try{ UserPendingorder userPendingorder = getById(id); if(null != userPendingorder && userPendingorder.getStatus() != 0){ return ServerResponse.createByErrorMsg("当前状态无法操作"); } userPendingorder.setStatus(1); SiteTaskLog siteTaskLog = new SiteTaskLog(); siteTaskLog.setTaskType("股票挂单转持仓"); String tasktarget = "此次挂单买入id:" + userPendingorder.getId(); siteTaskLog.setTaskTarget(tasktarget); siteTaskLog.setAddTime(new Date()); siteTaskLog.setIsSuccess(0); siteTaskLog.setErrorMsg(""); this.userPendingorderMapper.updateById(userPendingorder); this.siteTaskLogMapper.insert(siteTaskLog); //当前时间String String buyTime = DateTimeUtil.dateToStr(new Date()); this.iUserPositionService.create(userPendingorder.getUserId(), userPendingorder.getStockId(), String.valueOf(userPendingorder.getTargetPrice()), buyTime, userPendingorder.getBuyNum(), userPendingorder.getBuyType(), userPendingorder.getLever(), userPendingorder.getProfitTarget(), userPendingorder.getStopTarget()); return ServerResponse.createBySuccessMsg("审核成功,挂单已转持仓"); }catch (Exception e){ log.error("挂单失败"); } return ServerResponse.createByErrorMsg("操作失败"); } }