/
orders.go
100 lines (89 loc) · 2.39 KB
/
orders.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
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/sei-protocol/sei-chain/utils"
"github.com/sei-protocol/sei-chain/utils/datastructures"
)
type OrderBook struct {
Longs *CachedSortedOrderBookEntries
Shorts *CachedSortedOrderBookEntries
}
func (o *OrderBook) DeepCopy() *OrderBook {
return &OrderBook{
Longs: o.Longs.DeepCopy(),
Shorts: o.Shorts.DeepCopy(),
}
}
// entries are always sorted by prices in ascending order, regardless of side
type CachedSortedOrderBookEntries struct {
Entries []OrderBookEntry
DirtyEntries *datastructures.TypedSyncMap[string, OrderBookEntry]
}
func (c *CachedSortedOrderBookEntries) DeepCopy() *CachedSortedOrderBookEntries {
return &CachedSortedOrderBookEntries{
Entries: utils.Map(c.Entries, func(e OrderBookEntry) OrderBookEntry { return e.DeepCopy() }),
DirtyEntries: c.DirtyEntries.DeepCopy(func(e OrderBookEntry) OrderBookEntry { return e.DeepCopy() }),
}
}
func (c *CachedSortedOrderBookEntries) AddDirtyEntry(entry OrderBookEntry) {
c.DirtyEntries.Store(entry.GetPrice().String(), entry)
}
type OrderBookEntry interface {
GetPrice() sdk.Dec
GetEntry() *OrderEntry
DeepCopy() OrderBookEntry
}
func (m *LongBook) GetPrice() sdk.Dec {
if m != nil {
return m.Price
}
return sdk.ZeroDec()
}
func (m *LongBook) DeepCopy() OrderBookEntry {
allocations := []*Allocation{}
for _, allo := range m.Entry.Allocations {
allocations = append(allocations, &Allocation{
OrderId: allo.OrderId,
Quantity: allo.Quantity,
Account: allo.Account,
})
}
newOrderEntry := OrderEntry{
Price: m.Entry.Price,
Quantity: m.Entry.Quantity,
PriceDenom: m.Entry.PriceDenom,
AssetDenom: m.Entry.AssetDenom,
Allocations: allocations,
}
return &LongBook{
Price: m.Price,
Entry: &newOrderEntry,
}
}
func (m *ShortBook) GetPrice() sdk.Dec {
if m != nil {
return m.Price
}
return sdk.ZeroDec()
}
func (m *ShortBook) DeepCopy() OrderBookEntry {
allocations := []*Allocation{}
for _, allo := range m.Entry.Allocations {
allocations = append(allocations, &Allocation{
OrderId: allo.OrderId,
Quantity: allo.Quantity,
Account: allo.Account,
})
}
newOrderEntry := OrderEntry{
Price: m.Entry.Price,
Quantity: m.Entry.Quantity,
PriceDenom: m.Entry.PriceDenom,
AssetDenom: m.Entry.AssetDenom,
Allocations: allocations,
}
return &ShortBook{
Price: m.Price,
Entry: &newOrderEntry,
}
}