-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrade_book.go
51 lines (43 loc) · 1.02 KB
/
trade_book.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package tome
import (
"sort"
"sync"
)
// Trade book stores all daily trades in-memory.
// It flushes new trades periodically to persistent storage. (TODO)
type TradeBook struct {
Instrument string
trades map[uint64]Trade
tradeMutex sync.RWMutex
lastTradeID uint64
}
// Create a new trade book.
func NewTradeBook(instrument string) *TradeBook {
return &TradeBook{
Instrument: instrument,
trades: make(map[uint64]Trade),
}
}
// Enter a new trade.
func (t *TradeBook) Enter(trade Trade) {
t.tradeMutex.Lock()
defer t.tradeMutex.Unlock()
trade.ID = t.lastTradeID
t.trades[t.lastTradeID] = trade
t.lastTradeID += 1
}
// Return all daily trades in a trade book.
func (t *TradeBook) DailyTrades() []Trade {
t.tradeMutex.RLock()
defer t.tradeMutex.RUnlock()
tradesCopy := make([]Trade, len(t.trades))
i := 0
for _, trade := range t.trades {
tradesCopy[i] = trade
i += 1
}
sort.Slice(tradesCopy, func(i, j int) bool {
return tradesCopy[i].Timestamp.Before(tradesCopy[j].Timestamp)
})
return tradesCopy
}