From 2a1216a7372538f92a79c73180d618381f7c9bb1 Mon Sep 17 00:00:00 2001
From: zyy <zyy@email.com>
Date: Tue, 24 Jun 2025 18:04:25 +0800
Subject: [PATCH] test
---
src/main/java/com/nq/service/impl/UserPositionServiceImpl.java | 701 ++++++++++++++++++++++++++++++++-------------------------
1 files changed, 391 insertions(+), 310 deletions(-)
diff --git a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
index 19b053d..13137f1 100644
--- a/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
+++ b/src/main/java/com/nq/service/impl/UserPositionServiceImpl.java
@@ -1,5 +1,6 @@
package com.nq.service.impl;
+import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nq.dao.*;
@@ -18,6 +19,7 @@
import com.nq.utils.stock.pinyin.GetPyByChinese;
import com.nq.utils.stock.sina.StockApi;
import com.nq.utils.timeutil.DateTimeUtil;
+import com.nq.utils.timeutil.TimeUtil;
import com.nq.vo.agent.AgentIncomeVO;
import com.nq.vo.position.AdminPositionVO;
import com.nq.vo.position.AgentPositionVO;
@@ -32,6 +34,11 @@
import java.math.BigDecimal;
import java.sql.Timestamp;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -105,89 +112,66 @@
IUserAssetsServices iUserAssetsServices;
@Autowired
- TradingHourServiceImpl tradingHourService;
+ ITradingHourService tradingHourService;
+
+ @Autowired
+ IPriceServices priceServices;
+
@Autowired
UserAssetsMapper userAssetsMapper;
@Transactional
- public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) throws Exception {
-
+ public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType, Integer lever, BigDecimal profitTarget, BigDecimal stopTarget, HttpServletRequest request) {
SiteProduct siteProduct = iSiteProductService.getProductSetting();
User user = this.iUserService.getCurrentRefreshUser(request);
- if (user.getIsActive() != 2) {
- return ServerResponse.createByErrorMsg("Order failed, please first real name authentication");
+ if (siteProduct.getRealNameDisplay() && user.getIsActive() != 2) {
+ return ServerResponse.createByErrorMsg("订单失败,请先实名认证", request);
}
+ SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
+ // 手续费率
+ BigDecimal siteSettingBuyFee = siteSetting.getBuyFee();
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("下单出错,网站设置表不存在");
- return ServerResponse.createByErrorMsg("Order failed, system setting error");
+ return ServerResponse.createByErrorMsg("订单失败,帐户已被锁定", request);
}
Stock stock = stockMapper.selectByPrimaryKey(stockId);
if (stock == null) {
- return ServerResponse.createByErrorMsg("Order failed, stock code error");
+ return ServerResponse.createByErrorMsg("订单失败,股票代码不存在", request);
+ }
+ //判断股票是否在可交易时间段
+ Boolean b = tradingHourService.timeCheck(stock.getStockCode());
+ if (!b) {
+ return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
}
- if (stock.getIsLock().intValue() != 0) {
- return ServerResponse.createByErrorMsg("Order failed, shares cannot be traded at present");
+ UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), user.getId());
+ if (stock.getIsLock() != 0) {
+ return ServerResponse.createByErrorMsg("订单失败,股票被锁定", request);
}
- 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 = StockApi.getStockRealTime(stock);
- now_price = new BigDecimal(stockListVO.getNowPrice());
+ BigDecimal nowPrice = priceServices.getNowPrice(stock.getStockCode(),stock.getStockType());
- if (now_price.compareTo(new BigDecimal("0")) == 0) {
- return ServerResponse.createByErrorMsg("Quote 0, please try again later");
+ if (nowPrice.compareTo(new BigDecimal("0")) == 0) {
+ return ServerResponse.createByErrorMsg("报价0,请稍后再试", request);
}
- BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum));
+ BigDecimal buyAmt = nowPrice.multiply(new BigDecimal(buyNum)).divide(new BigDecimal(lever));
+ BigDecimal orderFree = siteSettingBuyFee.multiply(buyAmt);
-
-
- UserAssets userAssets = userAssetsServices.selectByUserId(user.getId(),EStockType.IN.getCode());
- if(userAssets.getAvailableBalance().compareTo(buy_amt)<0){
- return ServerResponse.createByErrorMsg("Order failed,Insufficient balance");
-
+ if (userAssets.getAvailableBalance().compareTo(buyAmt.add(orderFree)) < 0) {
+ return ServerResponse.createByErrorMsg("订单失败,配资不足", request);
}
-
UserPosition userPosition = new UserPosition();
-
if (profitTarget != null && profitTarget.compareTo(new BigDecimal("0")) > 0) {
userPosition.setProfitTargetPrice(profitTarget);
}
if (stopTarget != null && stopTarget.compareTo(new BigDecimal("0")) > 0) {
userPosition.setStopTargetPrice(stopTarget);
}
-
-
userPosition.setPositionType(user.getAccountType());
userPosition.setPositionSn(KeyUtils.getUniqueKey());
userPosition.setUserId(user.getId());
@@ -199,7 +183,7 @@
userPosition.setStockSpell(stock.getStockSpell());
userPosition.setBuyOrderId(GeneratePosition.getPositionId());
userPosition.setBuyOrderTime(new Date());
- userPosition.setBuyOrderPrice(now_price);
+ userPosition.setBuyOrderPrice(nowPrice);
userPosition.setOrderDirection((buyType.intValue() == 0) ? "买涨" : "买跌");
userPosition.setOrderNum(buyNum);
if (stock.getStockPlate() != null) {
@@ -207,33 +191,21 @@
}
userPosition.setIsLock(Integer.valueOf(0));
userPosition.setOrderLever(lever);
- userPosition.setOrderTotalPrice(buy_amt);
- BigDecimal allStayFee = BigDecimal.valueOf(0);
- userPosition.setOrderStayFee(allStayFee);
- userPosition.setOrderStayDays(1);
+ userPosition.setOrderTotalPrice(buyAmt);
+ // 手续费
- BigDecimal buy_fee_amt = BigDecimal.valueOf(0);
- log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
- userPosition.setOrderFee(buy_fee_amt);
-
- BigDecimal buy_yhs_amt = BigDecimal.valueOf(0);
- log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
- userPosition.setOrderSpread(buy_yhs_amt);
-
- BigDecimal spread_rate_amt = new BigDecimal("0");
-
- userPosition.setSpreadRatePrice(spread_rate_amt);
+ userPosition.setOrderFee(orderFree);
+ userPosition.setOrderSpread(BigDecimal.ZERO);
+ userPosition.setSpreadRatePrice(BigDecimal.ZERO);
BigDecimal profit_and_lose = new BigDecimal("0");
userPosition.setProfitAndLose(profit_and_lose);
- BigDecimal all_profit_and_lose = profit_and_lose.subtract(buy_fee_amt).subtract(buy_yhs_amt).subtract(spread_rate_amt);
- userPosition.setAllProfitAndLose(all_profit_and_lose);
+ userPosition.setAllProfitAndLose(profit_and_lose.add(orderFree));
userPosition.setOrderStayDays(Integer.valueOf(0));
- userPosition.setOrderStayFee(new BigDecimal("0"));
-
- userAssets.setAvailableBalance(userAssets.getAvailableBalance().subtract(buy_amt));
- userAssetsMapper.updateById(userAssets);
- this.userPositionMapper.insert(userPosition);
- return ServerResponse.createBySuccessMsg("Order successful");
+ userPosition.setOrderStayFee(BigDecimal.ZERO);
+ userPositionMapper.insert(userPosition);
+ iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.BUY, buyAmt.negate(), "", "");
+ iUserAssetsServices.availablebalanceChange(stock.getStockType(), user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
+ return ServerResponse.createBySuccessMsg("下单成功", request);
}
@@ -247,7 +219,7 @@
if (positionSn.contains("index")) {
UserIndexPosition userIndexPosition = userIndexPositionMapper.selectIndexPositionBySn(positionSn.replace("index", ""));
if (userIndexPosition == null) {
- return ServerResponse.createByErrorMsg("指数持仓单不存在");
+ return ServerResponse.createByErrorMsg("指数持仓单不存在",request);
}
if (profitTarget != null && profitTarget > 0) {
userIndexPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
@@ -255,13 +227,12 @@
if (stopTarget != null && stopTarget > 0) {
userIndexPosition.setStopTargetPrice(BigDecimal.valueOf(stopTarget));
}
- log.info("指数止盈线" + profitTarget + "-------指数止损线" + stopTarget);
update = this.userIndexPositionMapper.updateByPrimaryKeySelective(userIndexPosition);
} else {
UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
if (userPosition == null) {
- return ServerResponse.createByErrorMsg("持仓记录不存在");
+ return ServerResponse.createByErrorMsg("持仓记录不存在",request);
}
if (profitTarget != null && profitTarget > 0) {
userPosition.setProfitTargetPrice(BigDecimal.valueOf(profitTarget));
@@ -273,114 +244,177 @@
update = this.userPositionMapper.updateByPrimaryKeySelective(userPosition);
}
if (update > 0) {
- return ServerResponse.createBySuccessMsg("修改成功");
+ return ServerResponse.createBySuccessMsg("修改成功",request);
} else {
- return ServerResponse.createByErrorMsg("修改失败");
+ return ServerResponse.createByErrorMsg("修改失败",request);
}
}
-
+ public static void main(String[] args) {
+ String a = "09:00";
+ System.out.println(Integer.parseInt(a.split(":")[0])>12);
+ }
@Transactional
- public ServerResponse sell(String positionSn, int doType) throws Exception {
- SiteSetting siteSetting = this.iSiteSettingService.getSiteSetting();
- if (siteSetting == null) {
- log.error("平仓出错,网站设置表不存在");
- return ServerResponse.createByErrorMsg("Order failed, system setting error");
- }
- SiteProduct siteProduct = iSiteProductService.getProductSetting();
+ public ServerResponse sell(String positionSn, int doType){
UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
+ BigDecimal siitteBuyFee = iSiteSettingService.getSiteSetting().getBuyFee();
+ Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
- if (userPosition == null) {
- return ServerResponse.createByErrorMsg("Closing failed, order does not exist");
+ if (!b) {
+ return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内");
}
-
+ if (userPosition == null) {
+ return ServerResponse.createByErrorMsg("平仓失败,订单不存在");
+ }
User user = this.userMapper.selectById(userPosition.getUserId());
if (user == null) {
- return ServerResponse.createByErrorMsg("Closed position failed, user does not exist");
+ return ServerResponse.createByErrorMsg("平仓失败,用户不存在");
}
-
- /*实名认证开关开启*/
- if (user.getIsActive() != 2) {
-
- return ServerResponse.createByErrorMsg("Closing failed, user is locked");
-
- }
-
-
if (userPosition.getSellOrderId() != null) {
- return ServerResponse.createByErrorMsg("Closing failed, this order is closed");
+ return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓");
}
-
if (1 == userPosition.getIsLock().intValue()) {
return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
}
- BigDecimal now_price;
Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
- //股票卖出的 价格 数据源
-
- 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");
+ BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+ if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
+ return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试");
}
- if (now_price.compareTo(new BigDecimal("0")) != 1) {
- log.error("股票 = {} 收到报价 = {}", userPosition.getStockName(), now_price);
- return ServerResponse.createByErrorMsg("Quote 0, closing failed, please try again later");
- }
-
userPosition.setSellOrderId(GeneratePosition.getPositionId());
- userPosition.setSellOrderPrice(now_price);
+ userPosition.setSellOrderPrice(nowPrice);
userPosition.setSellOrderTime(new Date());
- userPositionMapper.updateById(userPosition);
- BigDecimal multiply = now_price.multiply(new BigDecimal(userPosition.getOrderNum()));//最新平仓总价
- BigDecimal purchasePrice = userPosition.getBuyOrderPrice().multiply(new BigDecimal(userPosition.getOrderNum()));//购买总价
- UserAssets userAssets = userAssetsServices.selectByUserId(user.getId(),EStockType.IN.getCode());
- BigDecimal subtract = multiply.subtract(purchasePrice);//盈亏价格
- userAssets.setTotleAssets(userAssets.getTotleAssets().add(subtract));
- userAssets.setAvailableBalance(userAssets.getAvailableBalance().add(multiply));
- BigDecimal ultimately = BigDecimal.ZERO;
- if(userAssets.getSign() < 0){
- BigDecimal negate = userAssets.getCumulativeProfitAndLoss().negate();
- ultimately = negate.add(subtract);
- }else{
- BigDecimal negate = userAssets.getCumulativeProfitAndLoss();
- ultimately = negate.add(subtract);
+ BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
+ BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
+ userPositionMapper.updateById(userPosition);
+ userAssetsServices.availablebalanceChange(stock.getStockType(),
+ userPosition.getUserId(),EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
+ userPosition.getOrderTotalPrice(),"","");
+ userAssetsServices.availablebalanceChange(stock.getStockType(),
+ userPosition.getUserId(),EUserAssets.HANDLING_CHARGE,
+ xsPrice,"","");
+
+ PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition,priceServices.getNowPrice(userPosition.getStockCode()));
+ userAssetsServices.availablebalanceChange(stock.getStockType(),userPosition.getUserId(),EUserAssets.CLOSE_POSITION,
+ profitVO.getAllProfitAndLose() ,"","");
+ return ServerResponse.createBySuccessMsg("平仓成功!");
+ }
+
+
+ @Transactional
+ public ServerResponse sell(String positionSn, int doType, HttpServletRequest request) {
+ UserPosition userPosition = this.userPositionMapper.findPositionBySn(positionSn);
+
+ SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
+ // 手续费率
+ BigDecimal siitteBuyFee = siteSetting.getSellFee();
+
+
+
+// Calendar calendar = Calendar.getInstance();
+// int time = calendar.get(Calendar.HOUR_OF_DAY);
+// if(time<12 && time>=Integer.parseInt(siteSetting.getTransAmEnd().split(":")[0])){ //上午
+// return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内",request);
+// }
+// if(time>12 && time>=Integer.parseInt(siteSetting.getTransPmEnd().split(":")[0])){//下午
+// return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内",request);
+// }
+ Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", userPosition.getStockCode()));
+ if(null == stock){
+ return ServerResponse.createBySuccessMsg("股票不存在!", request);
}
- if(ultimately.signum() < 0){
- userAssets.setSign(-1);
- }else{
- userAssets.setSign(1);
+ //判断股票是否在可交易时间段
+// Boolean b = isStockMarketOpen(stock.getStockType());
+// Boolean wb = tradingHourService.weekDayeCheck(stock.getStockCode());
+// if (!b || !wb) {
+// return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内", request);
+// }
+
+ Boolean b = tradingHourService.timeCheck(userPosition.getStockCode());
+ if (!b) {
+ return ServerResponse.createByErrorMsg("订单失败,不在交易时间之内");
}
- userAssets.setCumulativeProfitAndLoss(ultimately.abs());
- userAssetsMapper.updateById(userAssets);
- userMapper.updateById(user);
- return ServerResponse.createBySuccessMsg("Closed position successfully!");
+
+ if (userPosition == null) {
+ return ServerResponse.createByErrorMsg("平仓失败,订单不存在", request);
+ }
+ User user = this.userMapper.selectById(userPosition.getUserId());
+ if (user == null) {
+ return ServerResponse.createByErrorMsg("平仓失败,用户不存在", request);
+ }
+ if (userPosition.getSellOrderId() != null) {
+ return ServerResponse.createByErrorMsg("平仓失败, 订单已平仓", request);
+ }
+ if (1 == userPosition.getIsLock().intValue()) {
+ return ServerResponse.createByErrorMsg("this order is closed " + userPosition.getLockMsg());
+ }
+ BigDecimal nowPrice = priceServices.getNowPrice(userPosition.getStockCode());
+ if (nowPrice.compareTo(new BigDecimal("0")) != 1) {
+ return ServerResponse.createByErrorMsg("报价0,平仓失败,请稍后再试", request);
+ }
+ userPosition.setSellOrderId(GeneratePosition.getPositionId());
+ userPosition.setSellOrderPrice(nowPrice);
+ userPosition.setSellOrderTime(new Date());
+
+ BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(userPosition.getOrderNum()));
+ BigDecimal xsPrice = sellOrderTotel.multiply(siitteBuyFee);
+ userPositionMapper.updateById(userPosition);
+ userAssetsServices.availablebalanceChange(stock.getStockType(),
+ userPosition.getUserId(),
+ EUserAssets.CLOSE_POSITION_RETURN_SECURITY_DEPOSIT,
+ userPosition.getOrderTotalPrice(), "", "");
+ userAssetsServices.availablebalanceChange(stock.getStockType(),
+ userPosition.getUserId(), EUserAssets.HANDLING_CHARGE,
+ xsPrice, "", "");
+
+ PositionProfitVO profitVO = UserPointUtil.getPositionProfitVO(userPosition,
+ priceServices.getNowPrice(userPosition.getStockCode()));
+
+ userAssetsServices.availablebalanceChange(stock.getStockType(),
+ userPosition.getUserId(), EUserAssets.CLOSE_POSITION,
+ profitVO.getAllProfitAndLose(), "", "");
+ return ServerResponse.createBySuccessMsg("平仓成功!", request);
+ }
+
+ public boolean isStockMarketOpen(String stockType){
+ ZoneId zone = ZoneId.of("Asia/Shanghai");
+ LocalTime now = LocalTime.now(zone);
+ if("US".equalsIgnoreCase(stockType)){
+ LocalTime startTime = LocalTime.of(21, 30);
+ LocalTime endTime = LocalTime.of(4, 0);
+ if (now.isAfter(startTime) || now.isBefore(endTime)) {
+ return true;
+ } else {
+ return false;
+ }
+ }else if("IN".equalsIgnoreCase(stockType)){
+ LocalTime instartTime = LocalTime.of(11, 15);
+ LocalTime inendTime = LocalTime.of(17, 30);
+ if (now.isAfter(instartTime) && now.isBefore(inendTime)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ return false;
}
@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");
- }
- User user = iUserService.getCurrentUser(request);
- if(user == null){
- return ServerResponse.createByErrorMsg("Please login");
- }
+ User user = iUserService.getCurrentUser(request);
QueryWrapper<UserPosition> queryWrapper = new QueryWrapper<>();
- queryWrapper.eq("user_id",user.getId());
- queryWrapper.eq("stock_gid",stockType);
+ queryWrapper.eq("user_id", user.getId());
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);
+ sell(userPositionList.get(i).getPositionSn(), 0);
}
- return ServerResponse.createBySuccessMsg("Closed position successfully!");
+ return ServerResponse.createBySuccessMsg("平仓成功!");
}
//用户追加保证金操作
@@ -526,23 +560,38 @@
return ServerResponse.createByErrorMsg("删除失败");
}
+ @Override
+ public UserPositionVO findByPostionSn(String positionSn) {
+ UserPosition userPosition = userPositionMapper.selectOne(new QueryWrapper<UserPosition>().eq("position_sn",positionSn));
+ if(userPosition == null){
+ return null;
+ }
+
+ return UserPointUtil.assembleUserPositionVO(userPosition,priceServices.getNowPrice(userPosition.getStockCode()));
+ }
+
public ServerResponse findMyPositionByCodeAndSpell(String stockCode, String stockSpell,
Integer state, HttpServletRequest request,
int pageNum, int pageSize, String stockType) {
User user = this.iUserService.getCurrentUser(request);
PageHelper.startPage(pageNum, pageSize);
+ List<UserPosition> userPositions;
- List<UserPosition> userPositions = this.userPositionMapper.
+
+ userPositions = userPositionMapper.
findMyPositionByCodeAndSpell(user.getId(),
stockCode, stockSpell,
state, stockType);
+
List<UserPositionVO> userPositionVOS = Lists.newArrayList();
if (userPositions.size() > 0) {
for (UserPosition position : userPositions) {
- UserPositionVO userPositionVO = assembleUserPositionVO(position);
+ UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position, priceServices.getNowPrice(position.getStockCode(),stockType));
+ userPositionVO.setOrderTotalPrice(userPositionVO.getOrderTotalPrice().multiply(new BigDecimal(userPositionVO.getOrderLever())));
+ userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
userPositionVOS.add(userPositionVO);
}
}
@@ -559,33 +608,10 @@
BigDecimal allProfitAndLose = new BigDecimal("0");
BigDecimal allFreezAmt = new BigDecimal("0");
for (UserPosition position : userPositions) {
- Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
- StockListVO stockListVO = StockApi.getStockRealTime(
- stock);
- if (stockListVO.getNowPrice() == null) {
- stockListVO.setNowPrice("0");
- }
- BigDecimal nowPrice = new BigDecimal(stockListVO.getNowPrice());
- if (nowPrice.compareTo(new BigDecimal("0")) != 0) {
- BigDecimal buyPrice = position.getBuyOrderPrice();
- BigDecimal subPrice = nowPrice.subtract(buyPrice);
- BigDecimal profit_and_lose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
- if ("买跌".equals(position.getOrderDirection())) {
- profit_and_lose = profit_and_lose.negate();
- }
- BigDecimal total_fee = position.getOrderFee().add(position.getOrderSpread()).add(position.getOrderStayFee());
- BigDecimal position_profit = profit_and_lose.subtract(total_fee);
- allProfitAndLose = allProfitAndLose.add(position_profit);
- BigDecimal position_freez = position.getOrderTotalPrice().divide(new BigDecimal(position.getOrderLever().intValue()), 2, 4);
- allFreezAmt = allFreezAmt.add(position_freez).add(position.getMarginAdd());
- continue;
- }
- log.info("查询所有持仓单的总盈亏,现价返回0,当前为集合竞价");
- }
- //加上分仓交易保证金
- List<FundsApply> fundsApplyList = fundsApplyMapper.getUserMarginList(userId);
- for (FundsApply fundsApply : fundsApplyList) {
- allFreezAmt = allFreezAmt.add(fundsApply.getMargin());
+ BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+ PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position,nowPrice);
+ allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
+ allFreezAmt.add(positionProfitVO.getProfitAndLose());
}
@@ -597,41 +623,15 @@
@Override
public PositionVO findUserPositionAllProfitAndLose(Integer userId, String stockType) {
- List<UserPosition> userPositions = this.userPositionMapper.findPositionByUserIdAndSellId(userId, stockType);
-
+ List<UserPosition> userPositions = userPositionMapper.findPositionByUserIdAndSellId(userId, stockType);
BigDecimal allProfitAndLose = new BigDecimal("0");
BigDecimal allFreezAmt = new BigDecimal("0");
for (UserPosition position : userPositions) {
- Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
- StockListVO stockListVO = StockApi.getStockRealTime(
- stock);
- if (stockListVO.getNowPrice() == null) {
- stockListVO.setNowPrice("0");
- }
- BigDecimal nowPrice = new BigDecimal(stockListVO.getNowPrice());
- if (nowPrice.compareTo(new BigDecimal("0")) != 0) {
- BigDecimal buyPrice = position.getBuyOrderPrice();
- BigDecimal subPrice = nowPrice.subtract(buyPrice);
- BigDecimal profit_and_lose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
- if ("买跌".equals(position.getOrderDirection())) {
- profit_and_lose = profit_and_lose.negate();
- }
- BigDecimal total_fee = position.getOrderFee().add(position.getOrderSpread()).add(position.getOrderStayFee());
- BigDecimal position_profit = profit_and_lose.subtract(total_fee);
- allProfitAndLose = allProfitAndLose.add(position_profit);
- BigDecimal position_freez = position.getOrderTotalPrice().divide(new BigDecimal(position.getOrderLever().intValue()), 2, 4);
- allFreezAmt = allFreezAmt.add(position_freez).add(position.getMarginAdd());
- continue;
- }
- log.info("查询所有持仓单的总盈亏,现价返回0,当前为集合竞价");
+ BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+ PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position,nowPrice);
+ allProfitAndLose.add(positionProfitVO.getAllProfitAndLose());
+ allFreezAmt.add(positionProfitVO.getProfitAndLose());
}
- //加上分仓交易保证金
- List<FundsApply> fundsApplyList = fundsApplyMapper.getUserMarginList(userId);
- for (FundsApply fundsApply : fundsApplyList) {
- allFreezAmt = allFreezAmt.add(fundsApply.getMargin());
- }
-
-
PositionVO positionVO = new PositionVO();
positionVO.setAllProfitAndLose(allProfitAndLose);
positionVO.setAllFreezAmt(allFreezAmt);
@@ -1088,7 +1088,7 @@
adminPositionVO.setStockPlate(position.getStockPlate());
- PositionProfitVO positionProfitVO = getPositionProfitVO(position);
+ PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position,priceServices.getNowPrice(position.getStockCode()));
adminPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
adminPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
adminPositionVO.setNow_price(positionProfitVO.getNowPrice());
@@ -1130,7 +1130,7 @@
agentPositionVO.setStockPlate(position.getStockPlate());
- PositionProfitVO positionProfitVO = getPositionProfitVO(position);
+ PositionProfitVO positionProfitVO = UserPointUtil.getPositionProfitVO(position,priceServices.getNowPrice(position.getStockCode()));
agentPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
agentPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
agentPositionVO.setNow_price(positionProfitVO.getNowPrice());
@@ -1139,83 +1139,8 @@
return agentPositionVO;
}
- private UserPositionVO assembleUserPositionVO(UserPosition position) {
- UserPositionVO userPositionVO = new UserPositionVO();
- userPositionVO.setId(position.getId());
- userPositionVO.setPositionType(position.getPositionType());
- userPositionVO.setPositionSn(position.getPositionSn());
- userPositionVO.setUserId(position.getUserId());
- userPositionVO.setNickName(position.getNickName());
- userPositionVO.setAgentId(position.getAgentId());
- userPositionVO.setStockName(position.getStockName());
- userPositionVO.setStockCode(position.getStockCode());
- userPositionVO.setStockGid(position.getStockGid());
- userPositionVO.setStockSpell(position.getStockSpell());
- userPositionVO.setBuyOrderId(position.getBuyOrderId());
- userPositionVO.setBuyOrderTime(position.getBuyOrderTime());
- userPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
- userPositionVO.setSellOrderId(position.getSellOrderId());
- userPositionVO.setSellOrderTime(position.getSellOrderTime());
- userPositionVO.setSellOrderPrice(position.getSellOrderPrice());
- userPositionVO.setProfitTargetPrice(position.getProfitTargetPrice());
- userPositionVO.setStopTargetPrice(position.getStopTargetPrice());
- userPositionVO.setOrderDirection(position.getOrderDirection());
- userPositionVO.setOrderNum(position.getOrderNum());
- userPositionVO.setOrderLever(position.getOrderLever());
- userPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
- userPositionVO.setOrderFee(position.getOrderFee());
- userPositionVO.setOrderSpread(position.getOrderSpread());
- userPositionVO.setOrderStayFee(position.getOrderStayFee());
- userPositionVO.setOrderStayDays(position.getOrderStayDays());
- userPositionVO.setMarginAdd(position.getMarginAdd());
- userPositionVO.setStockPlate(position.getStockPlate());
- userPositionVO.setSpreadRatePrice(position.getSpreadRatePrice());
-
- PositionProfitVO positionProfitVO = getPositionProfitVO(position);
- userPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
- userPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
- userPositionVO.setNow_price(positionProfitVO.getNowPrice());
- return userPositionVO;
- }
-
- public PositionProfitVO getPositionProfitVO(UserPosition position) {
- BigDecimal profitAndLose = new BigDecimal("0");
- BigDecimal allProfitAndLose = new BigDecimal("0");
- String nowPrice = "";
-
- if (position.getSellOrderId() != null) {
-
- BigDecimal subPrice = position.getSellOrderPrice().subtract(position.getBuyOrderPrice());
- profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
- if ("买跌".equals(position.getOrderDirection())) {
- profitAndLose = profitAndLose.negate();
- }
- allProfitAndLose = profitAndLose.subtract(position.getOrderFee()).subtract(position.getOrderSpread()).subtract(position.getOrderStayFee()).subtract(position.getSpreadRatePrice());
- } else {
- StockListVO stockListVO = new StockListVO();
- StockCoin stockCoin = new StockCoin();
- Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
- stockListVO = StockApi.getStockRealTime(stock);
- nowPrice = stockListVO.getNowPrice();
- if (nowPrice == null) {
- nowPrice = String.valueOf(0);
- }
- BigDecimal subPrice = (new BigDecimal(nowPrice)).subtract(position.getBuyOrderPrice());
- profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum().intValue()));
- if ("买跌".equals(position.getOrderDirection())) {
- profitAndLose = profitAndLose.negate();
- }
- //总盈亏= 浮动盈亏 – 手续费 – 印花税 – 留仓费 – 点差费
- allProfitAndLose = profitAndLose.subtract(position.getOrderFee()).subtract(position.getOrderSpread()).subtract(position.getOrderStayFee()).subtract(position.getSpreadRatePrice());
- }
- PositionProfitVO positionProfitVO = new PositionProfitVO();
- positionProfitVO.setProfitAndLose(profitAndLose);
- positionProfitVO.setAllProfitAndLose(allProfitAndLose);
- positionProfitVO.setNowPrice(nowPrice);
- return positionProfitVO;
- }
/*股票入仓最新top列表*/
@@ -1224,7 +1149,7 @@
List<UserPositionVO> userPositionVOS = Lists.newArrayList();
if (userPositions.size() > 0) {
for (UserPosition position : userPositions) {
- UserPositionVO userPositionVO = assembleUserPositionVO(position);
+ UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position,priceServices.getNowPrice(position.getStockCode()));
userPositionVOS.add(userPositionVO);
}
}
@@ -1241,7 +1166,7 @@
List<UserPositionVO> userPositionVOS = Lists.newArrayList();
UserPositionVO userPositionVO = null;
if (position != null) {
- userPositionVO = assembleUserPositionVO(position);
+ userPositionVO = UserPointUtil.assembleUserPositionVO(position,priceServices.getNowPrice(position.getStockCode()));
}
userPositionVOS.add(userPositionVO);
@@ -1264,21 +1189,25 @@
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::getStockCode, userStockSubscribe.getNewCode()));
+ if(null == stock){
+ return ServerResponse.createByErrorMsg("该新股不存在");
+ }
UserPosition userPosition = new UserPosition();
userPosition.setPositionType(1);
userPosition.setPositionSn(KeyUtils.getUniqueKey());
userPosition.setUserId(userStockSubscribe.getUserId());
userPosition.setNickName(userStockSubscribe.getRealName());
userPosition.setAgentId(userStockSubscribe.getAgentId());
- userPosition.setStockCode(userStockSubscribe.getNewCode());
+ userPosition.setStockCode(stock.getStockCode());
+ userPosition.setStockSpell(stock.getStockSpell());
userPosition.setStockName(userStockSubscribe.getNewName());
- userPosition.setStockGid(stockSubscribe.getStockType() + userStockSubscribe.getNewCode());
+ userPosition.setStockGid(stock.getStockType());
userPosition.setBuyOrderId(GeneratePosition.getPositionId());
userPosition.setBuyOrderTime(new Date());
@@ -1291,7 +1220,7 @@
userPosition.setIsLock(Integer.valueOf(0));
- userPosition.setOrderLever(10);
+ userPosition.setOrderLever(1);
//递延费特殊处理
@@ -1330,7 +1259,11 @@
int ret = 0;
ret = this.userPositionMapper.insert(userPosition);
-
+ UserAssets userAssets = iUserAssetsServices.assetsByTypeAndUserId(stock.getStockType(), userPosition.getUserId());
+ if(null == userAssets){
+ return ServerResponse.createByErrorMsg("新股转持仓失败");
+ }
+ userAssetsMapper.updateById(userAssets);
if (ret > 0) {
userStockSubscribe.setStatus(5);
userStockSubscribeMapper.update1(userStockSubscribe);
@@ -1734,15 +1667,12 @@
//价格处理
Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", stockDz.getStockCode()));
stockListVO = StockApi.getStockRealTime(stock);
- now_price = new BigDecimal(stockListVO.getNowPrice()).multiply(new BigDecimal(num));
+ now_price = new BigDecimal(stockListVO.getNowPrice()).multiply(stockDz.getDiscount());
if (now_price.compareTo(new BigDecimal("0")) == 0) {
return ServerResponse.createByErrorMsg("Quote 0, please try again later");
}
- UserAssets userAssets = userAssetsServices.selectByUserId(user.getId(), EStockType.IN.getCode());
- if(userAssets.getAvailableBalance().compareTo(now_price) < 0){
- return ServerResponse.createByErrorMsg("Insufficient available balance");
- }
+
double stock_crease = stockListVO.getHcrate().doubleValue();
@@ -1811,20 +1741,20 @@
userPosition.setOrderTotalPrice(buy_amt);
//递延费特殊处理
-// BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
-// BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
- userPosition.setOrderStayFee(new BigDecimal(0));
+ BigDecimal stayFee = userPosition.getOrderTotalPrice().multiply(siteSetting.getStayFee());
+ BigDecimal allStayFee = stayFee.multiply(new BigDecimal(1));
+ userPosition.setOrderStayFee(allStayFee);
userPosition.setOrderStayDays(1);
BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee()).setScale(2, 4);
log.info("用户购买手续费(配资后总资金 * 百分比) = {}", buy_fee_amt);
- userPosition.setOrderFee(new BigDecimal(0));
+ userPosition.setOrderFee(buy_fee_amt);
BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee()).setScale(2, 4);
log.info("用户购买印花税(配资后总资金 * 百分比) = {}", buy_yhs_amt);
- userPosition.setOrderSpread(new BigDecimal(0));
+ userPosition.setOrderSpread(buy_yhs_amt);
SiteSpread siteSpread = iSiteSpreadService.findSpreadRateOne(new BigDecimal(stock_crease), buy_amt, stockDz.getStockCode(), now_price);
BigDecimal spread_rate_amt = new BigDecimal("0");
@@ -1865,11 +1795,6 @@
}
//核算代理收入-入仓手续费
iAgentAgencyFeeService.AgencyFeeIncome(1, userPosition.getPositionSn());
-
- userAssets.setAvailableBalance(userAssets.getAvailableBalance().subtract(now_price));
- userAssetsMapper.updateById(userAssets);
-
-
log.info("【用户交易下单】保存持仓记录成功");
} else {
log.error("用户交易下单】保存持仓记录出错");
@@ -1890,6 +1815,162 @@
}
+
+ @Override
+ @Transactional
+ public void stockConstraint(List<UserPosition> list) {
+ SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
+
+ for (UserPosition position : list) {
+ Stock stock = stockMapper.selectOne(new LambdaQueryWrapper<Stock>().eq(Stock::getStockCode, position.getStockCode()));
+ UserAssets userAssets = userAssetsMapper.selectOne(new LambdaQueryWrapper<UserAssets>()
+ .eq(UserAssets::getUserId, position.getUserId())
+ .eq(UserAssets::getAccectType, stock.getStockType())
+ );
+ if(userAssets.getAmountToBeCovered().compareTo(BigDecimal.ZERO) > 0){
+ continue;
+ }
+ //平仓检查
+ Result result = getResult(position);
+ if (result == null) continue;
+
+ Integer liquidation = 0;
+ liquidation = isLiquidation(position, result.signum, result.profit, liquidation);
+ if(liquidation != 0){
+ extracted(position, result.nowPrice, result.stock,liquidation);
+ }
+ }
+ }
+
+ private Result getResult(UserPosition position) {
+ // 检查订单是否存在
+ if (position == null) {
+ log.info("订单不存在,订单id: {}", position.getId());
+ return null;
+ }
+
+ // 检查用户是否存在
+ User user = this.userMapper.selectById(position.getUserId());
+ if (user == null) {
+ log.info("用户不存在,订单id: {}", position.getId());
+ return null;
+ }
+
+
+ //判断订单
+ if (1 == position.getIsLock().intValue()) {
+ log.info("订单已终止,订单id: {}", position.getId());
+ return null;
+ }
+
+ Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("stock_code", position.getStockCode()));
+
+
+ BigDecimal nowPrice = priceServices.getNowPrice(position.getStockCode());
+
+
+ //判断订单是否已到强制平仓价格
+ BigDecimal purchaseAmount = position.getBuyOrderPrice().multiply(new BigDecimal(position.getOrderNum()));// 买入价总额
+ BigDecimal nowPriceAmount = nowPrice.multiply(new BigDecimal(position.getOrderNum())); // 现价总额
+
+ BigDecimal profit = nowPriceAmount.subtract(purchaseAmount);//利润
+ int signum = profit.signum(); // -1, 0, 1,分别表示 负数、零、正数
+ Result result = new Result(stock, nowPrice, profit, signum);
+ return result;
+ }
+
+ private static class Result {
+ public final Stock stock;//股票
+ public final BigDecimal nowPrice;//现价
+ public final BigDecimal profit;//利润
+ public final int signum;// -1, 0, 1,分别表示 负数、零、正数
+
+ public Result(Stock stock, BigDecimal nowPrice, BigDecimal profit, int signum) {
+ this.stock = stock;
+ this.nowPrice = nowPrice;
+ this.profit = profit;
+ this.signum = signum;
+ }
+ }
+
+ //判断平仓
+ 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){
+ //止损
+ if(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) <= 0){
+ //强制平仓
+ 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(null != position.getStopTargetPrice() && nowPrice.compareTo(position.getStopTargetPrice()) >= 0){
+ //强制平仓
+ 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;
+ }
+ }
+ }
+ return liquidation;
+ }
+
+ //平仓
+ private void extracted(UserPosition position, BigDecimal nowPrice, Stock stock,Integer liquidation) {
+ //-1强平 0未触发 1止损强平 2止盈强平
+ BigDecimal sellOrderTotel = nowPrice.multiply(new BigDecimal(position.getOrderNum()));
+ SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
+ // 手续费率
+ BigDecimal xsPrice = sellOrderTotel.multiply(siteSetting.getForceStopFee());//手续费
+ // 更新订单信息
+ 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(), "", "");
+ }
+ log.info("强制平仓成功,订单id: {}", position.getId());
+ }
+
}
--
Gitblit v1.9.3