decouple display from trading: snapMu + RefreshSnapshot/ReadSnapshot

- Add snapMu RWMutex + positionsSnapshot to Trader
- RefreshSnapshot() called from main loop after Tick() — acquires
  t.mu briefly, stores deep copy under snapMu
- ReadSnapshot() returns snapshot copy under snapMu.RLock — never
  touches t.mu, zero contention with trading path
- Dashboard + handleStatus + hourly summary + status log all
  use ReadSnapshot() instead of GetPositionsCopy()
- Trading path (Tick/TryEntry/executeEntry/checkExit/checkScaleIn)
  never blocked by display reads
- Snapshot is at most 1 tick behind live state — acceptable delay
This commit is contained in:
jackyu66git
2026-05-03 18:35:47 +08:00
parent b08d8490fc
commit 02b74f1ec0
3 changed files with 31 additions and 6 deletions
+24
View File
@@ -89,6 +89,26 @@ func (t *Trader) GetPositionsCopy() []ArbPosition {
return r
}
// RefreshSnapshot takes a trading-lock snapshot of open positions for display use.
// Call this after each Tick() from the main loop — never during a trading operation.
// The display reads from this snapshot without blocking trading.
func (t *Trader) RefreshSnapshot() {
copy := t.GetPositionsCopy() // acquires t.mu briefly (not held during Tick call)
t.snapMu.Lock()
t.positionsSnapshot = copy
t.snapMu.Unlock()
}
// ReadSnapshot returns a copy of the last display snapshot — never locks t.mu.
// Safe to call from any goroutine without impacting trading latency.
func (t *Trader) ReadSnapshot() []ArbPosition {
t.snapMu.RLock()
defer t.snapMu.RUnlock()
r := make([]ArbPosition, len(t.positionsSnapshot))
copy(r, t.positionsSnapshot)
return r
}
// Trader handles scalable arbitrage between Bitget and HyperLiquid.
type Trader struct {
cfg *Config
@@ -102,6 +122,10 @@ type Trader struct {
closedTrades []TradeRecord // history of closed trades
OnTradeEvent func(event string, data interface{}) // P3-4: real-time SSE push
// Decoupled snapshot for display — snapMu never contended by trading path
snapMu sync.RWMutex
positionsSnapshot []ArbPosition
}
// TradeRecord stores a finalized trade for stats tracking.