-
Notifications
You must be signed in to change notification settings - Fork 20
/
priced_stop_orders.go
245 lines (201 loc) · 6.03 KB
/
priced_stop_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
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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package stoporders
import (
"fmt"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/num"
v1 "code.vegaprotocol.io/vega/protos/vega/snapshot/v1"
"github.com/google/btree"
"golang.org/x/exp/slices"
)
type ordersAtPrice struct {
price *num.Uint
orders []string
}
func (o *ordersAtPrice) String() string {
return fmt.Sprintf("%s:%v", o.price.String(), o.orders)
}
func lessFuncOrdersAtPrice(a, b *ordersAtPrice) bool {
return a.price.LT(b.price)
}
type orderAtPriceStat struct {
price *num.Uint
direction types.StopOrderTriggerDirection
}
type PricedStopOrders struct {
// mapping table for stop order ID
// help finding them back in the trees.
orders map[string]orderAtPriceStat
fallsBelow *btree.BTreeG[*ordersAtPrice]
risesAbove *btree.BTreeG[*ordersAtPrice]
}
func NewPricedStopOrders() *PricedStopOrders {
return &PricedStopOrders{
orders: map[string]orderAtPriceStat{},
fallsBelow: btree.NewG(2, lessFuncOrdersAtPrice),
risesAbove: btree.NewG(2, lessFuncOrdersAtPrice),
}
}
func NewPricedStopOrdersFromProto(p *v1.PricedStopOrders) *PricedStopOrders {
pso := NewPricedStopOrders()
for _, v := range p.FallsBellow {
for _, oid := range v.Orders {
price, overflow := num.UintFromString(v.Price, 10)
if overflow {
panic(fmt.Sprintf("invalid uint from snapshot, would overflow: %s", v.Price))
}
pso.Insert(oid, price, types.StopOrderTriggerDirectionFallsBelow)
}
}
for _, v := range p.RisesAbove {
for _, oid := range v.Orders {
price, overflow := num.UintFromString(v.Price, 10)
if overflow {
panic(fmt.Sprintf("invalid uint from snapshot, would overflow: %s", v.Price))
}
pso.Insert(oid, price, types.StopOrderTriggerDirectionRisesAbove)
}
}
return pso
}
func (p *PricedStopOrders) ToProto() *v1.PricedStopOrders {
return &v1.PricedStopOrders{
FallsBellow: p.serialize(p.fallsBelow),
RisesAbove: p.serialize(p.risesAbove),
}
}
func (p *PricedStopOrders) serialize(tree *btree.BTreeG[*ordersAtPrice]) []*v1.OrdersAtPrice {
out := []*v1.OrdersAtPrice{}
tree.Ascend(func(item *ordersAtPrice) bool {
out = append(out, &v1.OrdersAtPrice{
Price: item.price.String(),
Orders: slices.Clone(item.orders),
})
return true
})
return out
}
func (p *PricedStopOrders) PriceUpdated(newPrice *num.Uint) []string {
// first remove if price fallsBelow
orderIDs := p.trigger(
p.fallsBelow,
p.fallsBelow.DescendGreaterThan,
newPrice.Clone().Sub(newPrice.Clone(), num.NewUint(1)),
)
// then if it rises above?
orderIDs = append(orderIDs,
p.trigger(
p.risesAbove,
p.risesAbove.AscendLessThan,
newPrice.Clone().Add(newPrice.Clone(), num.NewUint(1)),
)...,
)
// here we can cleanup the mapping table as well
for _, v := range orderIDs {
delete(p.orders, v)
}
return orderIDs
}
func (p *PricedStopOrders) trigger(
tree *btree.BTreeG[*ordersAtPrice],
findFn func(pivot *ordersAtPrice, iterator btree.ItemIteratorG[*ordersAtPrice]),
newPrice *num.Uint,
) []string {
orderIDs := []string{}
toDelete := []*num.Uint{}
findFn(&ordersAtPrice{price: newPrice}, func(item *ordersAtPrice) bool {
orderIDs = append(orderIDs, item.orders...)
toDelete = append(toDelete, item.price)
return true
})
// now we delete all the unused tree item
for _, p := range toDelete {
tree.Delete(&ordersAtPrice{price: p})
}
return orderIDs
}
func (p *PricedStopOrders) Insert(
id string, price *num.Uint, direction types.StopOrderTriggerDirection,
) {
p.orders[id] = orderAtPriceStat{price.Clone(), direction}
switch direction {
case types.StopOrderTriggerDirectionFallsBelow:
p.insertOrUpdate(p.fallsBelow, id, price.Clone())
case types.StopOrderTriggerDirectionRisesAbove:
p.insertOrUpdate(p.risesAbove, id, price.Clone())
}
}
func (p *PricedStopOrders) insertOrUpdate(
tree *btree.BTreeG[*ordersAtPrice], id string, price *num.Uint,
) {
oap, ok := tree.Get(&ordersAtPrice{price: price})
if !ok {
oap = &ordersAtPrice{price: price}
}
// add to the list
oap.orders = append(oap.orders, id)
// finally insert or whatever
tree.ReplaceOrInsert(oap)
}
func (p *PricedStopOrders) Remove(id string) error {
oaps, ok := p.orders[id]
if !ok {
return ErrOrderNotFound
}
delete(p.orders, id)
var err error
switch oaps.direction {
case types.StopOrderTriggerDirectionFallsBelow:
err = p.removeAndMaybeDelete(p.fallsBelow, id, oaps.price)
case types.StopOrderTriggerDirectionRisesAbove:
err = p.removeAndMaybeDelete(p.risesAbove, id, oaps.price)
}
return err
}
func (p *PricedStopOrders) removeAndMaybeDelete(
tree *btree.BTreeG[*ordersAtPrice], id string, price *num.Uint,
) error {
// just declare it first, we may reuse it by the end
item := &ordersAtPrice{price: price}
oap, ok := tree.Get(item)
if !ok {
return ErrPriceNotFound
}
before := len(oap.orders)
for n, v := range oap.orders {
// this is our ID
if v == id {
oap.orders = slices.Delete(oap.orders, n, n+1)
break
}
}
// didn't found the order, we can just panic it should never happen
if before == len(oap.orders) {
panic("order not in tree but in mapping table")
}
// now if the len is 0, we probably don't need that
// price level anymore
if len(oap.orders) <= 0 {
tree.Delete(item)
}
return nil
}
func (p *PricedStopOrders) DumpRisesAbove() string {
return dumpTree(p.risesAbove)
}
func (p *PricedStopOrders) DumpFallsBelow() string {
return dumpTree(p.fallsBelow)
}