新版仿ok交易所-后端
1
dd
2026-05-30 030e1d50c1f643137220f1ecf1d90ce39174204a
trading-order-service/src/main/java/com/yami/trading/service/contract/ContractOrderService.java
@@ -1,5 +1,6 @@
package com.yami.trading.service.contract;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
@@ -9,12 +10,15 @@
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.trading.bean.contract.domain.ContractApplyOrder;
import com.yami.trading.bean.contract.domain.ContractOrderProfit;
import com.yami.trading.bean.syspara.domain.Syspara;
import com.yami.trading.bean.contract.dto.ContractApplyOrderDTO;
import com.yami.trading.bean.contract.dto.ContractOrderDTO;
import com.yami.trading.bean.contract.query.ContractApplyOrderQuery;
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;
@@ -23,6 +27,7 @@
import com.yami.trading.common.constants.TipConstants;
import com.yami.trading.common.exception.YamiShopBindException;
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;
@@ -30,7 +35,9 @@
import com.yami.trading.service.user.UserService;
import com.yami.trading.service.WalletService;
import com.yami.trading.service.item.ItemService;
import com.yami.trading.service.syspara.SysparaService;
import com.yami.trading.util.ConverterUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;
@@ -50,6 +57,10 @@
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@@ -60,9 +71,11 @@
 * @author lucas
 * @version 2023-03-29
 */
