From bf6c08e0b9f18cca48cc616729387e5885d067f2 Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Sun, 02 Mar 2025 18:08:19 +0800
Subject: [PATCH] 项目提交
---
trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java | 335 ++++++++++++++++++++++++++++++++++++++++---------------
1 files changed, 242 insertions(+), 93 deletions(-)
diff --git a/trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java b/trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java
index 3a38af1..0cbb865 100644
--- a/trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java
+++ b/trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java
@@ -1,8 +1,10 @@
package com.yami.trading.service.contract;
import cn.hutool.core.collection.CollectionUtil;
+import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -19,18 +21,19 @@
import com.yami.trading.common.constants.Constants;
import com.yami.trading.common.constants.ContractRedisKeys;
import com.yami.trading.common.constants.TipConstants;
-import com.yami.trading.common.util.DateUtils;
-import com.yami.trading.common.util.RandomUtil;
-import com.yami.trading.common.util.RedisUtil;
-import com.yami.trading.common.util.StringUtils;
+import com.yami.trading.common.exception.YamiShopBindException;
+import com.yami.trading.common.util.*;
+import com.yami.trading.service.StrongLevelCalculationService;
import com.yami.trading.service.data.DataService;
import com.yami.trading.service.system.TipService;
import com.yami.trading.service.user.UserDataService;
import com.yami.trading.service.user.UserService;
import com.yami.trading.service.WalletService;
import com.yami.trading.service.item.ItemService;
+import com.yami.trading.util.ConverterUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
+import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
@@ -42,9 +45,11 @@
import com.yami.trading.dao.contract.ContractOrderMapper;
import org.springframework.web.bind.annotation.RequestParam;
+import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@@ -92,6 +97,9 @@
@Lazy
private ContractApplyOrderService contractApplyOrderService;
+ @Autowired
+ private StrongLevelCalculationService strongLevelCalculationService;
+
public IPage<ContractOrderDTO> listRecord(Page page, ContractOrderQuery query) {
return baseMapper.listRecord(page, query);
}
@@ -127,7 +135,7 @@
public List<ContractOrder> findSubmitted(String partyId, String symbol, String direction, String startTime, String endTime, String symbolType) {
QueryWrapper<ContractOrder> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(StrUtil.isNotBlank(partyId), "party_id", partyId);
- queryWrapper.eq(StrUtil.isNotBlank(symbol), "symbol", symbol);
+// queryWrapper.eq(StrUtil.isNotBlank(symbol), "symbol", symbol);
queryWrapper.eq(StrUtil.isNotBlank(direction), "direction", direction);
queryWrapper.eq("state", "submitted");
List<String> symbols = itemService.findByType(symbolType).stream().map(Item::getSymbol).collect(Collectors.toList());
@@ -218,7 +226,7 @@
public List<Map<String, Object>> getPaged(int pageNo, int pageSize, String partyId, String symbol, String type, String startTime, String endTime, String symbolType) {
QueryWrapper<ContractOrder> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(StrUtil.isNotBlank(partyId), "party_id", partyId);
- queryWrapper.eq(StrUtil.isNotBlank(symbol), "symbol", symbol);
+// queryWrapper.eq(StrUtil.isNotBlank(symbol), "symbol", symbol);
if ("orders".equals(type)) {
queryWrapper.eq("state", "submitted");
} else if ("hisorders".equals(type)) {
@@ -243,61 +251,129 @@
/**
* 平仓,按订单进行平仓
*/
- public ContractOrder saveClose(String partyId, String orderNo) {
+ private final Object lock = new Object();
+
+ @Transactional
+ public ContractOrder saveClose(String partyId, String orderNo,String describe) {
/*
* 平仓
*/
- ContractOrder order = this.findByOrderNo(orderNo);
- if (order == null || !ContractOrder.STATE_SUBMITTED.equals(order.getState())
- || !partyId.equals(order.getPartyId()) || order.getVolume().compareTo(BigDecimal.ZERO) <= 0) {
+ synchronized (lock) {
+ ContractOrder order = this.findByOrderNo(orderNo);
+ if (order == null || !ContractOrder.STATE_SUBMITTED.equals(order.getState())
+ || !partyId.equals(order.getPartyId()) || order.getVolume().compareTo(BigDecimal.ZERO) <= 0) {
+ /**
+ * 状态已改变,退出处理
+ */
+ return null;
+ }
+
/**
- * 状态已改变,退出处理
+ * 收益
*/
- return null;
+ BigDecimal volume = order.getVolume();
+ BigDecimal profit = settle(order, order.getVolume());
+
+ Wallet wallet = walletService.findByUserId(order.getPartyId());
+
+ if (wallet.getMoney().add(profit).compareTo(BigDecimal.ZERO) < 0) {
+ // 如果结果是负数,就归零
+ if (wallet.getMoney().compareTo(BigDecimal.ZERO) < 0) {
+ profit = BigDecimal.ZERO;
+ }
+ }
+
+ walletService.updateMoney(order.getSymbol(), partyId, profit, BigDecimal.ZERO,
+ Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_CLOSE, describe+"平仓,平仓合约数[" + volume + "],订单号[" + order.getOrderNo() + "]");
+ order.setState(ContractOrder.STATE_CREATED);
+ order.setVolume(BigDecimal.ZERO);
+ order.setDeposit(BigDecimal.ZERO);
+ order.setCloseTime(DateUtil.currentSeconds());
+ order.setCloseTimeTs(DateUtil.currentSeconds());
+ update(order);
+
+ /**
+ * 合约产品平仓后添加当前流水setWithdraw_limit_now_amount
+ */
+ User party = userService.getById(order.getPartyId());
+ party.setWithdrawLimitNowAmount(party.getWithdrawLimitNowAmount().add(order.getDepositOpen()));
+ userService.updateById(party);
+ if (ObjectUtils.isEmpty(order.getCloseAvgPrice())) {
+ order.setCloseAvgPrice(BigDecimal.ZERO);
+ }
+ return order;
}
+ }
- /**
- * 收益
- */
- BigDecimal volume = order.getVolume();
- BigDecimal profit = settle(order, order.getVolume());
-// if (profit > 0) {
- Wallet wallet = walletService.findByUserId(order.getPartyId());
- BigDecimal amount_before = wallet.getMoney();
+ /**
+ * 全仓强平
+ */
+ private final Object allCloseLock = new Object();
-// wallet.setMoney(Arith.add(wallet.getMoney(), profit));
- if (wallet.getMoney().add(profit).compareTo(BigDecimal.ZERO) < 0) {
- profit = wallet.getMoney().negate();
+ @Transactional
+ public void allClose(String partyId) {
+ synchronized (allCloseLock) {
+ /*
+ * 平仓
+ */
+ //所有订单
+ List<ContractOrder> list = list(new LambdaQueryWrapper<>(ContractOrder.class)
+ .eq(ContractOrder::getState, ContractOrder.STATE_SUBMITTED)
+ .eq(ContractOrder::getPartyId, partyId)
+ );
+ //计算所有亏损
+ BigDecimal finalProfit = BigDecimal.ZERO; // 初始化为 0
+ String symbol = null;
+ String orderNo = null;
+ String volume = null;
+ for (ContractOrder order : list) {
+ /**
+ * 计算收益
+ */
+ BigDecimal earnings = settle(order, order.getVolume());
+ finalProfit = finalProfit.add(earnings);
+
+
+ order.setState(ContractOrder.STATE_CREATED);
+ order.setVolume(BigDecimal.ZERO);
+ order.setDeposit(BigDecimal.ZERO);
+ order.setCloseTime(DateUtil.currentSeconds());
+ order.setCloseTimeTs(DateUtil.currentSeconds());
+ update(order);
+
+ /**
+ * 合约产品平仓后添加当前流水setWithdraw_limit_now_amount
+ */
+ User party = userService.getById(order.getPartyId());
+ party.setWithdrawLimitNowAmount(party.getWithdrawLimitNowAmount().add(order.getDepositOpen()));
+ userService.updateById(party);
+ if (ObjectUtils.isEmpty(order.getCloseAvgPrice())) {
+ order.setCloseAvgPrice(BigDecimal.ZERO);
+ }
+
+ if (StringUtils.isNotEmpty(symbol)) {
+ symbol += "," + order.getSymbol();
+ } else {
+ symbol = order.getSymbol();
+ }
+
+ if (StringUtils.isNotEmpty(orderNo)) {
+ orderNo += "," + order.getOrderNo();
+ } else {
+ orderNo = order.getOrderNo();
+ }
+
+ if (StringUtils.isNotEmpty(volume)) {
+ volume += "," + "订单号:" + order.getOrderNo() + "数量:" + order.getVolumeOpen();
+ } else {
+ volume = "订单号:" + order.getOrderNo() + "数量:" + order.getVolumeOpen();
+ }
+
+ }
+ walletService.updateMoney(symbol, partyId, finalProfit, BigDecimal.ZERO,
+ Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_CLOSE, "强制平仓,平仓合约数" + list.size() + "[" + volume + "],订单号[" + orderNo + "]");
}
-
- walletService.updateMoney(order.getSymbol(), partyId, profit, BigDecimal.ZERO,
- Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_CLOSE, "平仓,平仓合约数[" + volume + "],订单号[" + order.getOrderNo() + "]");
- order.setState(ContractOrder.STATE_CREATED);
- order.setVolume(BigDecimal.ZERO);
- order.setDeposit(BigDecimal.ZERO);
- order.setCloseTime(DateUtil.currentSeconds());
- order.setCloseTimeTs(DateUtil.currentSeconds());
-// List<Realtime> list = this.dataService.realtime(order.getSymbol());
-// // 平仓时候把当前价格先更新回去
-// if (list.size() != 0) {
-// Realtime realtime = list.get(0);
-// BigDecimal close = realtime.getClose();
-// order.setCloseAvgPrice(close);
-// }
- update(order);
-
- /**
- * 合约产品平仓后添加当前流水setWithdraw_limit_now_amount
- */
- User party = userService.getById(order.getPartyId());
- party.setWithdrawLimitNowAmount(party.getWithdrawLimitNowAmount().add(order.getDepositOpen()));
- userService.updateById(party);
- if (ObjectUtils.isEmpty(order.getCloseAvgPrice())) {
- order.setCloseAvgPrice(BigDecimal.ZERO);
- }
- return order;
-
}
/**
@@ -405,10 +481,18 @@
*/
public BigDecimal settle(ContractOrder order, BigDecimal volume) {
/**
- * 平仓比率
+ * 偏差点位
*/
+ List<Realtime> list = this.dataService.realtime(order.getSymbol());
+ if (list.size() == 0) {
+ order.getProfit();
+ }
+ Realtime realtime = list.get(0);
+ BigDecimal close = realtime.getClose();
+ BigDecimal point = close.subtract(order.getTradeAvgPrice());
+ BigDecimal profit = point.multiply(new BigDecimal("0.01")).multiply(order.getVolumeOpen()).setScale(4, BigDecimal.ROUND_DOWN);;
+ BigDecimal rentalProfit = order.getDeposit().add(profit);
BigDecimal rate = volume.divide(order.getVolumeOpen(), 2, RoundingMode.HALF_UP);
- BigDecimal profit = order.getDeposit().add(order.getProfit()).multiply(rate);
order.setAmountClose(order.getAmountClose().add(profit));
order.setVolume(order.getVolume().subtract(volume));
order.setDeposit(order.getDeposit().subtract(order.getDepositOpen().multiply(rate)));
@@ -418,14 +502,91 @@
order.setCloseTimeTs(DateUtil.currentSeconds());
}
- return profit;
+ return rentalProfit;
}
-
-
-
public void saveOpen(ContractApplyOrder applyOrder, Realtime realtime) {
Item item = this.itemService.findBySymbol(applyOrder.getSymbol());
+ ContractOrder f = getOne(new LambdaQueryWrapper<>(ContractOrder.class)
+ .eq(ContractOrder::getPartyId, applyOrder.getPartyId())
+ .eq(ContractOrder::getSymbol, applyOrder.getSymbol())
+ .eq(ContractOrder::getDirection, applyOrder.getDirection())
+ .eq(ContractOrder::getState,"submitted")
+ .last(" limit 1")
+ );
+
+
+ //合并订单
+ if(ObjectUtils.isNotEmpty(f)){
+ //创建订单
+ if(applyOrder.getOrderPriceType().equals("opponent")){//市价单,创建订单在计算和扣款
+ BigDecimal price = ((realtime.getClose().add(f.getTradeAvgPrice()))
+ .divide(new BigDecimal(2))).multiply(BigDecimal.valueOf(item.getFaceValue()));
+ BigDecimal unitAmount = price.setScale(4, RoundingMode.DOWN);
+
+ f.setUnitAmount(unitAmount);
+ f.setDepositOpen(f.getDepositOpen().add(applyOrder.getMoney()));
+ f.setDeposit(f.getDeposit().add(applyOrder.getMoney()));
+ f.setTradeAvgPrice((f.getTradeAvgPrice().add(realtime.getClose())).divide(new BigDecimal(2)));
+
+ BigDecimal fee = BigDecimal.ZERO;
+ if (f.getLeverRate() != null) {
+
+ fee = applyOrder.getDeposit().multiply(f.getLeverRate()).multiply(item.getUnitFee());
+ fee = fee.setScale(4, RoundingMode.DOWN); // 保留两位小数
+ f.setFee(f.getFee().add(fee));
+ }
+ double number = strongLevelCalculationService.countSheets(f.getDepositOpen().doubleValue(), f.getLeverRate().intValue(), 0.01, realtime.getClose().doubleValue());
+ f.setVolumeOpen(new BigDecimal(number));
+ f.setVolume(new BigDecimal(number));
+
+ walletService.updateMoney(f.getSymbol(), f.getPartyId(), BigDecimal.ZERO.subtract(applyOrder.getDeposit()), BigDecimal.ZERO
+ , Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_OPEN, "委托单,订单号[" + f.getOrderNo() + "]"
+ );
+ walletService.updateMoney(f.getSymbol(), f.getPartyId(), BigDecimal.ZERO.subtract(fee), BigDecimal.ZERO
+ , Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_FEE, "委托单,订单号[" + f.getOrderNo() + "]"
+ );
+ }
+ //计算强平价格
+ getStrongPrice(f,item);
+ update(f);
+ refreshOrder(applyOrder, f);
+ }else{
+ //创建订单
+ ContractOrder order = getContractOrder(applyOrder, item);
+ if(applyOrder.getOrderPriceType().equals("opponent")) {//市价单,创建订单在计算和扣款
+ BigDecimal price = ((realtime.getClose().add(order.getTradeAvgPrice()))
+ .divide(new BigDecimal(2))).multiply(BigDecimal.valueOf(item.getFaceValue()));
+ BigDecimal unitAmount = price.setScale(4, RoundingMode.DOWN);
+ order.setUnitAmount(unitAmount);
+ order.setDepositOpen(applyOrder.getMoney());
+ order.setDeposit(applyOrder.getMoney());
+
+ if (order.getLeverRate() != null) {
+ BigDecimal fee = order.getDeposit().multiply(order.getLeverRate()).multiply(item.getUnitFee());
+ fee = fee.setScale(4, RoundingMode.DOWN); // 保留两位小数
+ order.setFee(fee);
+ }
+ double number = strongLevelCalculationService.countSheets(order.getDepositOpen().doubleValue(), order.getLeverRate().intValue(), 0.01, applyOrder.getPrice().doubleValue());
+ order.setVolume(new BigDecimal(number));
+ order.setVolumeOpen(new BigDecimal(number));
+
+ walletService.updateMoney(order.getSymbol(), order.getPartyId(), BigDecimal.ZERO.subtract(order.getDeposit()), BigDecimal.ZERO
+ , Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_OPEN, "委托单,订单号[" + order.getOrderNo() + "]"
+ );
+ walletService.updateMoney(order.getSymbol(), order.getPartyId(), BigDecimal.ZERO.subtract(order.getFee()), BigDecimal.ZERO
+ , Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_FEE, "委托单,订单号[" + order.getOrderNo() + "]"
+ );
+ }
+ //计算强平价格
+ getStrongPrice(order,item);
+ save(order);
+ refreshOrder(applyOrder, order);
+ }
+ }
+
+ @NotNull
+ private static ContractOrder getContractOrder(ContractApplyOrder applyOrder, Item item) {
ContractOrder order = new ContractOrder();
order.setPartyId(applyOrder.getPartyId());
order.setSymbol(applyOrder.getSymbol());
@@ -433,34 +594,16 @@
order.setOrderNo(orderNo);
order.setDirection(applyOrder.getDirection());
order.setLeverRate(applyOrder.getLeverRate());
- order.setVolume(applyOrder.getVolume());
- order.setVolumeOpen(applyOrder.getVolumeOpen());
order.setOrderPriceType(applyOrder.getOrderPriceType());
- order.setUnitAmount(applyOrder.getUnitAmount());
- order.setFee(applyOrder.getFee());
- order.setDeposit(applyOrder.getDeposit());
- order.setDepositOpen(applyOrder.getDeposit());
-
- order.setTradeAvgPrice(realtime.getClose());
+ order.setTradeAvgPrice(applyOrder.getPrice());
order.setStopPriceProfit(applyOrder.getStopPriceProfit());
order.setStopPriceLoss(applyOrder.getStopPriceLoss());
-
order.setPips(item.getPips());
order.setPipsAmount(item.getPipsAmount());
- // 爆仓是爆整个钱包
-// BigDecimal forceClose = BigDecimal.ZERO;
-// BigDecimal base = order.getDepositOpen().multiply(order.getPips()).divide(order.getPipsAmount(), 10, RoundingMode.HALF_UP).divide(order.getVolume(),10, RoundingMode.HALF_UP);
-// if(order.getDirection().equalsIgnoreCase(ContractOrder.DIRECTION_BUY)){
-// forceClose = order.getTradeAvgPrice().subtract(base).setScale(item.getDecimals(), RoundingMode.HALF_UP);
-// }else if(order.getDirection().equalsIgnoreCase(ContractOrder.DIRECTION_SELL)) {
-// forceClose = order.getTradeAvgPrice().add(base).setScale(item.getDecimals(), RoundingMode.HALF_UP);
-// }
-// if(forceClose.compareTo(BigDecimal.ZERO) <0 ){
-// forceClose = BigDecimal.ZERO;
-// }
-// order.setForceClosePrice(forceClose.toPlainString());
- save(order);
+ return order;
+ }
+ private void refreshOrder(ContractApplyOrder applyOrder, ContractOrder order) {
RedisUtil.set(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrderNo(), order);
Map<String, ContractOrder> map = RedisUtil
@@ -508,6 +651,23 @@
}
}
+ private void getStrongPrice(ContractOrder order, Item item) {
+ double faceValue = 0.01; // 合约面值(固定面值不能调整)
+ double maintenanceMarginRate = 0.004; // 维持保证金率(固定不变)
+ //"buy":买(多) "sell":卖(空)
+ if(order.getDirection().equals("buy")){
+ double forceClosePrice = strongLevelCalculationService.calculateLiquidationPrice(order.getDepositOpen().doubleValue(),
+ faceValue, order.getVolumeOpen().doubleValue(), order.getTradeAvgPrice().doubleValue()
+ , maintenanceMarginRate, item.getUnitFee().doubleValue());
+ order.setForceClosePrice(BigDecimal.valueOf(forceClosePrice).toString());
+ }else{
+ double forceClosePrice = strongLevelCalculationService.calculateEmptyLiquidationPrice(order.getDepositOpen().doubleValue(),
+ faceValue, order.getVolumeOpen().doubleValue(), order.getTradeAvgPrice().doubleValue()
+ , maintenanceMarginRate, item.getUnitFee().doubleValue());
+ order.setForceClosePrice(BigDecimal.valueOf(forceClosePrice).toString());
+ }
+ }
+
public ContractApplyOrder saveClose(ContractApplyOrder applyOrder, Realtime realtime, String order_no) {
ContractOrder order = this.findByOrderNo(order_no);
if (order == null || !ContractOrder.STATE_SUBMITTED.equals(order.getState()) || order.getVolume().compareTo(BigDecimal.ZERO) <= 0) {
@@ -528,7 +688,6 @@
BigDecimal profit = this.settle(order, volume);
update(order);
Wallet wallet = this.walletService.findByUserId(order.getPartyId());
- BigDecimal amount_before = wallet.getMoney();
if (wallet.getMoney().add(profit).compareTo(BigDecimal.ZERO) < 0) {
profit = wallet.getMoney().negate();
@@ -614,18 +773,7 @@
map.put("deposit", order.getDeposit());
map.put("deposit_open", order.getDepositOpen());
map.put("change_ratio", order.getChangeRatio());
- /**
- * 收益
- */
-// if (ContractOrder.STATE_SUBMITTED.equals(order.getState())) {
-// map.put("profit",
-// df.format(Arith.sub(
-// Arith.add(Arith.add(order.getAmount_close(), order.getProfit()), order.getDeposit()),
-// order.getDeposit_open())));
-// } else {
-// map.put("profit", df.format(
-// Arith.sub(Arith.add(order.getAmount_close(), order.getDeposit()), order.getDeposit_open())));
-// }
+
if(order.getProfit()!=null){
map.put("profit", order.getProfit().setScale(4, RoundingMode.HALF_UP));
}else{
@@ -633,6 +781,7 @@
}
map.put("volume", order.getVolume());
map.put("volume_open", order.getVolumeOpen());
+ map.put("force_close_rice", order.getForceClosePrice());
return map;
}
@@ -651,7 +800,7 @@
if (!CollectionUtils.isEmpty(findSubmittedContractOrders)) {
for (ContractOrder order : orders) {
if (ContractOrder.STATE_SUBMITTED.equals(order.getState())) {
- saveClose(order.getPartyId().toString(), order.getOrderNo());
+ saveClose(order.getPartyId().toString(), order.getOrderNo(),null);
}
RedisUtil.del(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrderNo());
}
--
Gitblit v1.9.3