新版仿ok交易所-后端
1
zj
2025-07-04 a2dc849bc20bffaa4ad45d68e401d3892ace24b3
trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java
@@ -1,6 +1,7 @@
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;
@@ -14,6 +15,7 @@
import com.yami.trading.bean.contract.query.ContractOrderQuery;
import com.yami.trading.bean.data.domain.Realtime;
import com.yami.trading.bean.item.domain.Item;
import com.yami.trading.bean.model.MoneyLog;
import com.yami.trading.bean.model.User;
import com.yami.trading.bean.model.UserData;
import com.yami.trading.bean.model.Wallet;
@@ -21,10 +23,8 @@
import com.yami.trading.common.constants.ContractRedisKeys;
import com.yami.trading.common.constants.TipConstants;
import com.yami.trading.common.exception.YamiShopBindException;
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.util.*;
import com.yami.trading.service.MoneyLogService;
import com.yami.trading.service.StrongLevelCalculationService;
import com.yami.trading.service.data.DataService;
import com.yami.trading.service.system.TipService;
@@ -32,8 +32,10 @@
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;
@@ -45,6 +47,7 @@
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;
@@ -98,6 +101,9 @@
    @Autowired
    private StrongLevelCalculationService strongLevelCalculationService;
    @Autowired
    MoneyLogService moneyLogService;
    public IPage<ContractOrderDTO> listRecord(Page page, ContractOrderQuery query) {
        return baseMapper.listRecord(page, query);
@@ -370,9 +376,39 @@
                }
            }
            walletService.updateMoney(symbol, partyId, finalProfit, BigDecimal.ZERO,
                    Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_CLOSE, "强制平仓,平仓合约数" + list.size() + "[" + volume + "],订单号[" + orderNo + "]");
            updateMoney(symbol, partyId, finalProfit, BigDecimal.ZERO,
                    Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MANDATORY_LIQUIDATION_CONTRACT_CLOSE, "强制平仓,平仓合约数" + list.size() + "[" + volume + "],订单号[" + orderNo + "]");
        }
    }
    @Transactional
    public void updateMoney(String symbol, String userId, BigDecimal money, BigDecimal amountFee,
                            String category, String walletType, String contentType, String log) {
        Date now = new Date();
        Wallet wallet = walletService.findByUserId(userId);
        BigDecimal amountBefore = wallet.getMoney();
        wallet.setMoney(BigDecimal.ZERO);
        if(wallet.getMoney().compareTo(BigDecimal.ZERO) < 0){
            wallet.setMoney(BigDecimal.ZERO);
        }
        wallet.setUpdateTime(now);
        walletService.updateById(wallet);
        // 账变日志
        MoneyLog moneyLog = new MoneyLog();
        moneyLog.setCreateTime(now);
        moneyLog.setSymbol(symbol);
        moneyLog.setCategory(category);
        moneyLog.setAmountBefore(amountBefore);
        moneyLog.setAmount(money);
        moneyLog.setAmountAfter(wallet.getMoney());
        moneyLog.setUserId(userId);
        moneyLog.setWalletType(walletType);
        moneyLog.setContentType(contentType);
        moneyLog.setLog(log);
        moneyLogService.save(moneyLog);
    }
    /**
@@ -506,6 +542,87 @@
    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)).setScale(4, RoundingMode.DOWN));
                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(), applyOrder.getLeverRate().intValue(), 0.01, realtime.getClose().doubleValue());
                f.setVolumeOpen(new BigDecimal(number));
                f.setVolume(new BigDecimal(number));
                f.setLeverRate(applyOrder.getLeverRate());
                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());
@@ -514,59 +631,16 @@
        order.setDirection(applyOrder.getDirection());
        order.setLeverRate(applyOrder.getLeverRate());
        order.setOrderPriceType(applyOrder.getOrderPriceType());
        order.setTradeAvgPrice(applyOrder.getPrice());
        order.setStopPriceProfit(applyOrder.getStopPriceProfit());
        order.setStopPriceLoss(applyOrder.getStopPriceLoss());
        order.setPips(item.getPips());
        order.setPipsAmount(item.getPipsAmount());
        if(applyOrder.getOrderPriceType().equals("opponent")){//市价单,创建订单在计算和扣款
            BigDecimal unitAmount = applyOrder.getPrice().multiply(BigDecimal.valueOf(item.getFaceValue()));
            unitAmount = unitAmount.setScale(4, RoundingMode.DOWN);
        order.setLocationType(applyOrder.getLocationType());
        return order;
    }
            BigDecimal deposit = unitAmount.multiply(applyOrder.getVolumeOpen()).divide(order.getLeverRate(), 4, RoundingMode.DOWN);
            order.setUnitAmount(unitAmount);
            order.setDepositOpen(deposit);
            order.setDeposit(deposit);
            if (order.getLeverRate() != null) {
                /**
                 * 加上杠杆
                 */
                // 设置订单数量
                order.setVolume(applyOrder.getVolumeOpen());
                BigDecimal fee = order.getDeposit().multiply(order.getLeverRate()).multiply(item.getUnitFee());
                fee = fee.setScale(4, RoundingMode.DOWN);  // 保留两位小数
                order.setFee(fee);
            }
            order.setVolumeOpen(applyOrder.getVolumeOpen());
            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() + "]"
            );
        }
        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());
        }
        save(order);
    private void refreshOrder(ContractApplyOrder applyOrder, ContractOrder order) {
        RedisUtil.set(ContractRedisKeys.CONTRACT_ORDERNO + order.getOrderNo(), order);
        Map<String, ContractOrder> map = RedisUtil
@@ -611,6 +685,26 @@
        User party = this.userService.getById(order.getPartyId());
        if (Constants.SECURITY_ROLE_MEMBER.equals(party.getRoleName())) {
            tipService.saveTip(order.getUuid().toString(), TipConstants.CONTRACT_ORDER);
        }
    }
    private void getStrongPrice(ContractOrder order, Item item) {
        // 获取当前账户余额并加到收益中
        Map<String, Object> moneyAll = walletService.getMoneyAll(order.getPartyId());
        BigDecimal earnings = order.getDepositOpen().add(new BigDecimal(moneyAll.get("money_all_coin").toString()));
        double faceValue = 0.01; // 合约面值(固定面值不能调整)
        double maintenanceMarginRate = 0.004; // 维持保证金率(固定不变)
        //"buy":买(多) "sell":卖(空)
        if(order.getDirection().equals("buy")){
            double forceClosePrice = strongLevelCalculationService.calculateLiquidationPrice(earnings.doubleValue(),
                    faceValue, order.getVolumeOpen().doubleValue(), order.getTradeAvgPrice().doubleValue()
                    , maintenanceMarginRate, item.getUnitFee().doubleValue());
            order.setForceClosePrice(BigDecimal.valueOf(forceClosePrice).toString());
        }else{
            double forceClosePrice = strongLevelCalculationService.calculateEmptyLiquidationPrice(earnings.doubleValue(),
                    faceValue, order.getVolumeOpen().doubleValue(), order.getTradeAvgPrice().doubleValue()
                    , maintenanceMarginRate, item.getUnitFee().doubleValue());
            order.setForceClosePrice(BigDecimal.valueOf(forceClosePrice).toString());
        }
    }
@@ -728,6 +822,7 @@
        map.put("volume", order.getVolume());
        map.put("volume_open", order.getVolumeOpen());
        map.put("force_close_rice", order.getForceClosePrice());
        map.put("locationType", order.getLocationType());
        return map;
    }