Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07b4d654b4 | |||
| b65827038f | |||
| d768da72c6 | |||
| 7385efff1a | |||
| 3e2e97e572 | |||
| ae68a33c1e | |||
| deea59fdbf | |||
| b90f86b081 |
@@ -89,8 +89,6 @@ class MarketPollingService(
|
||||
*/
|
||||
private suspend fun checkAndUpdateMissingMarkets() {
|
||||
try {
|
||||
logger.debug("开始检查缺失的市场信息...")
|
||||
|
||||
// 1. 获取所有买入订单的市场ID(去重)
|
||||
val allOrders = copyOrderTrackingRepository.findAll()
|
||||
val marketIds = allOrders.map { it.marketId }.distinct()
|
||||
@@ -99,9 +97,6 @@ class MarketPollingService(
|
||||
logger.debug("没有找到任何订单,跳过市场信息检查")
|
||||
return
|
||||
}
|
||||
|
||||
logger.debug("找到 ${marketIds.size} 个不同的市场ID")
|
||||
|
||||
// 2. 检查哪些市场信息在数据库中缺失
|
||||
val existingMarkets = marketService.marketRepository.findByMarketIdIn(marketIds)
|
||||
val existingMarketIds = existingMarkets.map { it.marketId }.toSet()
|
||||
@@ -113,7 +108,6 @@ class MarketPollingService(
|
||||
}
|
||||
|
||||
if (validMissingMarketIds.isEmpty()) {
|
||||
logger.debug("所有市场信息都已存在,无需更新")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+19
-3
@@ -14,6 +14,8 @@ import com.wrbug.polymarketbot.util.IllegalBigDecimal
|
||||
import com.wrbug.polymarketbot.util.JsonUtils
|
||||
import com.wrbug.polymarketbot.util.toSafeBigDecimal
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.context.ApplicationContext
|
||||
import org.springframework.context.ApplicationContextAware
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import java.math.BigDecimal
|
||||
@@ -30,10 +32,24 @@ class CopyTradingService(
|
||||
private val monitorService: CopyTradingMonitorService,
|
||||
private val jsonUtils: JsonUtils,
|
||||
private val gson: Gson
|
||||
) {
|
||||
|
||||
) : ApplicationContextAware {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyTradingService::class.java)
|
||||
|
||||
private var applicationContext: ApplicationContext? = null
|
||||
|
||||
override fun setApplicationContext(applicationContext: ApplicationContext) {
|
||||
this.applicationContext = applicationContext
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取代理对象,用于解决 @Transactional 自调用问题
|
||||
*/
|
||||
private fun getSelf(): CopyTradingService {
|
||||
return applicationContext?.getBean(CopyTradingService::class.java)
|
||||
?: throw IllegalStateException("ApplicationContext not initialized")
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建跟单配置
|
||||
* 支持两种方式:
|
||||
@@ -331,7 +347,7 @@ class CopyTradingService(
|
||||
*/
|
||||
@Transactional
|
||||
fun updateCopyTradingStatus(request: CopyTradingUpdateStatusRequest): Result<CopyTradingDto> {
|
||||
return updateCopyTrading(
|
||||
return getSelf().updateCopyTrading(
|
||||
CopyTradingUpdateRequest(
|
||||
copyTradingId = request.copyTradingId,
|
||||
enabled = request.enabled
|
||||
|
||||
+21
-4
@@ -23,6 +23,8 @@ import com.wrbug.polymarketbot.service.common.MarketService
|
||||
import com.wrbug.polymarketbot.service.common.PolymarketClobService
|
||||
import com.wrbug.polymarketbot.service.system.TelegramNotificationService
|
||||
import com.wrbug.polymarketbot.util.CryptoUtils
|
||||
import org.springframework.context.ApplicationContext
|
||||
import org.springframework.context.ApplicationContextAware
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import java.math.BigDecimal
|
||||
@@ -51,12 +53,26 @@ open class CopyOrderTrackingService(
|
||||
private val cryptoUtils: CryptoUtils,
|
||||
private val marketService: MarketService, // 市场信息服务
|
||||
private val telegramNotificationService: TelegramNotificationService? = null // 可选,避免循环依赖
|
||||
) {
|
||||
) : ApplicationContextAware {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(CopyOrderTrackingService::class.java)
|
||||
|
||||
// 协程作用域(用于异步发送通知)
|
||||
private val notificationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
private var applicationContext: ApplicationContext? = null
|
||||
|
||||
override fun setApplicationContext(applicationContext: ApplicationContext) {
|
||||
this.applicationContext = applicationContext
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取代理对象,用于解决 @Transactional 自调用问题
|
||||
*/
|
||||
private fun getSelf(): CopyOrderTrackingService {
|
||||
return applicationContext?.getBean(CopyOrderTrackingService::class.java)
|
||||
?: throw IllegalStateException("ApplicationContext not initialized")
|
||||
}
|
||||
|
||||
// 使用 Mutex 保证线程安全(按交易ID锁定)
|
||||
private val tradeMutexMap = ConcurrentHashMap<String, Mutex>()
|
||||
@@ -138,10 +154,11 @@ open class CopyOrderTrackingService(
|
||||
return@withLock Result.success(Unit)
|
||||
}
|
||||
|
||||
// 2. 处理交易逻辑
|
||||
// 2. 处理交易逻辑(通过代理对象调用,确保 @Transactional 生效)
|
||||
val self = getSelf()
|
||||
val result = when (trade.side.uppercase()) {
|
||||
"BUY" -> processBuyTrade(leaderId, trade, source)
|
||||
"SELL" -> processSellTrade(leaderId, trade)
|
||||
"BUY" -> self.processBuyTrade(leaderId, trade, source)
|
||||
"SELL" -> self.processSellTrade(leaderId, trade)
|
||||
else -> {
|
||||
logger.warn("未知的交易方向: ${trade.side}")
|
||||
Result.failure(IllegalArgumentException("未知的交易方向: ${trade.side}"))
|
||||
|
||||
+123
-15
@@ -12,6 +12,8 @@ import com.wrbug.polymarketbot.util.multi
|
||||
import kotlinx.coroutines.*
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent
|
||||
import org.springframework.context.ApplicationContext
|
||||
import org.springframework.context.ApplicationContextAware
|
||||
import org.springframework.context.event.EventListener
|
||||
import org.springframework.context.i18n.LocaleContextHolder
|
||||
import org.springframework.scheduling.annotation.Scheduled
|
||||
@@ -37,11 +39,29 @@ class OrderStatusUpdateService(
|
||||
private val trackingService: CopyOrderTrackingService,
|
||||
private val marketService: MarketService, // 市场信息服务
|
||||
private val telegramNotificationService: TelegramNotificationService?
|
||||
) {
|
||||
) : ApplicationContextAware {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(OrderStatusUpdateService::class.java)
|
||||
|
||||
private val updateScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
// 跟踪上一次更新任务的 Job,防止并发执行
|
||||
@Volatile
|
||||
private var updateJob: Job? = null
|
||||
|
||||
private var applicationContext: ApplicationContext? = null
|
||||
|
||||
override fun setApplicationContext(applicationContext: ApplicationContext) {
|
||||
this.applicationContext = applicationContext
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取代理对象,用于解决 @Transactional 自调用问题
|
||||
*/
|
||||
private fun getSelf(): OrderStatusUpdateService {
|
||||
return applicationContext?.getBean(OrderStatusUpdateService::class.java)
|
||||
?: throw IllegalStateException("ApplicationContext not initialized")
|
||||
}
|
||||
|
||||
// 缓存首次检测到订单详情为 null 的时间戳(订单ID -> 首次检测时间)
|
||||
private val orderNullDetectionTime = ConcurrentHashMap<String, Long>()
|
||||
@@ -60,24 +80,38 @@ class OrderStatusUpdateService(
|
||||
/**
|
||||
* 定时更新订单状态
|
||||
* 每5秒执行一次
|
||||
* 如果上一次任务还在执行,则跳过本次执行,避免并发问题
|
||||
*/
|
||||
@Scheduled(fixedDelay = 5000)
|
||||
fun updateOrderStatus() {
|
||||
updateScope.launch {
|
||||
// 检查上一次任务是否还在执行
|
||||
val previousJob = updateJob
|
||||
if (previousJob != null && previousJob.isActive) {
|
||||
logger.debug("上一次订单状态更新任务还在执行,跳过本次执行")
|
||||
return
|
||||
}
|
||||
|
||||
// 启动新任务并记录 Job
|
||||
updateJob = updateScope.launch {
|
||||
try {
|
||||
// 1. 清理已删除账户的订单
|
||||
cleanupDeletedAccountOrders()
|
||||
val self = getSelf()
|
||||
|
||||
// 1. 清理已删除账户的订单(通过代理对象调用,确保事务生效)
|
||||
self.cleanupDeletedAccountOrders()
|
||||
|
||||
// 2. 检查30秒前创建的订单,如果未成交则删除
|
||||
checkAndDeleteUnfilledOrders()
|
||||
// 2. 检查30秒前创建的订单,如果未成交则删除(通过代理对象调用,确保事务生效)
|
||||
self.checkAndDeleteUnfilledOrders()
|
||||
|
||||
// 3. 更新卖出订单的实际成交价并发送通知(priceUpdated 共用字段)
|
||||
updatePendingSellOrderPrices()
|
||||
// 3. 更新卖出订单的实际成交价并发送通知(priceUpdated 共用字段)(通过代理对象调用,确保事务生效)
|
||||
self.updatePendingSellOrderPrices()
|
||||
|
||||
// 4. 更新买入订单的实际数据并发送通知
|
||||
updatePendingBuyOrders()
|
||||
// 4. 更新买入订单的实际数据并发送通知(通过代理对象调用,确保事务生效)
|
||||
self.updatePendingBuyOrders()
|
||||
} catch (e: Exception) {
|
||||
logger.error("订单状态更新异常: ${e.message}", e)
|
||||
} finally {
|
||||
// 任务完成后清除 Job 引用
|
||||
updateJob = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,7 +140,7 @@ class OrderStatusUpdateService(
|
||||
* 清理已删除账户的订单
|
||||
*/
|
||||
@Transactional
|
||||
private suspend fun cleanupDeletedAccountOrders() {
|
||||
suspend fun cleanupDeletedAccountOrders() {
|
||||
try {
|
||||
// 查询所有卖出记录
|
||||
val allRecords = sellMatchRecordRepository.findAll()
|
||||
@@ -150,7 +184,7 @@ class OrderStatusUpdateService(
|
||||
* 首次检测但加入缓存中30s后还没有成交,则删除
|
||||
*/
|
||||
@Transactional
|
||||
private suspend fun checkAndDeleteUnfilledOrders() {
|
||||
suspend fun checkAndDeleteUnfilledOrders() {
|
||||
try {
|
||||
// 计算30秒前的时间戳
|
||||
val thirtySecondsAgo = System.currentTimeMillis() - 30000
|
||||
@@ -235,6 +269,43 @@ class OrderStatusUpdateService(
|
||||
orderNullDetectionTime.getOrPut(order.buyOrderId) { System.currentTimeMillis() }
|
||||
val currentTime = System.currentTimeMillis()
|
||||
|
||||
// 检查订单是否已经通过订单详情更正过数据并发送过通知
|
||||
if (order.notificationSent) {
|
||||
// 检查是否超过重试时间窗口
|
||||
if (currentTime - firstDetectionTime >= ORDER_NULL_RETRY_WINDOW_MS) {
|
||||
// 超过60秒,将订单状态改为 fully_matched,不再查询
|
||||
logger.info("订单已发送通知且详情为 null 超过60秒,标记为 fully_matched: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
try {
|
||||
val updatedOrder = CopyOrderTracking(
|
||||
id = order.id,
|
||||
copyTradingId = order.copyTradingId,
|
||||
accountId = order.accountId,
|
||||
leaderId = order.leaderId,
|
||||
marketId = order.marketId,
|
||||
side = order.side,
|
||||
outcomeIndex = order.outcomeIndex,
|
||||
buyOrderId = order.buyOrderId,
|
||||
leaderBuyTradeId = order.leaderBuyTradeId,
|
||||
quantity = order.quantity,
|
||||
price = order.price,
|
||||
matchedQuantity = order.matchedQuantity,
|
||||
remainingQuantity = order.remainingQuantity,
|
||||
status = "fully_matched", // 标记为完全匹配
|
||||
notificationSent = order.notificationSent,
|
||||
source = order.source,
|
||||
createdAt = order.createdAt,
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
copyOrderTrackingRepository.save(updatedOrder)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新订单状态失败: orderId=${order.buyOrderId}, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
// 清除缓存,下次重新检测
|
||||
orderNullDetectionTime.remove(order.buyOrderId)
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查订单是否已部分卖出,如果已部分卖出则保留订单用于统计
|
||||
val hasMatchedDetails =
|
||||
sellMatchDetailRepository.findByTrackingId(order.id!!).isNotEmpty()
|
||||
@@ -323,7 +394,7 @@ class OrderStatusUpdateService(
|
||||
* 注意:priceUpdated 现在同时表示价格已更新和通知已发送(共用字段)
|
||||
*/
|
||||
@Transactional
|
||||
private suspend fun updatePendingSellOrderPrices() {
|
||||
suspend fun updatePendingSellOrderPrices() {
|
||||
try {
|
||||
// 查询所有价格未更新的卖出记录(priceUpdated = false 表示未处理)
|
||||
val pendingRecords = sellMatchRecordRepository.findByPriceUpdatedFalse()
|
||||
@@ -566,7 +637,7 @@ class OrderStatusUpdateService(
|
||||
* 查询订单详情获取实际价格和数量,然后发送通知并更新数据库
|
||||
*/
|
||||
@Transactional
|
||||
private suspend fun updatePendingBuyOrders() {
|
||||
suspend fun updatePendingBuyOrders() {
|
||||
try {
|
||||
// 查询所有未发送通知的买入订单
|
||||
val pendingOrders = copyOrderTrackingRepository.findByNotificationSentFalse()
|
||||
@@ -676,6 +747,43 @@ class OrderStatusUpdateService(
|
||||
orderNullDetectionTime.getOrPut(order.buyOrderId) { System.currentTimeMillis() }
|
||||
val currentTime = System.currentTimeMillis()
|
||||
|
||||
// 检查订单是否已经通过订单详情更正过数据并发送过通知
|
||||
if (order.notificationSent) {
|
||||
// 检查是否超过重试时间窗口
|
||||
if (currentTime - firstDetectionTime >= ORDER_NULL_RETRY_WINDOW_MS) {
|
||||
// 超过60秒,将订单状态改为 fully_matched,不再查询
|
||||
logger.info("订单已发送通知且详情为 null 超过60秒,标记为 fully_matched: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
try {
|
||||
val updatedOrder = CopyOrderTracking(
|
||||
id = order.id,
|
||||
copyTradingId = order.copyTradingId,
|
||||
accountId = order.accountId,
|
||||
leaderId = order.leaderId,
|
||||
marketId = order.marketId,
|
||||
side = order.side,
|
||||
outcomeIndex = order.outcomeIndex,
|
||||
buyOrderId = order.buyOrderId,
|
||||
leaderBuyTradeId = order.leaderBuyTradeId,
|
||||
quantity = order.quantity,
|
||||
price = order.price,
|
||||
matchedQuantity = order.matchedQuantity,
|
||||
remainingQuantity = order.remainingQuantity,
|
||||
status = "fully_matched", // 标记为完全匹配
|
||||
notificationSent = order.notificationSent,
|
||||
source = order.source,
|
||||
createdAt = order.createdAt,
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
copyOrderTrackingRepository.save(updatedOrder)
|
||||
} catch (e: Exception) {
|
||||
logger.error("更新订单状态失败: orderId=${order.buyOrderId}, error=${e.message}", e)
|
||||
}
|
||||
}
|
||||
// 清除缓存,下次重新检测
|
||||
orderNullDetectionTime.remove(order.buyOrderId)
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查订单是否已部分卖出,如果已部分卖出则保留订单用于统计
|
||||
val hasMatchedDetails = sellMatchDetailRepository.findByTrackingId(order.id!!).isNotEmpty()
|
||||
if (hasMatchedDetails || order.matchedQuantity > BigDecimal.ZERO) {
|
||||
@@ -712,7 +820,7 @@ class OrderStatusUpdateService(
|
||||
}
|
||||
|
||||
// 超过重试窗口,删除本地订单
|
||||
logger.warn("订单详情为 null 超过重试窗口,删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, 已等待=$((currentTime - firstDetectionTime) / 1000)s")
|
||||
logger.warn("订单详情为 null 超过重试窗口,删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}, 已等待=$((currentTime - firstDetectionTime) / 1000}s")
|
||||
try {
|
||||
copyOrderTrackingRepository.deleteById(order.id!!)
|
||||
logger.info("已删除本地订单: orderId=${order.buyOrderId}, copyOrderTrackingId=${order.id}")
|
||||
|
||||
@@ -40,6 +40,8 @@ const PositionList: React.FC = () => {
|
||||
const [redeemableSummary, setRedeemableSummary] = useState<RedeemablePositionsSummary | null>(null)
|
||||
const [loadingRedeemableSummary, setLoadingRedeemableSummary] = useState(false)
|
||||
const [redeeming, setRedeeming] = useState(false)
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
useEffect(() => {
|
||||
fetchAccounts()
|
||||
@@ -66,6 +68,11 @@ const PositionList: React.FC = () => {
|
||||
fetchRedeemableSummary()
|
||||
}
|
||||
}, [currentPositions, selectedAccountId])
|
||||
|
||||
// 当筛选条件或搜索关键词变化时,重置分页到第一页
|
||||
useEffect(() => {
|
||||
setCurrentPage(1)
|
||||
}, [positionFilter, selectedAccountId, searchKeyword])
|
||||
|
||||
// 获取可赎回仓位统计
|
||||
const fetchRedeemableSummary = async () => {
|
||||
@@ -265,12 +272,12 @@ const PositionList: React.FC = () => {
|
||||
// 本地搜索和筛选过滤
|
||||
const filteredPositions = useMemo(() => {
|
||||
let filtered = basePositions
|
||||
|
||||
|
||||
// 1. 先按账户筛选
|
||||
if (selectedAccountId !== undefined) {
|
||||
filtered = filtered.filter(p => p.accountId === selectedAccountId)
|
||||
}
|
||||
|
||||
|
||||
// 2. 最后按关键词搜索
|
||||
if (searchKeyword.trim()) {
|
||||
const keyword = searchKeyword.trim().toLowerCase()
|
||||
@@ -302,9 +309,16 @@ const PositionList: React.FC = () => {
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
return filtered
|
||||
}, [basePositions, searchKeyword, selectedAccountId])
|
||||
|
||||
// 分页后的数据
|
||||
const paginatedPositions = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * pageSize
|
||||
const endIndex = startIndex + pageSize
|
||||
return filteredPositions.slice(startIndex, endIndex)
|
||||
}, [filteredPositions, currentPage, pageSize])
|
||||
|
||||
const getSideColor = (side: string) => {
|
||||
return side === 'YES' ? 'green' : 'red'
|
||||
@@ -349,14 +363,32 @@ const PositionList: React.FC = () => {
|
||||
if (!isNaN(initialValue)) {
|
||||
totalInitialValue += initialValue
|
||||
}
|
||||
|
||||
// 当前仓位:统计持仓价值
|
||||
// 历史仓位:currentValue 应该为 0(已平仓)
|
||||
if (!isNaN(currentValue)) {
|
||||
totalCurrentValue += currentValue
|
||||
}
|
||||
if (!isNaN(pnl)) {
|
||||
totalPnl += pnl
|
||||
}
|
||||
if (!isNaN(realizedPnl)) {
|
||||
totalRealizedPnl += realizedPnl
|
||||
|
||||
// 对于当前仓位:
|
||||
// - pnl:未实现盈亏(浮动盈亏)
|
||||
// - realizedPnl:已实现盈亏(部分平仓时产生)
|
||||
// 对于历史仓位:
|
||||
// - pnl:总已实现盈亏(包含部分平仓 + 完全平仓)
|
||||
// - realizedPnl:部分平仓的已实现盈亏(可能与 pnl 重复)
|
||||
if (pos.isCurrent) {
|
||||
// 当前仓位:未实现盈亏 + 已实现盈亏
|
||||
if (!isNaN(pnl)) {
|
||||
totalPnl += pnl
|
||||
}
|
||||
if (!isNaN(realizedPnl)) {
|
||||
totalRealizedPnl += realizedPnl
|
||||
}
|
||||
} else {
|
||||
// 历史仓位:pnl 是总已实现盈亏,realizedPnl 可能重复,所以只统计 pnl
|
||||
if (!isNaN(pnl)) {
|
||||
totalRealizedPnl += pnl
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -516,10 +548,10 @@ const PositionList: React.FC = () => {
|
||||
|
||||
// 渲染卡片视图
|
||||
const renderCardView = () => {
|
||||
if (filteredPositions.length === 0) {
|
||||
if (paginatedPositions.length === 0) {
|
||||
return (
|
||||
<Empty
|
||||
description="暂无仓位数据"
|
||||
<Empty
|
||||
description="暂无仓位数据"
|
||||
style={{ padding: '60px 0' }}
|
||||
/>
|
||||
)
|
||||
@@ -527,7 +559,7 @@ const PositionList: React.FC = () => {
|
||||
|
||||
return (
|
||||
<Row gutter={[16, 16]}>
|
||||
{filteredPositions.map((position, index) => {
|
||||
{paginatedPositions.map((position, index) => {
|
||||
const pnlNum = parseFloat(position.pnl || '0')
|
||||
const isProfit = pnlNum >= 0
|
||||
// 只有当前仓位才根据盈亏显示边框颜色
|
||||
@@ -1235,8 +1267,8 @@ const PositionList: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* 合计信息:开仓价值、当前价值、盈亏、已实现盈亏(基于当前筛选后的仓位) */}
|
||||
{filteredPositions.length > 0 && (
|
||||
{/* 合计信息:开仓价值、当前价值、盈亏、已实现盈亏(仅当前仓位显示) */}
|
||||
{filteredPositions.length > 0 && positionFilter === 'current' && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '12px',
|
||||
@@ -1259,13 +1291,11 @@ const PositionList: React.FC = () => {
|
||||
<span>
|
||||
当前价值合计:{' '}
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{positionFilter === 'current'
|
||||
? `${formatUSDC(positionTotals.totalCurrentValue.toString())} USDC`
|
||||
: '-'}
|
||||
{formatUSDC(positionTotals.totalCurrentValue.toString())} USDC
|
||||
</span>
|
||||
</span>
|
||||
<span>
|
||||
盈亏合计:{' '}
|
||||
浮动盈亏合计:{' '}
|
||||
<span
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
@@ -1295,32 +1325,87 @@ const PositionList: React.FC = () => {
|
||||
{(isMobile || viewMode === 'card') ? (
|
||||
<Card loading={loading}>
|
||||
{renderCardView()}
|
||||
{/* 移动端分页 */}
|
||||
{filteredPositions.length > 0 && (
|
||||
<div style={{
|
||||
marginTop: '24px',
|
||||
textAlign: 'center',
|
||||
color: '#999',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
共 {filteredPositions.length} 个仓位{searchKeyword ? `(已过滤)` : ''}
|
||||
</div>
|
||||
<>
|
||||
<div style={{
|
||||
marginTop: '16px',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap',
|
||||
gap: '8px'
|
||||
}}>
|
||||
<div style={{ fontSize: '14px', color: '#666' }}>
|
||||
共 {filteredPositions.length} 个仓位{searchKeyword ? `(已过滤)` : ''}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '8px' }}>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={currentPage === 1}
|
||||
onClick={() => setCurrentPage(currentPage - 1)}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<span style={{ lineHeight: '32px', fontSize: '14px' }}>
|
||||
{currentPage} / {Math.ceil(filteredPositions.length / pageSize)}
|
||||
</span>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={currentPage >= Math.ceil(filteredPositions.length / pageSize)}
|
||||
onClick={() => setCurrentPage(currentPage + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/* 每页条数选择器 */}
|
||||
<div style={{
|
||||
marginTop: '8px',
|
||||
textAlign: 'right',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
<Select
|
||||
value={pageSize}
|
||||
onChange={(value) => {
|
||||
setPageSize(value)
|
||||
setCurrentPage(1)
|
||||
}}
|
||||
size="small"
|
||||
style={{ width: '100px' }}
|
||||
>
|
||||
<Select.Option value={10}>10 条/页</Select.Option>
|
||||
<Select.Option value={20}>20 条/页</Select.Option>
|
||||
<Select.Option value={50}>50 条/页</Select.Option>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<Table
|
||||
dataSource={filteredPositions}
|
||||
columns={columns}
|
||||
rowKey={(record, index) => `${record.accountId}-${record.marketId}-${index}`}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
pageSize: 20,
|
||||
showSizeChanger: !isMobile,
|
||||
showTotal: (total) => `共 ${total} 个仓位${searchKeyword ? `(已过滤)` : ''}`
|
||||
}}
|
||||
scroll={isMobile ? { x: 1500 } : undefined}
|
||||
/>
|
||||
</Card>
|
||||
<Card>
|
||||
<Table
|
||||
dataSource={filteredPositions}
|
||||
columns={columns}
|
||||
rowKey={(record, index) => `${record.accountId}-${record.marketId}-${index}`}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
current: currentPage,
|
||||
pageSize: pageSize,
|
||||
total: filteredPositions.length,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: ['10', '20', '50'],
|
||||
showTotal: (total) => `共 ${total} 个仓位${searchKeyword ? `(已过滤)` : ''}`,
|
||||
onChange: (page, size) => {
|
||||
setCurrentPage(page)
|
||||
if (size !== pageSize) {
|
||||
setPageSize(size)
|
||||
}
|
||||
}
|
||||
}}
|
||||
scroll={isMobile ? { x: 1500 } : undefined}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 出售模态框 */}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* 获取订单详情脚本
|
||||
*
|
||||
* 使用方法:
|
||||
* node scripts/get-order-detail.js <private_key> <order_id>
|
||||
*
|
||||
* 参数说明:
|
||||
* private_key: 钱包私钥(用于签名)
|
||||
* order_id: 订单 ID
|
||||
*
|
||||
* 示例:
|
||||
* node scripts/get-order-detail.js "0x..." "0x123..."
|
||||
*/
|
||||
|
||||
import { Wallet } from '@ethersproject/wallet';
|
||||
import { ClobClient } from '@polymarket/clob-client';
|
||||
|
||||
// Polymarket CLOB 主机地址
|
||||
const HOST = 'https://clob.polymarket.com';
|
||||
const CHAIN_ID = 137; // Polygon 主网
|
||||
|
||||
async function getOrderDetail(privateKey, orderId) {
|
||||
try {
|
||||
console.log('正在初始化钱包...');
|
||||
const wallet = new Wallet(privateKey);
|
||||
console.log(`钱包地址: ${wallet.address}`);
|
||||
|
||||
console.log('\n正在初始化 ClobClient...');
|
||||
const clobClient = new ClobClient(
|
||||
HOST,
|
||||
CHAIN_ID,
|
||||
wallet
|
||||
);
|
||||
|
||||
console.log('\n正在获取或创建 API Key...');
|
||||
try {
|
||||
// 尝试 derive API key(如果已存在)
|
||||
const creds = await clobClient.deriveApiKey();
|
||||
console.log(`✅ API Key 已获取`);
|
||||
console.log(` API Key: ${creds.key.substring(0, 10)}...`);
|
||||
console.log(` Passphrase: ${creds.passphrase.substring(0, 10)}...`);
|
||||
|
||||
// 使用 creds 初始化一个新的 ClobClient 实例用于 L2 认证
|
||||
const authenticatedClient = new ClobClient(
|
||||
HOST,
|
||||
CHAIN_ID,
|
||||
wallet,
|
||||
creds
|
||||
);
|
||||
|
||||
console.log(`\n正在获取订单详情...`);
|
||||
console.log(` 订单 ID: ${orderId}`);
|
||||
|
||||
const orderDetail = await authenticatedClient.getOrder(orderId);
|
||||
|
||||
console.log('\n================ 订单详情 ================');
|
||||
console.log(`订单 ID: ${orderDetail.id}`);
|
||||
console.log(`状态: ${orderDetail.status}`);
|
||||
console.log(`所有者: ${orderDetail.owner}`);
|
||||
console.log(`Maker 地址: ${orderDetail.maker_address}`);
|
||||
console.log(`市场 ID: ${orderDetail.market}`);
|
||||
console.log(`资产 ID: ${orderDetail.asset_id}`);
|
||||
console.log(`方向: ${orderDetail.side}`);
|
||||
console.log(`原始数量: ${orderDetail.original_size}`);
|
||||
console.log(`已匹配数量: ${orderDetail.size_matched}`);
|
||||
console.log(`价格: ${orderDetail.price}`);
|
||||
console.log(`结果: ${orderDetail.outcome}`);
|
||||
console.log(`创建时间: ${new Date(orderDetail.created_at * 1000).toISOString()}`);
|
||||
console.log(`过期时间: ${orderDetail.expiration}`);
|
||||
console.log(`订单类型: ${orderDetail.order_type}`);
|
||||
|
||||
if (orderDetail.associate_trades && orderDetail.associate_trades.length > 0) {
|
||||
console.log(`关联交易数量: ${orderDetail.associate_trades.length}`);
|
||||
console.log(`关联交易 IDs: ${orderDetail.associate_trades.join(', ')}`);
|
||||
}
|
||||
console.log('=========================================\n');
|
||||
|
||||
} catch (apiKeyError) {
|
||||
if (apiKeyError.message && apiKeyError.message.includes('API key does not exist')) {
|
||||
console.log('⚠️ API Key 不存在,正在创建新的 API Key...');
|
||||
|
||||
// 创建新的 API key
|
||||
const creds = await clobClient.createApiKey();
|
||||
console.log(`✅ API Key 已创建`);
|
||||
console.log(` API Key: ${creds.key.substring(0, 10)}...`);
|
||||
console.log(` Passphrase: ${creds.passphrase.substring(0, 10)}...`);
|
||||
|
||||
// 使用 creds 初始化一个新的 ClobClient 实例用于 L2 认证
|
||||
const authenticatedClient = new ClobClient(
|
||||
HOST,
|
||||
CHAIN_ID,
|
||||
wallet,
|
||||
creds
|
||||
);
|
||||
|
||||
console.log(`\n正在获取订单详情...`);
|
||||
console.log(` 订单 ID: ${orderId}`);
|
||||
|
||||
const orderDetail = await authenticatedClient.getOrder(orderId);
|
||||
|
||||
console.log('\n================ 订单详情 ================');
|
||||
console.log(`订单 ID: ${orderDetail.id}`);
|
||||
console.log(`状态: ${orderDetail.status}`);
|
||||
console.log(`所有者: ${orderDetail.owner}`);
|
||||
console.log(`Maker 地址: ${orderDetail.maker_address}`);
|
||||
console.log(`市场 ID: ${orderDetail.market}`);
|
||||
console.log(`资产 ID: ${orderDetail.asset_id}`);
|
||||
console.log(`方向: ${orderDetail.side}`);
|
||||
console.log(`原始数量: ${orderDetail.original_size}`);
|
||||
console.log(`已匹配数量: ${orderDetail.size_matched}`);
|
||||
console.log(`价格: ${orderDetail.price}`);
|
||||
console.log(`结果: ${orderDetail.outcome}`);
|
||||
console.log(`创建时间: ${new Date(orderDetail.created_at * 1000).toISOString()}`);
|
||||
console.log(`过期时间: ${orderDetail.expiration}`);
|
||||
console.log(`订单类型: ${orderDetail.order_type}`);
|
||||
|
||||
if (orderDetail.associate_trades && orderDetail.associate_trades.length > 0) {
|
||||
console.log(`关联交易数量: ${orderDetail.associate_trades.length}`);
|
||||
console.log(`关联交易 IDs: ${orderDetail.associate_trades.join(', ')}`);
|
||||
}
|
||||
console.log('=========================================\n');
|
||||
} else {
|
||||
throw apiKeyError;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('\n❌ 获取订单详情失败:');
|
||||
console.error(error.message);
|
||||
|
||||
if (error.response) {
|
||||
console.error(`\nHTTP 状态码: ${error.response.status}`);
|
||||
console.error(`响应数据:`, error.response.data);
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 检查命令行参数
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length < 2) {
|
||||
console.error('错误: 缺少必要参数');
|
||||
console.error('\n使用方法:');
|
||||
console.error(' node scripts/get-order-detail.js <private_key> <order_id>');
|
||||
console.error('\n参数说明:');
|
||||
console.error(' private_key: 钱包私钥(用于签名)');
|
||||
console.error(' order_id: 订单 ID');
|
||||
console.error('\n示例:');
|
||||
console.error(' node scripts/get-order-detail.js "0x123..." "0x456..."');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const [privateKey, orderId] = args;
|
||||
|
||||
// 验证私钥格式
|
||||
if (!privateKey.startsWith('0x')) {
|
||||
console.error('错误: 私钥格式不正确,必须以 0x 开头');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (privateKey.length !== 66) {
|
||||
console.error('错误: 私钥长度不正确,应为 66 个字符(包括 0x 前缀)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 验证订单 ID
|
||||
if (!orderId.startsWith('0x')) {
|
||||
console.error('错误: 订单 ID 格式不正确,必须以 0x 开头');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 执行主函数
|
||||
getOrderDetail(privateKey, orderId);
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "polyhermes-scripts",
|
||||
"version": "1.0.0",
|
||||
"description": "Utility scripts for Polyhermes",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"get-order-detail": "node get-order-detail.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ethersproject/wallet": "^5.7.0",
|
||||
"@polymarket/clob-client": "^5.2.1"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user