-
Notifications
You must be signed in to change notification settings - Fork 18
/
market_depth.go
328 lines (282 loc) · 9.07 KB
/
market_depth.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.DATANODE file and at https://www.mariadb.com/bsl11.
//
// Change Date: 18 months from the later of the date of the first publicly
// available Distribution of this version of the repository, and 25 June 2022.
//
// On the date above, in accordance with the Business Source License, use
// of this software will be governed by version 3 or later of the GNU General
// Public License.
package service
import (
"context"
"sync"
"time"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/datanode/entities"
"code.vegaprotocol.io/vega/datanode/utils"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
)
type OrderStore interface {
GetLiveOrders(ctx context.Context) ([]entities.Order, error)
}
type MarketDepth struct {
marketDepths map[string]*entities.MarketDepth
orderStore OrderStore
depthObserver utils.Observer[*types.MarketDepth]
updateObserver utils.Observer[*types.MarketDepthUpdate]
mu sync.RWMutex
sequenceNumber uint64
}
func NewMarketDepth(orderStore OrderStore, logger *logging.Logger) *MarketDepth {
return &MarketDepth{
marketDepths: map[string]*entities.MarketDepth{},
orderStore: orderStore,
depthObserver: utils.NewObserver[*types.MarketDepth]("market_depth", logger, 100, 100),
updateObserver: utils.NewObserver[*types.MarketDepthUpdate]("market_depth_update", logger, 100, 100),
}
}
func (m *MarketDepth) Initialise(ctx context.Context) error {
liveOrders, err := m.orderStore.GetLiveOrders(ctx)
if err != nil {
return err
}
// process the live orders and initialize market depths from database data
for _, liveOrder := range liveOrders {
order, err := types.OrderFromProto(liveOrder.ToProto())
if err != nil {
panic(err)
}
m.AddOrder(order, liveOrder.VegaTime, liveOrder.SeqNum)
}
return nil
}
func (m *MarketDepth) PublishAtEndOfBlock() {
m.publishChanges()
}
func (m *MarketDepth) publishChanges() {
m.mu.Lock()
defer m.mu.Unlock()
for marketID, md := range m.marketDepths {
buyPtr := []*types.PriceLevel{}
sellPtr := []*types.PriceLevel{}
// No need to notify anyone if nothing has changed
if len(md.Changes) == 0 {
continue
}
// Send out market depth updates to any listeners
for _, pl := range md.Changes {
if pl.Side == types.SideBuy {
buyPtr = append(buyPtr, &types.PriceLevel{
Price: pl.Price.Clone(),
NumberOfOrders: pl.TotalOrders,
Volume: pl.TotalVolume,
})
} else {
sellPtr = append(sellPtr, &types.PriceLevel{
Price: pl.Price.Clone(),
NumberOfOrders: pl.TotalOrders,
Volume: pl.TotalVolume,
})
}
}
marketDepthUpdate := &types.MarketDepthUpdate{
MarketId: marketID,
Buy: types.PriceLevels(buyPtr).IntoProto(),
Sell: types.PriceLevels(sellPtr).IntoProto(),
SequenceNumber: md.SequenceNumber,
PreviousSequenceNumber: md.PreviousSequenceNumber,
}
m.updateObserver.Notify([]*types.MarketDepthUpdate{marketDepthUpdate})
m.depthObserver.Notify([]*types.MarketDepth{md.ToProto(0)})
// Clear the list of changes
md.Changes = make([]*entities.PriceLevel, 0, len(md.Changes))
md.PreviousSequenceNumber = md.SequenceNumber
}
}
func (m *MarketDepth) AddOrder(order *types.Order, vegaTime time.Time, sequenceNumber uint64) {
m.mu.Lock()
defer m.mu.Unlock()
// Non persistent and network orders do not matter
if order.Type == types.OrderTypeMarket ||
order.TimeInForce == types.OrderTimeInForceFOK ||
order.TimeInForce == types.OrderTimeInForceIOC {
return
}
// Orders that where not valid are ignored
if order.Status == types.OrderStatusUnspecified {
return
}
// we truncate the vegaTime by microsecond because Postgres only supports microsecond
// granularity for time. In order to be able to reproduce the same sequence numbers regardless
// the source, we have to truncate the time to microsecond granularity
seqNum := uint64(vegaTime.Truncate(time.Microsecond).UnixNano()) + sequenceNumber
if m.sequenceNumber > seqNum {
// This update is older than the current MarketDepth
return
}
m.sequenceNumber = seqNum
// See if we already have a MarketDepth item for this market
md := m.marketDepths[order.MarketID]
if md == nil {
// First time we have an update for this market
// so we need to create a new MarketDepth
md = &entities.MarketDepth{
MarketID: order.MarketID,
LiveOrders: map[string]*types.Order{},
}
md.SequenceNumber = m.sequenceNumber
m.marketDepths[order.MarketID] = md
}
md.AddOrderUpdate(order)
md.SequenceNumber = m.sequenceNumber
}
// GetMarketDepth builds up the structure to be sent out to any market depth listeners.
func (m *MarketDepth) GetMarketDepth(market string, limit uint64) *types.MarketDepth {
m.mu.RLock()
defer m.mu.RUnlock()
md, ok := m.marketDepths[market]
if !ok || md == nil {
// When a market is new with no orders there will not be any market depth/order book
// so we do not need to try and calculate the depth cumulative volumes etc
return &types.MarketDepth{
MarketId: market,
Buy: []*vega.PriceLevel{},
Sell: []*vega.PriceLevel{},
}
}
return md.ToProto(limit)
}
func (m *MarketDepth) ObserveDepth(ctx context.Context, retries int, marketIds []string) (<-chan []*types.MarketDepth, uint64) {
markets := map[string]bool{}
for _, id := range marketIds {
markets[id] = true
}
ch, ref := m.depthObserver.Observe(ctx,
retries,
func(md *types.MarketDepth) bool { return markets[md.MarketId] })
return ch, ref
}
func (m *MarketDepth) ObserveDepthUpdates(ctx context.Context, retries int, marketIds []string) (<-chan []*types.MarketDepthUpdate, uint64) {
markets := map[string]bool{}
for _, id := range marketIds {
markets[id] = true
}
ch, ref := m.updateObserver.Observe(ctx,
retries,
func(md *types.MarketDepthUpdate) bool { return markets[md.MarketId] })
return ch, ref
}
/*****************************************************************************/
/* FUNCTIONS TO HELP WITH UNIT TESTING */
/*****************************************************************************/
func (m *MarketDepth) GetAllOrders(market string) map[string]*types.Order {
md := m.marketDepths[market]
if md != nil {
return md.LiveOrders
}
return nil
}
// GetOrderCount returns the number of live orders for the given market.
func (m *MarketDepth) GetOrderCount(market string) int64 {
var liveOrders int64
var bookOrders uint64
md := m.marketDepths[market]
if md != nil {
liveOrders = int64(len(md.LiveOrders))
for _, pl := range md.BuySide {
bookOrders += pl.TotalOrders
}
for _, pl := range md.SellSide {
bookOrders += pl.TotalOrders
}
if liveOrders != int64(bookOrders) {
return -1
}
return liveOrders
}
return 0
}
// GetVolumeAtPrice returns the order volume at the given price level.
func (m *MarketDepth) GetVolumeAtPrice(market string, side types.Side, price uint64) uint64 {
md := m.marketDepths[market]
if md != nil {
pl := md.GetPriceLevel(side, num.NewUint(price))
if pl == nil {
return 0
}
return pl.TotalVolume
}
return 0
}
// GetTotalVolume returns the total volume in the order book.
func (m *MarketDepth) GetTotalVolume(market string) int64 {
var volume int64
md := m.marketDepths[market]
if md != nil {
for _, pl := range md.BuySide {
volume += int64(pl.TotalVolume)
}
for _, pl := range md.SellSide {
volume += int64(pl.TotalVolume)
}
return volume
}
return 0
}
// GetOrderCountAtPrice returns the number of orders at the given price level.
func (m *MarketDepth) GetOrderCountAtPrice(market string, side types.Side, price uint64) uint64 {
md := m.marketDepths[market]
if md != nil {
pl := md.GetPriceLevel(side, num.NewUint(price))
if pl == nil {
return 0
}
return pl.TotalOrders
}
return 0
}
// GetPriceLevels returns the number of non empty price levels.
func (m *MarketDepth) GetPriceLevels(market string) int {
return m.GetBuyPriceLevels(market) + m.GetSellPriceLevels(market)
}
// GetBestBidPrice returns the highest bid price in the book.
func (m *MarketDepth) GetBestBidPrice(market string) *num.Uint {
md := m.marketDepths[market]
if md != nil {
if len(md.BuySide) > 0 {
return md.BuySide[0].Price.Clone()
}
}
return num.UintZero()
}
// GetBestAskPrice returns the highest bid price in the book.
func (m *MarketDepth) GetBestAskPrice(market string) *num.Uint {
md := m.marketDepths[market]
if md != nil {
if len(md.SellSide) > 0 {
return md.SellSide[0].Price.Clone()
}
}
return num.UintZero()
}
// GetBuyPriceLevels returns the number of non empty buy price levels.
func (m *MarketDepth) GetBuyPriceLevels(market string) int {
md := m.marketDepths[market]
if md != nil {
return len(md.BuySide)
}
return 0
}
// GetSellPriceLevels returns the number of non empty sell price levels.
func (m *MarketDepth) GetSellPriceLevels(market string) int {
md := m.marketDepths[market]
if md != nil {
return len(md.SellSide)
}
return 0
}