-
Notifications
You must be signed in to change notification settings - Fork 21
/
position.go
277 lines (242 loc) · 7.78 KB
/
position.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
// 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 sqlsubscribers
import (
"context"
"fmt"
"sync"
"github.com/pkg/errors"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/datanode/entities"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/protos/vega"
)
type tradeEvent interface {
MarketID() string
IsParty(id string) bool // we don't use this one, but it's to make sure we identify the event correctly
Trade() vega.Trade
}
type positionEventBase interface {
events.Event
MarketID() string
PartyID() string
Timestamp() int64
}
type positionSettlement interface {
positionEventBase
Price() *num.Uint
PositionFactor() num.Decimal
Trades() []events.TradeSettlement
}
type lossSocialization interface {
positionEventBase
Amount() *num.Int
}
type settleDistressed interface {
positionEventBase
Margin() *num.Uint
}
type ordersClosed interface {
MarketID() string
Parties() []string
}
type settleMarket interface {
positionEventBase
SettledPrice() *num.Uint
PositionFactor() num.Decimal
}
type distressedPositions interface {
MarketID() string
SafeParties() []string
DistressedParties() []string
}
type PositionStore interface {
Add(context.Context, entities.Position) error
GetByMarket(ctx context.Context, marketID string) ([]entities.Position, error)
GetByMarketAndParty(ctx context.Context, marketID string, partyID string) (entities.Position, error)
GetByMarketAndParties(ctx context.Context, marketID string, parties []string) ([]entities.Position, error)
Flush(ctx context.Context) error
}
type MarketSvc interface {
GetMarketScalingFactor(ctx context.Context, marketID string) (num.Decimal, bool)
}
type Position struct {
subscriber
store PositionStore
mktSvc MarketSvc
mutex sync.Mutex
}
func NewPosition(store PositionStore, mktSvc MarketSvc) *Position {
t := &Position{
store: store,
mktSvc: mktSvc,
}
return t
}
func (p *Position) Types() []events.Type {
return []events.Type{
events.SettlePositionEvent,
events.SettleDistressedEvent,
events.LossSocializationEvent,
events.SettleMarketEvent,
events.TradeEvent,
events.DistressedOrdersClosedEvent,
events.DistressedPositionsEvent,
}
}
func (p *Position) Flush(ctx context.Context) error {
err := p.store.Flush(ctx)
return errors.Wrap(err, "flushing positions")
}
func (p *Position) Push(ctx context.Context, evt events.Event) error {
switch event := evt.(type) {
case positionSettlement:
return p.handlePositionSettlement(ctx, event)
case lossSocialization:
return p.handleLossSocialization(ctx, event)
case settleDistressed:
return p.handleSettleDistressed(ctx, event)
case settleMarket:
return p.handleSettleMarket(ctx, event)
case tradeEvent:
return p.handleTradeEvent(ctx, event)
case ordersClosed:
return p.handleOrdersClosedEvent(ctx, event)
case distressedPositions:
return p.handleDistressedPositions(ctx, event)
default:
return errors.Errorf("unknown event type %s", evt.Type().String())
}
}
func (p *Position) handleDistressedPositions(ctx context.Context, event distressedPositions) error {
p.mutex.Lock()
defer p.mutex.Unlock()
parties := append(event.DistressedParties(), event.SafeParties()...)
positions, err := p.store.GetByMarketAndParties(ctx, event.MarketID(), parties)
if err != nil {
return fmt.Errorf("failed to get positions: %w", err)
}
for _, pos := range positions {
pos.ToggleDistressedStatus()
if err := p.updatePosition(ctx, pos); err != nil {
return fmt.Errorf("failed to update position: %w", err)
}
}
return nil
}
func (p *Position) handleOrdersClosedEvent(ctx context.Context, event ordersClosed) error {
p.mutex.Lock()
defer p.mutex.Unlock()
positions, err := p.store.GetByMarketAndParties(ctx, event.MarketID(), event.Parties())
if err != nil {
return fmt.Errorf("failed to get positions: %w", err)
}
for _, pos := range positions {
pos.UpdateOrdersClosed()
if err := p.updatePosition(ctx, pos); err != nil {
return fmt.Errorf("failed to update position: %w", err)
}
}
return nil
}
func (p *Position) handleTradeEvent(ctx context.Context, event tradeEvent) error {
trade := event.Trade()
p.mutex.Lock()
defer p.mutex.Unlock()
sf, ok := p.mktSvc.GetMarketScalingFactor(ctx, trade.MarketId)
if !ok {
return fmt.Errorf("failed to get market scaling factor for market %s", trade.MarketId)
}
buyer, seller := p.getPositionsByTrade(ctx, trade)
buyer.UpdateWithTrade(trade, false, sf)
// this can't really result in an error...
_ = p.updatePosition(ctx, buyer)
seller.UpdateWithTrade(trade, true, sf)
return p.updatePosition(ctx, seller)
}
func (p *Position) handlePositionSettlement(ctx context.Context, event positionSettlement) error {
p.mutex.Lock()
defer p.mutex.Unlock()
pos := p.getPosition(ctx, event)
pos.UpdateWithPositionSettlement(event)
return p.updatePosition(ctx, pos)
}
func (p *Position) handleLossSocialization(ctx context.Context, event lossSocialization) error {
p.mutex.Lock()
defer p.mutex.Unlock()
pos := p.getPosition(ctx, event)
pos.UpdateWithLossSocialization(event)
return p.updatePosition(ctx, pos)
}
func (p *Position) handleSettleDistressed(ctx context.Context, event settleDistressed) error {
p.mutex.Lock()
defer p.mutex.Unlock()
pos := p.getPosition(ctx, event)
pos.UpdateWithSettleDistressed(event)
return p.updatePosition(ctx, pos)
}
func (p *Position) handleSettleMarket(ctx context.Context, event settleMarket) error {
p.mutex.Lock()
defer p.mutex.Unlock()
pos, err := p.store.GetByMarket(ctx, event.MarketID())
if err != nil {
return errors.Wrap(err, "error getting positions")
}
for i := range pos {
pos[i].UpdateWithSettleMarket(event)
err := p.updatePosition(ctx, pos[i])
if err != nil {
return errors.Wrap(err, "error updating position")
}
}
return nil
}
func (p *Position) getPositionsByTrade(ctx context.Context, trade vega.Trade) (buyer entities.Position, seller entities.Position) {
mID := entities.MarketID(trade.MarketId)
bID := entities.PartyID(trade.Buyer)
sID := entities.PartyID(trade.Seller)
var err error
buyer, err = p.store.GetByMarketAndParty(ctx, mID.String(), bID.String())
if errors.Is(err, entities.ErrNotFound) {
buyer = entities.NewEmptyPosition(mID, bID)
} else if err != nil {
// this is a really bad thing to happen :)
panic("unable to query for existing position")
}
seller, err = p.store.GetByMarketAndParty(ctx, mID.String(), sID.String())
if errors.Is(err, entities.ErrNotFound) {
seller = entities.NewEmptyPosition(mID, sID)
} else if err != nil {
// this is a really bad thing to happen :)
panic("unable to query for existing position")
}
return buyer, seller
}
func (p *Position) getPosition(ctx context.Context, e positionEventBase) entities.Position {
mID := entities.MarketID(e.MarketID())
pID := entities.PartyID(e.PartyID())
position, err := p.store.GetByMarketAndParty(ctx, mID.String(), pID.String())
if errors.Is(err, entities.ErrNotFound) {
return entities.NewEmptyPosition(mID, pID)
}
if err != nil {
// TODO: Can we do something less drastic here? If we can't get existing positions
// things are a bit screwed as we'll start writing down wrong aggregates.
panic("unable to query for existing position")
}
return position
}
func (p *Position) updatePosition(ctx context.Context, pos entities.Position) error {
pos.VegaTime = p.vegaTime
err := p.store.Add(ctx, pos)
return errors.Wrap(err, "error updating position")
}