-
Notifications
You must be signed in to change notification settings - Fork 22
/
orderbook.go
1164 lines (1024 loc) · 34.2 KB
/
orderbook.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2022 Gobalsky Labs Limited
//
// Use of this software is governed by the Business Source License included
// in the LICENSE.VEGA 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 matching
import (
"sort"
"sync"
"time"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
"github.com/pkg/errors"
)
var (
// ErrNotEnoughOrders signals that not enough orders were
// in the book to achieve a given operation.
ErrNotEnoughOrders = errors.New("insufficient orders")
ErrOrderDoesNotExist = errors.New("order does not exist")
ErrInvalidVolume = errors.New("invalid volume")
ErrNoBestBid = errors.New("no best bid")
ErrNoBestAsk = errors.New("no best ask")
ErrNotCrossed = errors.New("not crossed")
)
// OrderBook represents the book holding all orders in the system.
type OrderBook struct {
log *logging.Logger
Config
cfgMu *sync.Mutex
marketID string
buy *OrderBookSide
sell *OrderBookSide
lastTradedPrice *num.Uint
latestTimestamp int64
ordersByID map[string]*types.Order
ordersPerParty map[string]map[string]struct{}
auction bool
batchID uint64
indicativePriceAndVolume *IndicativePriceAndVolume
snapshot *types.PayloadMatchingBook
stopped bool // if true then we should stop creating snapshots
// we keep track here of which type of orders are in the orderbook so we can quickly
// find an order of a certain type. These get updated when orders are added or removed from the book.
peggedOrders map[string]struct{}
lpOrdersPerParty map[string]map[string]struct{}
peggedOrdersCount uint64
peggedCountNotify func(int64)
}
// CumulativeVolumeLevel represents the cumulative volume at a price level for both bid and ask.
type CumulativeVolumeLevel struct {
price *num.Uint
bidVolume uint64
askVolume uint64
cumulativeBidVolume uint64
cumulativeAskVolume uint64
maxTradableAmount uint64
}
func (b *OrderBook) Hash() []byte {
return crypto.Hash(append(b.buy.Hash(), b.sell.Hash()...))
}
// NewOrderBook create an order book with a given name.
func NewOrderBook(log *logging.Logger, config Config, marketID string, auction bool, peggedCountNotify func(int64)) *OrderBook {
// setup logger
log = log.Named(namedLogger)
log.SetLevel(config.Level.Get())
return &OrderBook{
log: log,
marketID: marketID,
cfgMu: &sync.Mutex{},
buy: &OrderBookSide{log: log, side: types.SideBuy},
sell: &OrderBookSide{log: log, side: types.SideSell},
Config: config,
ordersByID: map[string]*types.Order{},
auction: auction,
batchID: 0,
ordersPerParty: map[string]map[string]struct{}{},
lpOrdersPerParty: map[string]map[string]struct{}{},
lastTradedPrice: num.UintZero(),
snapshot: &types.PayloadMatchingBook{
MatchingBook: &types.MatchingBook{
MarketID: marketID,
},
},
peggedOrders: map[string]struct{}{},
peggedOrdersCount: 0,
peggedCountNotify: peggedCountNotify,
}
}
// ReloadConf is used in order to reload the internal configuration of
// the OrderBook.
func (b *OrderBook) ReloadConf(cfg Config) {
b.log.Info("reloading configuration")
if b.log.GetLevel() != cfg.Level.Get() {
b.log.Info("updating log level",
logging.String("old", b.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
b.log.SetLevel(cfg.Level.Get())
}
b.cfgMu.Lock()
b.Config = cfg
b.cfgMu.Unlock()
}
// GetOrderBookLevelCount returns the number of levels in the book.
func (b *OrderBook) GetOrderBookLevelCount() uint64 {
return uint64(len(b.buy.levels) + len(b.sell.levels))
}
func (b *OrderBook) GetPeggedOrdersCount() uint64 {
return b.peggedOrdersCount
}
// GetCloseoutPrice returns the exit price which would be achieved for a given
// volume and give side of the book.
func (b *OrderBook) GetCloseoutPrice(volume uint64, side types.Side) (*num.Uint, error) {
if b.auction {
p := b.GetIndicativePrice()
return p, nil
}
if volume == 0 {
return num.UintZero(), ErrInvalidVolume
}
var (
price = num.UintZero()
vol = volume
levels []*PriceLevel
)
if side == types.SideSell {
levels = b.sell.getLevels()
} else {
levels = b.buy.getLevels()
}
for i := len(levels) - 1; i >= 0; i-- {
lvl := levels[i]
if lvl.volume >= vol {
// price += lvl.price * vol
price.Add(price, num.UintZero().Mul(lvl.price, num.NewUint(vol)))
// return price / volume, nil
return price.Div(price, num.NewUint(volume)), nil
}
price.Add(price, num.UintZero().Mul(lvl.price, num.NewUint(lvl.volume)))
vol -= lvl.volume
}
// at this point, we should check vol, make sure it's 0, if not return an error to indicate something is wrong
// still return the price for the volume we could close out, so the caller can make a decision on what to do
if vol == volume {
return b.lastTradedPrice.Clone(), ErrNotEnoughOrders
}
price.Div(price, num.NewUint(volume-vol))
if vol != 0 {
return price, ErrNotEnoughOrders
}
return price, nil
}
// EnterAuction Moves the order book into an auction state.
func (b *OrderBook) EnterAuction() []*types.Order {
// Scan existing orders to see which ones can be kept or cancelled
ordersToCancel := append(
b.buy.getOrdersToCancel(true),
b.sell.getOrdersToCancel(true)...,
)
// Set the market state
b.auction = true
b.indicativePriceAndVolume = NewIndicativePriceAndVolume(b.log, b.buy, b.sell)
// Return all the orders that have been removed from the book and need to be cancelled
return ordersToCancel
}
// LeaveAuction Moves the order book back into continuous trading state.
func (b *OrderBook) LeaveAuction(at time.Time) ([]*types.OrderConfirmation, []*types.Order, error) {
// Update batchID
b.batchID++
ts := at.UnixNano()
// Uncross the book
uncrossedOrders, err := b.uncrossBook()
if err != nil {
return nil, nil, err
}
for _, uo := range uncrossedOrders {
if uo.Order.Remaining == 0 {
uo.Order.Status = types.OrderStatusFilled
b.remove(uo.Order)
}
uo.Order.UpdatedAt = ts
for idx, po := range uo.PassiveOrdersAffected {
po.UpdatedAt = ts
// also remove the orders from lookup tables
if uo.PassiveOrdersAffected[idx].Remaining == 0 {
uo.PassiveOrdersAffected[idx].Status = types.OrderStatusFilled
b.remove(po)
}
}
for _, tr := range uo.Trades {
tr.Timestamp = ts
tr.Aggressor = types.SideUnspecified
}
}
// Remove any orders that will not be valid in continuous trading
// Return all the orders that have been cancelled from the book
ordersToCancel := append(
b.buy.getOrdersToCancel(false),
b.sell.getOrdersToCancel(false)...,
)
for _, oc := range ordersToCancel {
oc.UpdatedAt = ts
}
// Flip back to continuous
b.auction = false
b.indicativePriceAndVolume = nil
return uncrossedOrders, ordersToCancel, nil
}
func (b OrderBook) InAuction() bool {
return b.auction
}
// CanLeaveAuction calls canUncross with required trades and, if that returns false
// without required trades (which still permits leaving liquidity auction
// if canUncross with required trades returs true, both returns are true.
func (b *OrderBook) CanLeaveAuction() (withTrades, withoutTrades bool) {
withTrades = b.canUncross(true)
withoutTrades = withTrades
if withTrades {
return
}
withoutTrades = b.canUncross(false)
return
}
// CanUncross - a clunky name for a somewhat clunky function: this checks if there will be LIMIT orders
// on the book after we uncross the book (at the end of an auction). If this returns false, the opening auction should be extended.
func (b *OrderBook) CanUncross() bool {
return b.canUncross(true)
}
func (b *OrderBook) BidAndAskPresentAfterAuction() bool {
return b.canUncross(false)
}
func (b *OrderBook) canUncross(requireTrades bool) bool {
bb, err := b.GetBestBidPrice() // sell
if err != nil {
return false
}
ba, err := b.GetBestAskPrice() // buy
if err != nil || bb.IsZero() || ba.IsZero() || (requireTrades && bb.LT(ba)) {
return false
}
// check all buy price levels below ba, find limit orders
buyMatch := false
// iterate from the end, where best is
for i := len(b.buy.levels) - 1; i >= 0; i-- {
l := b.buy.levels[i]
if l.price.LT(ba) {
for _, o := range l.orders {
// limit order && not just GFA found
if o.Type == types.OrderTypeLimit && o.TimeInForce != types.OrderTimeInForceGFA {
buyMatch = true
break
}
}
}
}
sellMatch := false
for i := len(b.sell.levels) - 1; i >= 0; i-- {
l := b.sell.levels[i]
if l.price.GT(bb) {
for _, o := range l.orders {
if o.Type == types.OrderTypeLimit && o.TimeInForce != types.OrderTimeInForceGFA {
sellMatch = true
break
}
}
}
}
// non-GFA orders outside the price range found on the book, we can uncross
if buyMatch && sellMatch {
return true
}
_, v, _ := b.GetIndicativePriceAndVolume()
// no buy orders remaining on the book after uncrossing, it buyMatches exactly
vol := uint64(0)
if !buyMatch {
for i := len(b.buy.levels) - 1; i >= 0; i-- {
l := b.buy.levels[i]
// buy orders are ordered ascending
if l.price.LT(ba) {
break
}
for _, o := range l.orders {
vol += o.Remaining
// we've filled the uncrossing volume, and found an order that is not GFA
if vol > v && o.TimeInForce != types.OrderTimeInForceGFA {
buyMatch = true
break
}
}
}
if !buyMatch {
return false
}
}
// we've had to check buy side - sell side is fine
if sellMatch {
return true
}
vol = 0
// for _, l := range b.sell.levels {
// sell side is ordered descending
for i := len(b.sell.levels) - 1; i >= 0; i-- {
l := b.sell.levels[i]
if l.price.GT(bb) {
break
}
for _, o := range l.orders {
vol += o.Remaining
if vol > v && o.TimeInForce != types.OrderTimeInForceGFA {
sellMatch = true
break
}
}
}
return sellMatch
}
// GetIndicativePriceAndVolume Calculates the indicative price and volume of the order book without modifying the order book state.
func (b *OrderBook) GetIndicativePriceAndVolume() (retprice *num.Uint, retvol uint64, retside types.Side) {
// Generate a set of price level pairs with their maximum tradable volumes
cumulativeVolumes, maxTradableAmount, err := b.buildCumulativePriceLevels()
if err != nil {
if b.log.GetLevel() <= logging.DebugLevel {
b.log.Debug("could not get cumulative price levels", logging.Error(err))
}
return num.UintZero(), 0, types.SideUnspecified
}
// Pull out all prices that match that volume
prices := make([]*num.Uint, 0, len(cumulativeVolumes))
for _, value := range cumulativeVolumes {
if value.maxTradableAmount == maxTradableAmount {
prices = append(prices, value.price)
}
}
// get the maximum volume price from the average of the maximum and minimum tradable price levels
var (
uncrossPrice = num.UintZero()
uncrossSide types.Side
)
if len(prices) > 0 {
// uncrossPrice = (prices[len(prices)-1] + prices[0]) / 2
uncrossPrice.Div(
num.UintZero().Add(prices[len(prices)-1], prices[0]),
num.NewUint(2),
)
}
// See which side we should fully process when we uncross
ordersToFill := int64(maxTradableAmount)
for _, value := range cumulativeVolumes {
ordersToFill -= int64(value.bidVolume)
if ordersToFill == 0 {
// Buys fill exactly, uncross from the buy side
uncrossSide = types.SideBuy
break
} else if ordersToFill < 0 {
// Buys are not exact, uncross from the sell side
uncrossSide = types.SideSell
break
}
}
return uncrossPrice, maxTradableAmount, uncrossSide
}
// GetIndicativePrice Calculates the indicative price of the order book without modifying the order book state.
func (b *OrderBook) GetIndicativePrice() (retprice *num.Uint) {
// Generate a set of price level pairs with their maximum tradable volumes
cumulativeVolumes, maxTradableAmount, err := b.buildCumulativePriceLevels()
if err != nil {
if b.log.GetLevel() <= logging.DebugLevel {
b.log.Debug("could not get cumulative price levels", logging.Error(err))
}
return num.UintZero()
}
// Pull out all prices that match that volume
prices := make([]*num.Uint, 0, len(cumulativeVolumes))
for _, value := range cumulativeVolumes {
if value.maxTradableAmount == maxTradableAmount {
prices = append(prices, value.price)
}
}
// get the maximum volume price from the average of the minimum and maximum tradable price levels
if len(prices) > 0 {
// return (prices[len(prices)-1] + prices[0]) / 2
return num.UintZero().Div(
num.UintZero().Add(prices[len(prices)-1], prices[0]),
num.NewUint(2),
)
}
return num.UintZero()
}
func (b *OrderBook) GetIndicativeTrades() ([]*types.Trade, error) {
// Get the uncrossing price and which side has the most volume at that price
price, volume, uncrossSide := b.GetIndicativePriceAndVolume()
// If we have no uncrossing price, we have nothing to do
if price.IsZero() && volume == 0 {
return nil, nil
}
var (
uncrossOrders []*types.Order
uncrossingSide *OrderBookSide
)
if uncrossSide == types.SideBuy {
uncrossingSide = b.buy
} else {
uncrossingSide = b.sell
}
// Remove all the orders from that side of the book up to the given volume
uncrossOrders = uncrossingSide.ExtractOrders(price, volume, false)
opSide := b.getOppositeSide(uncrossSide)
output := make([]*types.Trade, 0, len(uncrossOrders))
trades, err := opSide.fakeUncrossAuction(uncrossOrders)
if err != nil {
return nil, err
}
// Update all the trades to have the correct uncrossing price
for _, t := range trades {
t.Price = price.Clone()
}
output = append(output, trades...)
return output, nil
}
// buildCumulativePriceLevels this returns a slice of all the price levels with the
// cumulative volume for each level. Also returns the max tradable size.
func (b *OrderBook) buildCumulativePriceLevels() ([]CumulativeVolumeLevel, uint64, error) {
bestBid, err := b.GetBestBidPrice()
if err != nil {
return nil, 0, ErrNoBestBid
}
bestAsk, err := b.GetBestAskPrice()
if err != nil {
return nil, 0, ErrNoBestAsk
}
// Short circuit if the book is not crossed
if bestBid.LT(bestAsk) || bestBid.IsZero() || bestAsk.IsZero() {
return nil, 0, ErrNotCrossed
}
volume, maxTradableAmount := b.indicativePriceAndVolume.
GetCumulativePriceLevels(bestBid, bestAsk)
return volume, maxTradableAmount, nil
}
// Uncrosses the book to generate the maximum volume set of trades
// if removeOrders is set to true then matched orders get removed from the book.
func (b *OrderBook) uncrossBook() ([]*types.OrderConfirmation, error) {
// Get the uncrossing price and which side has the most volume at that price
price, volume, uncrossSide := b.GetIndicativePriceAndVolume()
// If we have no uncrossing price, we have nothing to do
if price.IsZero() && volume == 0 {
return nil, nil
}
var (
uncrossOrders []*types.Order
uncrossingSide *OrderBookSide
)
if uncrossSide == types.SideBuy {
uncrossingSide = b.buy
} else {
uncrossingSide = b.sell
}
// Remove all the orders from that side of the book up to the given volume
uncrossOrders = uncrossingSide.ExtractOrders(price, volume, true)
return b.uncrossBookSide(uncrossOrders, b.getOppositeSide(uncrossSide), price.Clone())
}
// Takes extracted order from a side of the book, and uncross them
// with the opposite side.
func (b *OrderBook) uncrossBookSide(
uncrossOrders []*types.Order,
opSide *OrderBookSide,
price *num.Uint,
) ([]*types.OrderConfirmation, error) {
var (
uncrossedOrder *types.OrderConfirmation
allOrders = make([]*types.OrderConfirmation, 0, len(uncrossOrders))
)
if len(uncrossOrders) == 0 {
return nil, nil
}
// get price factor, if price is 10,000, but market price is 100, this is 10,000/100 -> 100
// so we can get the market price simply by doing price / (order.Price/ order.OriginalPrice)
mPrice := num.UintZero().Div(uncrossOrders[0].Price, uncrossOrders[0].OriginalPrice)
mPrice.Div(price, mPrice)
// Uncross each one
for _, order := range uncrossOrders {
// try to get the market price value from the order
trades, affectedOrders, _, err := opSide.uncross(order, false)
if err != nil {
return nil, err
}
// If the affected order is fully filled set the status
for _, affectedOrder := range affectedOrders {
if affectedOrder.Remaining == 0 {
affectedOrder.Status = types.OrderStatusFilled
}
}
// Update all the trades to have the correct uncrossing price
for index := 0; index < len(trades); index++ {
trades[index].Price = price.Clone()
trades[index].MarketPrice = mPrice.Clone()
}
uncrossedOrder = &types.OrderConfirmation{Order: order, PassiveOrdersAffected: affectedOrders, Trades: trades}
allOrders = append(allOrders, uncrossedOrder)
}
return allOrders, nil
}
func (b *OrderBook) GetOrdersPerParty(party string) []*types.Order {
orderIDs := b.ordersPerParty[party]
if len(orderIDs) <= 0 {
return []*types.Order{}
}
orders := make([]*types.Order, 0, len(orderIDs))
for oid := range orderIDs {
orders = append(orders, b.ordersByID[oid])
}
return orders
}
func (b *OrderBook) GetLiquidityOrders(party string) []*types.Order {
orderIDs := b.lpOrdersPerParty[party]
if len(orderIDs) <= 0 {
return []*types.Order{}
}
orders := make([]*types.Order, 0, len(orderIDs))
for oid := range orderIDs {
orders = append(orders, b.ordersByID[oid])
}
return orders
}
func (b *OrderBook) GetAllLiquidityOrders() []*types.Order {
orders := make([]*types.Order, 0)
for party := range b.lpOrdersPerParty {
orders = append(orders, b.GetLiquidityOrders(party)...)
}
sort.Slice(orders, func(i, j int) bool {
return orders[i].ID < orders[j].ID
})
return orders
}
// BestBidPriceAndVolume : Return the best bid and volume for the buy side of the book.
func (b *OrderBook) BestBidPriceAndVolume() (*num.Uint, uint64, error) {
return b.buy.BestPriceAndVolume()
}
// BestOfferPriceAndVolume : Return the best bid and volume for the sell side of the book.
func (b *OrderBook) BestOfferPriceAndVolume() (*num.Uint, uint64, error) {
return b.sell.BestPriceAndVolume()
}
func (b *OrderBook) CancelAllOrders(party string) ([]*types.OrderCancellationConfirmation, error) {
var (
orders = b.GetOrdersPerParty(party)
confs = []*types.OrderCancellationConfirmation{}
conf *types.OrderCancellationConfirmation
err error
)
for _, o := range orders {
conf, err = b.CancelOrder(o)
if err != nil {
return nil, err
}
confs = append(confs, conf)
}
return confs, err
}
// CancelOrder cancel an order that is active on an order book. Market and Order ID are validated, however the order must match
// the order on the book with respect to side etc. The caller will typically validate this by using a store, we should
// not trust that the external world can provide these values reliably.
func (b *OrderBook) CancelOrder(order *types.Order) (*types.OrderCancellationConfirmation, error) {
// Validate Market
if order.MarketID != b.marketID {
b.log.Panic("Market ID mismatch",
logging.Order(*order),
logging.String("order-book", b.marketID))
}
// Validate Order ID must be present
if err := validateOrderID(order.ID); err != nil {
if b.log.GetLevel() == logging.DebugLevel {
b.log.Debug("Order ID missing or invalid",
logging.Order(*order),
logging.String("order-book", b.marketID))
}
return nil, err
}
order, err := b.DeleteOrder(order)
if err != nil {
return nil, err
}
// Important to mark the order as cancelled (and no longer active)
order.Status = types.OrderStatusCancelled
result := &types.OrderCancellationConfirmation{
Order: order,
}
return result, nil
}
// RemoveOrder takes the order off the order book.
func (b *OrderBook) RemoveOrder(id string) (*types.Order, error) {
order, err := b.GetOrderByID(id)
if err != nil {
return nil, err
}
order, err = b.DeleteOrder(order)
if err != nil {
return nil, err
}
// Important to mark the order as parked (and no longer active)
order.Status = types.OrderStatusParked
return order, nil
}
// AmendOrder amends an order which is an active order on the book.
func (b *OrderBook) AmendOrder(originalOrder, amendedOrder *types.Order) error {
if originalOrder == nil {
if amendedOrder != nil {
b.log.Panic("invalid input, orginalOrder is nil", logging.Order(*amendedOrder))
}
}
// If the creation date for the 2 orders is different, something went wrong
if originalOrder != nil && originalOrder.CreatedAt != amendedOrder.CreatedAt {
return types.ErrOrderOutOfSequence
}
if err := b.validateOrder(amendedOrder); err != nil {
if b.log.GetLevel() == logging.DebugLevel {
b.log.Debug("Order validation failure",
logging.Order(*amendedOrder),
logging.Error(err),
logging.String("order-book", b.marketID))
}
return err
}
var (
reduceBy uint64
side = b.sell
err error
)
if amendedOrder.Side == types.SideBuy {
side = b.buy
}
if reduceBy, err = side.amendOrder(amendedOrder); err != nil {
if b.log.GetLevel() == logging.DebugLevel {
b.log.Debug("Failed to amend",
logging.String("side", amendedOrder.Side.String()),
logging.Order(*amendedOrder),
logging.String("market", b.marketID),
logging.Error(err),
)
}
return err
}
// update the order by ids mapping
b.ordersByID[amendedOrder.ID] = amendedOrder
if b.auction && reduceBy != 0 {
// reduce volume at price level
b.indicativePriceAndVolume.RemoveVolumeAtPrice(
amendedOrder.Price, reduceBy, amendedOrder.Side)
}
return nil
}
// GetTrades returns the trades a given order generates if we were to submit it now
// this is used to calculate fees, perform price monitoring, etc...
func (b *OrderBook) GetTrades(order *types.Order) ([]*types.Trade, error) {
// this should always return straight away in an auction
if b.auction {
return nil, nil
}
if err := b.validateOrder(order); err != nil {
return nil, err
}
if order.CreatedAt > b.latestTimestamp {
b.latestTimestamp = order.CreatedAt
}
trades, err := b.getOppositeSide(order.Side).fakeUncross(order, true)
// it's fine for the error to be a wash trade here,
// it's just be stopped when really uncrossing.
if err != nil && err != ErrWashTrade {
// some random error happened, return both trades and error
// this is a case that isn't covered by the current SubmitOrder call
return trades, err
}
// no error uncrossing, in all other cases, return trades (could be empty) without an error
return trades, nil
}
func (b *OrderBook) ReplaceOrder(rm, rpl *types.Order) (*types.OrderConfirmation, error) {
if _, err := b.CancelOrder(rm); err != nil {
return nil, err
}
return b.SubmitOrder(rpl)
}
func (b *OrderBook) ReSubmitSpecialOrders(order *types.Order) {
// not allowed to submit a normal order here
if len(order.LiquidityProvisionID) <= 0 && order.PeggedOrder == nil {
b.log.Panic("only pegged orders or liquidity orders allowed", logging.Order(order))
}
order.BatchID = b.batchID
// check if order would trade, that should never happen as well.
switch order.Side {
case types.SideBuy:
price, err := b.GetBestAskPrice()
if err != nil {
b.log.Panic("tried to re submit special orders in an empty book", logging.Order(order))
}
if price.LTE(order.Price) {
b.log.Panic("re submit special order would cross", logging.Order(order), logging.BigUint("best-ask", price))
}
case types.SideSell:
price, err := b.GetBestBidPrice()
if err != nil {
b.log.Panic("tried to re submit special orders in an empty book", logging.Order(order))
}
if price.GTE(order.Price) {
b.log.Panic("re submit special order would cross", logging.Order(order), logging.BigUint("best-bid", price))
}
default:
b.log.Panic("invalid order side", logging.Order(order))
}
// now we can nicely add the order to the book, no uncrossing needed
b.getSide(order.Side).addOrder(order)
b.add(order)
}
// SubmitOrder Add an order and attempt to uncross the book, returns a TradeSet protobuf message object.
func (b *OrderBook) SubmitOrder(order *types.Order) (*types.OrderConfirmation, error) {
if err := b.validateOrder(order); err != nil {
return nil, err
}
if _, ok := b.ordersByID[order.ID]; ok {
b.log.Panic("an order in the book already exists with the same ID", logging.Order(*order))
}
if order.CreatedAt > b.latestTimestamp {
b.latestTimestamp = order.CreatedAt
}
var (
trades []*types.Trade
impactedOrders []*types.Order
lastTradedPrice *num.Uint
err error
)
order.BatchID = b.batchID
if !b.auction {
// uncross with opposite
trades, impactedOrders, lastTradedPrice, err = b.getOppositeSide(order.Side).uncross(order, true)
if !lastTradedPrice.IsZero() {
b.lastTradedPrice = lastTradedPrice
}
}
// if order is persistent type add to order book to the correct side
// and we did not hit a error / wash trade error
if order.IsPersistent() && err == nil {
b.getSide(order.Side).addOrder(order)
// also add it to the indicative price and volume if in auction
if b.auction {
b.indicativePriceAndVolume.AddVolumeAtPrice(
order.Price, order.Remaining, order.Side)
}
}
// Was the aggressive order fully filled?
if order.Remaining == 0 {
order.Status = types.OrderStatusFilled
}
// What is an Immediate or Cancel Order?
// An immediate or cancel order (IOC) is an order to buy or sell that executes all
// or part immediately and cancels any unfilled portion of the order.
if order.TimeInForce == types.OrderTimeInForceIOC && order.Remaining > 0 {
// Stopped as not filled at all
if order.Remaining == order.Size {
order.Status = types.OrderStatusStopped
} else {
// IOC so we set status as Cancelled.
order.Status = types.OrderStatusPartiallyFilled
}
}
// What is Fill Or Kill?
// Fill or kill (FOK) is a type of time-in-force designation used in trading that instructs
// the protocol to execute an order immediately and completely or not at all.
// The order must be filled in its entirety or cancelled (killed).
if order.TimeInForce == types.OrderTimeInForceFOK && order.Remaining == order.Size {
// FOK and didnt trade at all we set status as Stopped
order.Status = types.OrderStatusStopped
}
for idx := range impactedOrders {
if impactedOrders[idx].Remaining == 0 {
impactedOrders[idx].Status = types.OrderStatusFilled
// delete from lookup tables
b.remove(impactedOrders[idx])
}
}
// if we did hit a wash trade, set the status to STOPPED
if err == ErrWashTrade {
if order.Size > order.Remaining {
order.Status = types.OrderStatusPartiallyFilled
} else {
order.Status = types.OrderStatusStopped
}
order.Reason = types.OrderErrorSelfTrading
}
if order.Status == types.OrderStatusActive {
b.add(order)
}
orderConfirmation := makeResponse(order, trades, impactedOrders)
return orderConfirmation, nil
}
// DeleteOrder remove a given order on a given side from the book.
func (b *OrderBook) DeleteOrder(
order *types.Order,
) (*types.Order, error) {
dorder, err := b.getSide(order.Side).RemoveOrder(order)
if err != nil {
if b.log.GetLevel() == logging.DebugLevel {
b.log.Debug("Failed to remove order",
logging.Order(*order),
logging.Error(err),
logging.String("order-book", b.marketID))
}
return nil, types.ErrOrderRemovalFailure
}
b.remove(order)
// also remove it to the indicative price and volume if in auction
// here we use specifically the order which was in the book, just in case
// the order passed in would be wrong
// TODO: refactor this better, we should never need to pass in more that IDs there
// because by using the order passed in remain and price, we could use
// values which have been amended previously... (e.g: amending an order which
// cancel the order if it expires it
if b.auction {
b.indicativePriceAndVolume.RemoveVolumeAtPrice(
dorder.Price, dorder.Remaining, dorder.Side)
}
return dorder, err
}
// GetOrderByID returns order by its ID (IDs are not expected to collide within same market).
func (b *OrderBook) GetOrderByID(orderID string) (*types.Order, error) {
if err := validateOrderID(orderID); err != nil {
if b.log.GetLevel() == logging.DebugLevel {
b.log.Debug("Order ID missing or invalid",
logging.String("order-id", orderID))
}
return nil, err
}
// First look for the order in the order book
order, exists := b.ordersByID[orderID]
if !exists {
return nil, ErrOrderDoesNotExist
}
return order, nil
}
// RemoveDistressedOrders remove from the book all order holding distressed positions.
func (b *OrderBook) RemoveDistressedOrders(
parties []events.MarketPosition,
) ([]*types.Order, error) {
rmorders := []*types.Order{}
for _, party := range parties {
orders := []*types.Order{}
for _, l := range b.buy.levels {
rm := l.getOrdersByParty(party.Party())
orders = append(orders, rm...)
}
for _, l := range b.sell.levels {
rm := l.getOrdersByParty(party.Party())
orders = append(orders, rm...)
}
for _, o := range orders {
confirm, err := b.CancelOrder(o)
if err != nil {
b.log.Panic(
"Failed to cancel a given order for party",
logging.Order(*o),
logging.String("party", party.Party()),
logging.Error(err))
}
// here we set the status of the order as stopped as the system triggered it as well.
confirm.Order.Status = types.OrderStatusStopped
rmorders = append(rmorders, confirm.Order)
}
}
return rmorders, nil
}
func (b OrderBook) getSide(orderSide types.Side) *OrderBookSide {
if orderSide == types.SideBuy {
return b.buy
}
return b.sell
}