Compare commits

...

4 Commits

Author SHA1 Message Date
WrBug 3e2e97e572 fix: 修复 CopyOrderTrackingService 和 CopyTradingService 的 @Transactional 自调用问题
1. CopyOrderTrackingService 修复
   - 实现 ApplicationContextAware 接口
   - 添加 getSelf() 方法获取代理对象
   - 在 processTrade() 中通过代理调用 processBuyTrade() 和 processSellTrade()
   - 确保两个子方法的 @Transactional 生效

2. CopyTradingService 修复
   - 实现 ApplicationContextAware 接口
   - 添加 getSelf() 方法获取代理对象
   - 在 updateCopyTradingStatus() 中通过代理调用 updateCopyTrading()
   - 确保内部调用的 @Transactional 生效

修改的文件:
- CopyOrderTrackingService.kt
- CopyTradingService.kt
2026-01-16 10:28:39 +08:00
WrBug ae68a33c1e fix: 优化仓位列表分页和统计功能
- 添加完整的分页功能,支持移动端和桌面端
- 移动端:自定义分页控件,支持切换每页 10/20/50 条
- 桌面端:使用 Ant Design Table 分页,支持切换每页 10/20/50 条
- 优化仓位统计逻辑,区分当前仓位和历史仓位
- 当前仓位:显示浮动盈亏和已实现盈亏
- 历史仓位:移除盈亏统计显示
- 筛选条件变化时自动重置到第一页
2026-01-16 10:14:54 +08:00
WrBug deea59fdbf fix: 修复 OrderStatusUpdateService 的事务和并发问题
1. 解决 @Transactional 自调用问题
   - 实现 ApplicationContextAware 接口
   - 通过代理对象调用 @Transactional 方法,确保事务生效

2. 防止定时任务并发执行
   - 添加 updateJob 跟踪上一次任务状态
   - 如果上一次任务还在执行,跳过本次执行
   - 避免多个更新任务同时运行导致的数据竞争

修改的方法:
- updateOrderStatus(): 添加并发控制
- cleanupDeletedAccountOrders(): 通过代理对象调用
- checkAndDeleteUnfilledOrders(): 通过代理对象调用
- updatePendingSellOrderPrices(): 通过代理对象调用
- updatePendingBuyOrders(): 通过代理对象调用
2026-01-15 15:21:29 +08:00
WrBug b90f86b081 fix: 修复 @Transactional 方法的可见性问题
将 OrderStatusUpdateService 中 4 个使用 @Transactional 的方法从 private 改为 public,
确保 Spring 能够正确代理这些方法。

修改的方法:
- cleanupDeletedAccountOrders()
- checkAndDeleteUnfilledOrders()
- updatePendingSellOrderPrices()
- updatePendingBuyOrders()

参考 UserService.kt 的实现模式,@Transactional 方法必须是 public 的。
2026-01-15 15:05:53 +08:00
4 changed files with 213 additions and 61 deletions
@@ -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
@@ -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}"))
@@ -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
@@ -323,7 +357,7 @@ class OrderStatusUpdateService(
* 注意:priceUpdated 现在同时表示价格已更新和通知已发送(共用字段)
*/
@Transactional
private suspend fun updatePendingSellOrderPrices() {
suspend fun updatePendingSellOrderPrices() {
try {
// 查询所有价格未更新的卖出记录(priceUpdated = false 表示未处理)
val pendingRecords = sellMatchRecordRepository.findByPriceUpdatedFalse()
@@ -566,7 +600,7 @@ class OrderStatusUpdateService(
* 查询订单详情获取实际价格和数量,然后发送通知并更新数据库
*/
@Transactional
private suspend fun updatePendingBuyOrders() {
suspend fun updatePendingBuyOrders() {
try {
// 查询所有未发送通知的买入订单
val pendingOrders = copyOrderTrackingRepository.findByNotificationSentFalse()
+125 -40
View File
@@ -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>
)}
{/* 出售模态框 */}