@Slf4j
@Service
@Transactional
public class ContractOrderService extends ServiceImpl<ContractOrderMapper, ContractOrder> {
    private static final int FUNDING_SETTLEMENT_INTERVAL_MINUTES = 240;
    private final ConcurrentMap<String, ContractOrder> map = new ConcurrentHashMap<>();
    private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
@@ -98,7 +111,20 @@
    private ContractApplyOrderService contractApplyOrderService;
    @Autowired
    @Lazy
    private ContractOrderCalculationService contractOrderCalculationService;
    @Autowired
    private StrongLevelCalculationService strongLevelCalculationService;
    @Autowired
    MoneyLogService moneyLogService;
    @Autowired
    private SysparaService sysparaService;
    @Autowired
    private ContractPositionModeService contractPositionModeService;
    public IPage<ContractOrderDTO> listRecord(Page page, ContractOrderQuery query) {
        return baseMapper.listRecord(page, query);
@@ -209,7 +235,7 @@
    }
    public ContractOrder findByOrderNoRedis(String orderNo) {
       return  RedisUtil.get(ContractRedisKeys.CONTRACT_ORDERNO + orderNo);
        return  RedisUtil.get(ContractRedisKeys.CONTRACT_ORDERNO + orderNo);
    }
    public ContractOrder findByOrderNo(String orderNo) {
@@ -268,6 +294,8 @@
                return null;
            }
            contractOrderCalculationService.refreshMarkPriceProfit(order);
            /**
             * 收益
             */
@@ -275,12 +303,12 @@
            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;
                }
                }*/
                profit = wallet.getMoney().negate();
            }
            walletService.updateMoney(order.getSymbol(), partyId, profit, BigDecimal.ZERO,
@@ -296,6 +324,9 @@
             * 合约产品平仓后添加当前流水setWithdraw_limit_now_amount
             */
            User party = userService.getById(order.getPartyId());
            if (party.getWithdrawLimitNowAmount() == null) {
                party.setWithdrawLimitNowAmount(BigDecimal.ZERO);
            }
            party.setWithdrawLimitNowAmount(party.getWithdrawLimitNowAmount().add(order.getDepositOpen()));
            userService.updateById(party);
            if (ObjectUtils.isEmpty(order.getCloseAvgPrice())) {
@@ -332,6 +363,7 @@
                 * 计算收益
                 */
                BigDecimal earnings = settle(order, order.getVolume());
                System.out.println("------------------计算收益earnings-------------:"+earnings);
                finalProfit = finalProfit.add(earnings);
@@ -371,9 +403,40 @@
                }
            }
            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);
        //wallet.setMoney(amountBefore.add(money));
        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);
    }
    /**
@@ -385,7 +448,145 @@
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateByIdBuffer(ContractOrder entity) {
        updateProfit(entity);
        map.put(entity.getUuid(), entity);
    }
    public void wrapProfit(ContractOrder contractOrder) {
        if (ContractOrder.STATE_SUBMITTED.equalsIgnoreCase(contractOrder.getState())) {
            ContractOrderProfit cacheProfit = getCacheProfit(contractOrder.getUuid());
            if (cacheProfit != null) {
                contractOrder.setProfit(cacheProfit.getProfit());
                contractOrder.setCloseAvgPrice(cacheProfit.getCloseAvgPrice());
                contractOrder.setForceClosePrice(cacheProfit.getForceClosePrice());
            } else {
                contractOrder.setProfit(BigDecimal.ZERO);
            }
        }
    }
    public ContractOrderProfit getCacheProfit(String uuid) {
        return RedisUtil.get(ContractRedisKeys.CONTRACT_PROFIT_V1 + uuid);
    }
    public void updateProfit(ContractOrder order) {
        if (ContractOrder.STATE_SUBMITTED.equals(order.getState())) {
            RedisUtil.set(ContractRedisKeys.CONTRACT_PROFIT_V1 + order.getUuid(), BeanUtil.copyProperties(order, ContractOrderProfit.class));
            Map<String, ContractOrder> submittedMap =
                    RedisUtil.get(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId());
            if (null == submittedMap) {
                submittedMap = new ConcurrentHashMap<>();
            }
            ContractOrder orderOld = submittedMap.get(order.getOrderNo());
            if (orderOld == null) {
                return;
            }
            orderOld.setCloseAvgPrice(order.getCloseAvgPrice());
            orderOld.setProfit(order.getProfit());
            orderOld.setForceClosePrice(order.getForceClosePrice());
            submittedMap.put(order.getOrderNo(), orderOld);
            RedisUtil.set(ContractRedisKeys.CONTRACT_SUBMITTED_ORDER_PARTY_ID + order.getPartyId(), submittedMap);
            Map<String, BigDecimal> contractAssetsOrder = this.walletService.getMoneyContractByOrder(order);
            Map<String, BigDecimal> contractAssetsOrderOld = this.walletService.getMoneyContractByOrder(orderOld);
            BigDecimal contractAssets = RedisUtil.get(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString());
            if (contractAssets == null) {
                contractAssets = BigDecimal.ZERO;
            }
            BigDecimal contractAssetsDeposit = RedisUtil.get(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString());
            if (contractAssetsDeposit == null) {
                contractAssetsDeposit = BigDecimal.ZERO;
            }
            BigDecimal contractAssetsProfit = RedisUtil.get(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString());
            if (contractAssetsProfit == null) {
                contractAssetsProfit = BigDecimal.ZERO;
            }
            RedisUtil.set(ContractRedisKeys.CONTRACT_ASSETS_PARTY_ID + order.getPartyId().toString(),
                    contractAssets.add(contractAssetsOrder.get("money_contract")).subtract(contractAssetsOrderOld.get("money_contract")));
            RedisUtil.set(ContractRedisKeys.CONTRACT_ASSETS_DEPOSIT_PARTY_ID + order.getPartyId().toString(),
                    contractAssetsDeposit.add(contractAssetsOrder.get("money_contract_deposit")).subtract(contractAssetsOrderOld.get("money_contract_deposit")));
            RedisUtil.set(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + order.getPartyId().toString(),
                    contractAssetsProfit.add(contractAssetsOrder.get("money_contract_profit")).subtract(contractAssetsOrderOld.get("money_contract_profit")));
        }
    }
    /**
     * 累计资金费带来的盈亏(正数表示用户获利):多仓为 -合约价值×费率×次数,空仓为 +合约价值×费率×次数。
     */
    public BigDecimal calculateAccruedFundingPnl(ContractOrder order, BigDecimal markPrice, Date asOf) {
        if (order == null || markPrice == null || asOf == null || order.getCreateTime() == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal vol = defaultZero(order.getVolume());
        if (vol.compareTo(BigDecimal.ZERO) <= 0 || markPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        long periods = countFundingSettlementPoints(
                order.getCreateTime().toInstant(),
                asOf.toInstant(),
                ZoneId.systemDefault(),
                FUNDING_SETTLEMENT_INTERVAL_MINUTES);
        if (periods <= 0) {
            return BigDecimal.ZERO;
        }
        Item item = itemService.findBySymbol(order.getSymbol());
        BigDecimal faceValue = item != null && item.getFaceValue() > 0
                ? BigDecimal.valueOf(item.getFaceValue()) : new BigDecimal("0.01");
        BigDecimal notional = markPrice.multiply(vol).multiply(faceValue);
        BigDecimal rate = getContractFundingRate();
        BigDecimal signed = ContractOrder.DIRECTION_BUY.equalsIgnoreCase(order.getDirection())
                ? rate.negate() : rate;
        return notional.multiply(signed).multiply(BigDecimal.valueOf(periods)).setScale(8, RoundingMode.HALF_UP);
    }
    public BigDecimal getContractFundingRate() {
        try {
            Syspara p = sysparaService.find("funding_fee");
            if (p == null || StringUtils.isEmptyString(p.getSvalue())) {
                return BigDecimal.ZERO;
            }
            return new BigDecimal(p.getSvalue().trim());
        } catch (Exception e) {
            log.warn("parse funding_fee syspara failed", e);
            return BigDecimal.ZERO;
        }
    }
    private static ZonedDateTime nextFundingSettlementStrictlyAfter(ZonedDateTime t, int intervalMinutes) {
        int step = intervalMinutes <= 0 ? 240 : intervalMinutes;
        ZonedDateTime tTrunc = t.withSecond(0).withNano(0);
        ZonedDateTime dayStart = tTrunc.toLocalDate().atStartOfDay(tTrunc.getZone());
        long minutesFromDayStart = ChronoUnit.MINUTES.between(dayStart, tTrunc);
        long slotIndex = minutesFromDayStart / step;
        ZonedDateTime slotStart = dayStart.plusMinutes(slotIndex * step);
        ZonedDateTime next = slotStart;
        while (!next.isAfter(t)) {
            next = next.plusMinutes(step);
        }
        return next;
    }
    private static long countFundingSettlementPoints(Instant open, Instant end, ZoneId zone, int intervalMinutes) {
        if (open == null || end == null || !end.isAfter(open)) {
            return 0;
        }
        int step = intervalMinutes <= 0 ? 240 : intervalMinutes;
        ZonedDateTime zEnd = end.atZone(zone);
        ZonedDateTime cursor = nextFundingSettlementStrictlyAfter(open.atZone(zone), step);
        long cnt = 0;
        while (!cursor.isAfter(zEnd)) {
            cnt++;
            cursor = cursor.plusMinutes(step);
        }
        return cnt;
    }
    private BigDecimal defaultZero(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
    public void update(ContractOrder order) {
@@ -475,23 +676,58 @@
    /**
     * 价差盈亏(与持仓定时计算一致):(平仓价 - 开仓价) × 平仓张数 × 面值,空仓取反
     */
    private BigDecimal calculatePricePnl(ContractOrder order, BigDecimal closePrice, BigDecimal sheets) {
        BigDecimal tradeAvgPrice = order.getTradeAvgPrice() == null ? BigDecimal.ZERO : order.getTradeAvgPrice();
        if (tradeAvgPrice.compareTo(BigDecimal.ZERO) <= 0 || sheets == null || sheets.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        Item item = itemService.findBySymbol(order.getSymbol());
        BigDecimal faceValue = item != null && item.getFaceValue() > 0
                ? BigDecimal.valueOf(item.getFaceValue()) : new BigDecimal("0.01");
        BigDecimal point = closePrice.subtract(tradeAvgPrice);
        BigDecimal pnl = point.multiply(faceValue).multiply(sheets).setScale(4, RoundingMode.DOWN);
        if (!ContractOrder.DIRECTION_BUY.equals(order.getDirection())) {
            pnl = pnl.negate();
        }
        return pnl;
    }
    /**
     * 收益结算,平仓时计算
     *
     * @param closevolume 平仓的张数
     * @param volume 平仓的张数
     */
    public BigDecimal settle(ContractOrder order, BigDecimal volume) {
        /**
         * 偏差点位
         */
        List<Realtime> list = this.dataService.realtime(order.getSymbol());
        if (list.size() == 0) {
            order.getProfit();
        ContractOrderProfit cacheProfit = getCacheProfit(order.getUuid());
        BigDecimal currentVolume = order.getVolume() == null ? BigDecimal.ZERO : order.getVolume();
        if (currentVolume.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        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 closeRatio = volume.divide(currentVolume, 10, RoundingMode.HALF_UP);
        BigDecimal originProfit = BigDecimal.ZERO;
        if (cacheProfit != null) {
            originProfit = cacheProfit.getProfit();
            if (cacheProfit.getCloseAvgPrice() != null) {
                order.setCloseAvgPrice(cacheProfit.getCloseAvgPrice());
            }
        } else {
            List<Realtime> list = this.dataService.realtime(order.getSymbol());
            if (!list.isEmpty()) {
                originProfit = calculatePricePnl(order, list.get(0).getClose(), currentVolume);
            }
        }
        BigDecimal profit = originProfit.multiply(closeRatio).setScale(4, RoundingMode.DOWN);
        if (null != order.getProfitLossRatio() && order.getProfitLossRatio() > 0) {
            profit = order.getDepositOpen().multiply(new BigDecimal((order.getProfitLossRatio() / 100))).setScale(2, RoundingMode.DOWN);
        }
        order.setProfit(profit);
        BigDecimal rentalProfit = order.getDepositOpen().add(order.getProfit()).add(order.getAddDepositOpen());
        BigDecimal rate = volume.divide(order.getVolumeOpen(), 2, RoundingMode.HALF_UP);
        order.setAmountClose(order.getAmountClose().add(profit));
        order.setVolume(order.getVolume().subtract(volume));
@@ -500,12 +736,192 @@
            order.setState(ContractOrder.STATE_CREATED);
            order.setCloseTime(DateUtil.currentSeconds());
            order.setCloseTimeTs(DateUtil.currentSeconds());
        }
        return rentalProfit;
    }
    /**
     * 单向持仓:反向开仓前先按张数平掉对向持仓,释放保证金后再开剩余仓位。
     *
     * @return 对冲后仍需新开仓的张数
     */
    private BigDecimal netOppositePositions(ContractApplyOrder applyOrder, Realtime realtime, BigDecimal openVolume) {
        if (openVolume == null || openVolume.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        String oppositeDirection = ContractOrder.DIRECTION_BUY.equals(applyOrder.getDirection())
                ? ContractOrder.DIRECTION_SELL
                : ContractOrder.DIRECTION_BUY;
        List<ContractOrder> oppositeList = findSubmitted(
                applyOrder.getPartyId(), applyOrder.getSymbol(), oppositeDirection);
        if (CollectionUtil.isEmpty(oppositeList)) {
            return openVolume;
        }
        BigDecimal remainingOpenVolume = openVolume;
        for (ContractOrder opposite : oppositeList) {
            if (remainingOpenVolume.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
            if (opposite.getVolume() == null || opposite.getVolume().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            if (!ContractLock.add(opposite.getOrderNo())) {
                continue;
            }
            try {
                BigDecimal closeVolume = remainingOpenVolume.min(opposite.getVolume());
                contractOrderCalculationService.refreshMarkPriceProfit(opposite);
                BigDecimal profit = settle(opposite, closeVolume);
                update(opposite);
                Wallet wallet = walletService.findByUserId(applyOrder.getPartyId());
                if (wallet.getMoney().add(profit).compareTo(BigDecimal.ZERO) < 0) {
                    profit = wallet.getMoney().negate();
                }
                walletService.updateMoney(opposite.getSymbol(), applyOrder.getPartyId(), profit, BigDecimal.ZERO,
                        Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT,
                        Constants.MONEYLOG_CONTENT_CONTRACT_CLOSE,
                        "反手对冲平仓,平仓合约数[" + closeVolume + "],订单号[" + opposite.getOrderNo() + "]");
                if (ContractOrder.STATE_CREATED.equals(opposite.getState())) {
                    User party = userService.getById(opposite.getPartyId());
                    if (party != null) {
                        if (party.getWithdrawLimitNowAmount() == null) {
                            party.setWithdrawLimitNowAmount(BigDecimal.ZERO);
                        }
                        party.setWithdrawLimitNowAmount(party.getWithdrawLimitNowAmount().add(opposite.getDepositOpen()));
                        userService.updateById(party);
                    }
                    userDataService.saveClose(opposite);
                    User partyUser = userService.getById(opposite.getPartyId());
                    if (partyUser != null && Constants.SECURITY_ROLE_MEMBER.equals(partyUser.getRoleName())) {
                        tipService.deleteTip(opposite.getUuid().toString());
                    }
                }
                remainingOpenVolume = remainingOpenVolume.subtract(closeVolume);
            } finally {
                ContractLock.remove(opposite.getOrderNo());
            }
        }
        return remainingOpenVolume;
    }
    /**
     * 反向开仓完全被对向持仓对冲,无需再开新仓。
     */
    private void completeNettedApplyOrder(ContractApplyOrder applyOrder,
                                          BigDecimal originalDeposit, BigDecimal originalFee) {
        applyOrder.setVolume(BigDecimal.ZERO);
        applyOrder.setState(ContractApplyOrder.STATE_CREATED);
        contractApplyOrderService.updateById(applyOrder);
        if (ContractApplyOrder.ORDER_PRICE_TYPE_LIMIT.equals(applyOrder.getOrderPriceType())) {
            BigDecimal refund = defaultZero(originalDeposit).add(defaultZero(originalFee));
            if (refund.compareTo(BigDecimal.ZERO) > 0) {
                walletService.updateMoney(applyOrder.getSymbol(), applyOrder.getPartyId(), refund, BigDecimal.ZERO,
                        Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT,
                        Constants.MONEYLOG_CONTENT_CONTRACT_CONCEL,
                        "反手完全对冲,退回保证金,订单号[" + applyOrder.getOrderNo() + "]");
            }
        }
    }
    /**
     * 部分对冲后,按剩余比例调整委托单保证金/手续费;限价单退回多扣部分。
     */
    private void adjustApplyOrderAfterPartialNet(ContractApplyOrder applyOrder,
                                                 BigDecimal originalVolume,
                                                 BigDecimal remainingVolume,
                                                 BigDecimal originalMoney,
                                                 BigDecimal originalDeposit,
                                                 BigDecimal originalFee) {
        BigDecimal ratio = remainingVolume.divide(originalVolume, 10, RoundingMode.HALF_UP);
        BigDecimal remainingMoney = originalMoney.multiply(ratio).setScale(4, RoundingMode.DOWN);
        BigDecimal remainingDeposit = defaultZero(originalDeposit).multiply(ratio).setScale(4, RoundingMode.DOWN);
        BigDecimal remainingFee = defaultZero(originalFee).multiply(ratio).setScale(4, RoundingMode.DOWN);
        if (ContractApplyOrder.ORDER_PRICE_TYPE_LIMIT.equals(applyOrder.getOrderPriceType())) {
            BigDecimal refund = defaultZero(originalDeposit).subtract(remainingDeposit)
                    .add(defaultZero(originalFee).subtract(remainingFee));
            if (refund.compareTo(BigDecimal.ZERO) > 0) {
                walletService.updateMoney(applyOrder.getSymbol(), applyOrder.getPartyId(), refund, BigDecimal.ZERO,
                        Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT,
                        Constants.MONEYLOG_CONTENT_CONTRACT_CONCEL,
                        "反手部分对冲,退回多余保证金,订单号[" + applyOrder.getOrderNo() + "]");
            }
        }
        applyOrder.setVolume(remainingVolume);
        applyOrder.setVolumeOpen(remainingVolume);
        applyOrder.setMoney(remainingMoney);
        applyOrder.setDeposit(remainingDeposit);
        applyOrder.setFee(remainingFee);
    }
    private void applyLimitOpenToOrder(ContractOrder order, ContractApplyOrder applyOrder) {
        order.setUnitAmount(applyOrder.getUnitAmount());
        order.setDepositOpen(applyOrder.getDeposit());
        order.setDeposit(applyOrder.getDeposit());
        order.setFee(defaultZero(applyOrder.getFee()));
        order.setVolume(applyOrder.getVolume());
        order.setVolumeOpen(applyOrder.getVolumeOpen());
        order.setTradeAvgPrice(applyOrder.getPrice());
    }
    private void mergeLimitOpenToPosition(ContractOrder position, ContractApplyOrder applyOrder, Item item) {
        position.setDepositOpen(position.getDepositOpen().add(applyOrder.getDeposit()));
        position.setDeposit(position.getDeposit().add(applyOrder.getDeposit()));
        position.setFee(defaultZero(position.getFee()).add(defaultZero(applyOrder.getFee())));
        position.setLeverRate(applyOrder.getLeverRate());
        double number = strongLevelCalculationService.countSheets(
                position.getDepositOpen().doubleValue(),
                applyOrder.getLeverRate().intValue(),
                0.01,
                applyOrder.getPrice().doubleValue());
        position.setVolumeOpen(new BigDecimal(number));
        position.setVolume(new BigDecimal(number));
        BigDecimal price = applyOrder.getPrice().multiply(BigDecimal.valueOf(item.getFaceValue()));
        position.setUnitAmount(price.setScale(4, RoundingMode.DOWN));
        BigDecimal avgPrice = position.getTradeAvgPrice().add(applyOrder.getPrice())
                .divide(new BigDecimal(2), 4, RoundingMode.DOWN);
        position.setTradeAvgPrice(avgPrice);
    }
    private void ensureOpponentOpenMargin(ContractApplyOrder applyOrder) {
        BigDecimal cost = defaultZero(applyOrder.getDeposit()).add(defaultZero(applyOrder.getFee()));
        BigDecimal available = contractApplyOrderService.getAvailableOpenMargin(
                applyOrder.getPartyId(), applyOrder.getOrderNo());
        if (available.compareTo(cost) < 0) {
            throw new YamiShopBindException("not sufficient funds");
        }
    }
    public void saveOpen(ContractApplyOrder applyOrder, Realtime realtime) {
        Item item = this.itemService.findBySymbol(applyOrder.getSymbol());
        if (item == null) {
            throw new YamiShopBindException("Parameter Error3");
        }
        // 单向持仓:反向开仓前先平掉对向仓位;双向持仓(默认)允许同币种多空并存
        if (contractPositionModeService.isOneWayMode()) {
            BigDecimal originalVolume = applyOrder.getVolume();
            BigDecimal originalMoney = applyOrder.getMoney();
            BigDecimal originalDeposit = applyOrder.getDeposit();
            BigDecimal originalFee = applyOrder.getFee();
            BigDecimal remainingVolume = netOppositePositions(applyOrder, realtime, originalVolume);
            if (remainingVolume.compareTo(BigDecimal.ZERO) <= 0) {
                completeNettedApplyOrder(applyOrder, originalDeposit, originalFee);
                return;
            }
            if (remainingVolume.compareTo(originalVolume) < 0) {
                adjustApplyOrderAfterPartialNet(applyOrder, originalVolume, remainingVolume,
                        originalMoney, originalDeposit, originalFee);
            }
        }
        if (ContractApplyOrder.ORDER_PRICE_TYPE_OPPONENT.equals(applyOrder.getOrderPriceType())) {
            ensureOpponentOpenMargin(applyOrder);
        }
        ContractOrder f = getOne(new LambdaQueryWrapper<>(ContractOrder.class)
                .eq(ContractOrder::getPartyId, applyOrder.getPartyId())
@@ -534,7 +950,7 @@
                    fee = applyOrder.getDeposit().multiply(f.getLeverRate()).multiply(item.getUnitFee());
                    fee = fee.setScale(4, RoundingMode.DOWN);  // 保留两位小数
                    f.setFee(f.getFee().add(fee));
                    f.setFee(defaultZero(f.getFee()).add(fee));
                }
                double number = strongLevelCalculationService.countSheets(f.getDepositOpen().doubleValue(), applyOrder.getLeverRate().intValue(), 0.01, realtime.getClose().doubleValue());
                f.setVolumeOpen(new BigDecimal(number));
@@ -547,9 +963,11 @@
                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() + "]"
                );
            } else {
                mergeLimitOpenToPosition(f, applyOrder, item);
            }
            //计算强平价格
            getStrongPrice(f,item);
            getStrongPrice(f);
            update(f);
            refreshOrder(applyOrder, f);
        }else{
@@ -568,9 +986,10 @@
                    fee = fee.setScale(4, RoundingMode.DOWN);  // 保留两位小数
                    order.setFee(fee);
                }
                double number = strongLevelCalculationService.countSheets(order.getDepositOpen().doubleValue(), order.getLeverRate().intValue(), 0.01, applyOrder.getPrice().doubleValue());
                double number = strongLevelCalculationService.countSheets(order.getDepositOpen().doubleValue(), order.getLeverRate().intValue(), 0.01, realtime.getClose().doubleValue());
                order.setVolume(new BigDecimal(number));
                order.setVolumeOpen(new BigDecimal(number));
                order.setTradeAvgPrice(realtime.getClose());
                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() + "]"
@@ -578,10 +997,12 @@
                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() + "]"
                );
            } else {
                applyLimitOpenToOrder(order, applyOrder);
            }
            //计算强平价格
            getStrongPrice(order,item);
            save(order);
            getStrongPrice(order);
            update(order);
            refreshOrder(applyOrder, order);
        }
    }
@@ -601,6 +1022,7 @@
        order.setStopPriceLoss(applyOrder.getStopPriceLoss());
        order.setPips(item.getPips());
        order.setPipsAmount(item.getPipsAmount());
        order.setLocationType(applyOrder.getLocationType());
        return order;
    }
@@ -652,21 +1074,8 @@
        }
    }
    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());
        }
    private void getStrongPrice(ContractOrder order) {
        order.setForceClosePrice(contractOrderCalculationService.calculateForceClosePriceForOrder(order));
    }
    public ContractApplyOrder saveClose(ContractApplyOrder applyOrder, Realtime realtime, String order_no) {
@@ -738,7 +1147,7 @@
        }
        map.put("name", name);
        map.put("symbol", order.getSymbol());
        map.put("create_time", DateUtils.format(order.getCreateTime(), DateUtils.DF_yyyyMMddHHmmss));
        map.put("create_time", order.getCreateTime());
        map.put("create_time_ts", order.getCreateTimeTs());
        if (order.getCloseTime() != null) {
@@ -771,18 +1180,19 @@
        map.put("amount", order.getVolume().multiply(order.getUnitAmount()));
        map.put("amount_open", order.getVolumeOpen().multiply(order.getUnitAmount()));
        map.put("fee", order.getFee());
        map.put("deposit", order.getDeposit());
        map.put("deposit_open", order.getDepositOpen());
        map.put("change_ratio", order.getChangeRatio());
        map.put("deposit", order.getDeposit().add(order.getAddDepositOpen()));
        map.put("deposit_open", order.getDepositOpen().add(order.getAddDepositOpen()));
        map.put("change_ratio", order.getChangeRatio().setScale(2, RoundingMode.HALF_UP));
        if(order.getProfit()!=null){
            map.put("profit", order.getProfit().setScale(4, RoundingMode.HALF_UP));
            map.put("profit", order.getProfit().setScale(2, RoundingMode.HALF_UP));
        }else{
            map.put("profit", order.getProfit());
        }
        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;
    }
@@ -812,4 +1222,18 @@
            RedisUtil.del(ContractRedisKeys.CONTRACT_ASSETS_PROFIT_PARTY_ID + partyId);
        }
    }
    public void addDepositOpen(ContractOrder order, BigDecimal addDepositOpen) {
        Wallet wallet = walletService.findByUserId(order.getPartyId());
        BigDecimal amountBefore = wallet.getMoney();
        if (amountBefore.compareTo(addDepositOpen) < 0) {
            throw new YamiShopBindException("not sufficient funds");
        }
        order.setAddDepositOpen(order.getAddDepositOpen().add(addDepositOpen));
        walletService.updateMoney(order.getSymbol(), order.getPartyId(), BigDecimal.ZERO.subtract(addDepositOpen), BigDecimal.ZERO
                , Constants.MONEYLOG_CATEGORY_CONTRACT, Constants.WALLET_USDT, Constants.MONEYLOG_CONTENT_CONTRACT_ADD, "委托单追加保证金,订单号[" + order.getOrderNo() + "]"
        );
        update(order);
    }
}