import { getRateValue, getCostByQuantity, getQuantityByCost } from "@utils/contractRules"; import { toDefaultNumber, formatFloor } from "@utils/FormatNumber"; import { PositionSideEnum } from "@shared/types"; export const _DEFAULT = { buy: "0", sell: "0", show: false }; type numType = string | number; /** * 计算成本和数量 * @param qty * @param sliderValue * @param maxBuyQty * @param maxSellQty * @param baseOn * @param buyPrice * @param sellPrice * @param leverage * @param takerRate * @param isClose */ export const getCostAndQuantity = ( qty: numType, sliderValue: number, maxBuyQty: numType | undefined, maxSellQty: numType | undefined, baseOn: boolean, buyPrice: numType, sellPrice: numType, leverage: numType, takerRate: numType, isClose: boolean ) => { let buyQuantity = 0, sellQuantity = 0, buyCost = 0, sellCost = 0; const useRate = toDefaultNumber(sliderValue) > 0; const numQuantity = toDefaultNumber(qty); maxBuyQty = toDefaultNumber(maxBuyQty); maxSellQty = toDefaultNumber(maxSellQty); // 数量 if (baseOn) { if (useRate) { buyQuantity = getRateValue({ rate: sliderValue, max: maxBuyQty }); sellQuantity = getRateValue({ rate: sliderValue, max: maxSellQty }); } else { buyQuantity = numQuantity; sellQuantity = numQuantity; } if (!isClose) { // 按数量计算成本 buyCost = getCostByQuantity({ price: buyPrice, quantity: buyQuantity, leverage, takerFee: takerRate }); sellCost = getCostByQuantity({ price: sellPrice, quantity: sellQuantity, leverage, takerFee: takerRate }); } } else { // 按成本 buyCost = numQuantity; sellCost = numQuantity; // 按成本计算数量 buyQuantity = getQuantityByCost({ balance: buyCost, price: buyPrice, takerFee: takerRate, leverage }); sellQuantity = getQuantityByCost({ balance: sellCost, price: sellPrice, takerFee: takerRate, leverage }); } return { buyCost, sellCost, buyQuantity, sellQuantity }; }; /** * 获取positionSide类型 * @param isBuy * @param isClose * @returns */ export const getPositionSide = (isBuy: boolean, isClose: boolean) => { // 空 let positionSide = isClose ? PositionSideEnum.Long : PositionSideEnum.Short; // 多 if (isBuy) { positionSide = isClose ? PositionSideEnum.Short : PositionSideEnum.Long; } return positionSide; }; export const getPositionSideWithSideText = (isClose: boolean) => { return { buy: isClose ? "平空" : "开多", sell: isClose ? "平多" : "开空" }; }; /** * 格式化资产,因为资产会为负数,所以要做max(0, avb)操作 * @param avb 资产 * @param scale 精度 * @returns */ export const formatAvbBalance = (avb: unknown, scale: number) => { const avbBalance = Math.max(0, toDefaultNumber(avb)); return toDefaultNumber(formatFloor(avbBalance, scale)); };