Skip to content

Commit b721002

Browse files
committed
fix(market): resolve price staleness issue in GetCurrentKlines
## Problem GetCurrentKlines had two critical bugs causing price data to become stale: 1. Incorrect return logic: returned error even when data fetch succeeded 2. Race condition: returned slice reference instead of deep copy, causing concurrent data corruption ## Impact - BTC price stuck at 106xxx while actual market price was 107xxx+ - LLM calculated take-profit based on stale prices → orders failed validation - Statistics showed incorrect P&L (0.00%) due to corrupted historical data - Alt-coins filtered out due to failed market data fetch ## Solution 1. Fixed return logic: only return error when actual failure occurs 2. Return deep copy instead of reference to prevent race conditions 3. Downgrade subscription errors to warnings (non-blocking) ## Test Results ✅ Price updates in real-time ✅ Take-profit orders execute successfully ✅ P&L calculations accurate ✅ Alt-coins now tradeable Related: Price feed mechanism, concurrent data access
1 parent 5649cb7 commit b721002

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

market/monitor.go

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -239,19 +239,32 @@ func (m *WSMonitor) GetCurrentKlines(symbol string, _time string) ([]Kline, erro
239239
// 如果Ws数据未初始化完成时,单独使用api获取 - 兼容性代码 (防止在未初始化完成是,已经有交易员运行)
240240
apiClient := NewAPIClient()
241241
klines, err := apiClient.GetKlines(symbol, _time, 100)
242-
m.getKlineDataMap(_time).Store(strings.ToUpper(symbol), klines) //动态缓存进缓存
242+
if err != nil {
243+
return nil, fmt.Errorf("获取%v分钟K线失败: %v", _time, err)
244+
}
245+
246+
// 动态缓存进缓存
247+
m.getKlineDataMap(_time).Store(strings.ToUpper(symbol), klines)
248+
249+
// 订阅 WebSocket 流
243250
subStr := m.subscribeSymbol(symbol, _time)
244251
subErr := m.combinedClient.subscribeStreams(subStr)
245252
log.Printf("动态订阅流: %v", subStr)
246253
if subErr != nil {
247-
return nil, fmt.Errorf("动态订阅%v分钟K线失败: %v", _time, subErr)
254+
log.Printf("警告: 动态订阅%v分钟K线失败: %v (使用API数据)", _time, subErr)
248255
}
249-
if err != nil {
250-
return nil, fmt.Errorf("获取%v分钟K线失败: %v", _time, err)
251-
}
252-
return klines, fmt.Errorf("symbol不存在")
256+
257+
// ✅ FIX: 返回深拷贝而非引用
258+
result := make([]Kline, len(klines))
259+
copy(result, klines)
260+
return result, nil
253261
}
254-
return value.([]Kline), nil
262+
263+
// ✅ FIX: 返回深拷贝而非引用,避免并发竞态条件
264+
klines := value.([]Kline)
265+
result := make([]Kline, len(klines))
266+
copy(result, klines)
267+
return result, nil
255268
}
256269

257270
func (m *WSMonitor) Close() {

0 commit comments

Comments
 (0)