-
Notifications
You must be signed in to change notification settings - Fork 19
/
positions.go
415 lines (374 loc) · 11 KB
/
positions.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
// 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 plugins
import (
"context"
"sync"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/subscribers"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/protos/vega"
"github.com/pkg/errors"
)
var ErrMarketNotFound = errors.New("could not find market")
// SE SettleEvent - common denominator between SPE & SDE.
type SE interface {
events.Event
PartyID() string
MarketID() string
Price() *num.Uint
Timestamp() int64
}
// SPE SettlePositionEvent.
type SPE interface {
SE
PositionFactor() num.Decimal
Trades() []events.TradeSettlement
Timestamp() int64
}
// SDE SettleDistressedEvent.
type SDE interface {
SE
Margin() *num.Uint
Timestamp() int64
}
// LSE LossSocializationEvent.
type LSE interface {
events.Event
PartyID() string
MarketID() string
Amount() *num.Int
Timestamp() int64
}
// DOC DistressedOrdersClosedEvent.
type DOC interface {
events.Event
MarketID() string
Parties() []string
}
// DPE DistressedPositionsEvent.
type DPE interface {
events.Event
MarketID() string
DistressedParties() []string
SafeParties() []string
}
// Positions plugin taking settlement data to build positions API data.
type Positions struct {
*subscribers.Base
mu *sync.RWMutex
data map[string]map[string]Position
}
func NewPositions(ctx context.Context) *Positions {
return &Positions{
Base: subscribers.NewBase(ctx, 10, true),
mu: &sync.RWMutex{},
data: map[string]map[string]Position{},
}
}
func (p *Positions) Push(evts ...events.Event) {
if len(evts) == 0 {
return
}
// lock here, because some of these events are sent in batch (if not all of them)
p.mu.Lock()
for _, e := range evts {
switch te := e.(type) {
case SPE:
p.updatePosition(te)
case SDE:
p.updateSettleDestressed(te)
case LSE:
p.applyLossSocialization(te)
case DOC:
p.applyDistressedOrders(te)
case DPE:
p.applyDistressedPositions(te)
}
}
p.mu.Unlock()
}
func (p *Positions) applyDistressedPositions(e DPE) {
marketID := e.MarketID()
partyPos, ok := p.data[marketID]
if !ok {
return
}
for _, party := range e.DistressedParties() {
if pos, ok := partyPos[party]; ok {
pos.state = vega.PositionStatus_POSITION_STATUS_DISTRESSED
partyPos[party] = pos
}
}
for _, party := range e.SafeParties() {
if pos, ok := partyPos[party]; ok {
pos.state = vega.PositionStatus_POSITION_STATUS_UNSPECIFIED
partyPos[party] = pos
}
}
p.data[marketID] = partyPos
}
func (p *Positions) applyDistressedOrders(e DOC) {
marketID, parties := e.MarketID(), e.Parties()
partyPos, ok := p.data[marketID]
if !ok {
return
}
for _, party := range parties {
if pos, ok := partyPos[party]; ok {
pos.state = vega.PositionStatus_POSITION_STATUS_ORDERS_CLOSED
partyPos[party] = pos
}
}
p.data[marketID] = partyPos
}
func (p *Positions) applyLossSocialization(e LSE) {
marketID, partyID, amountLoss := e.MarketID(), e.PartyID(), num.DecimalFromInt(e.Amount())
pos, ok := p.data[marketID][partyID]
if !ok {
return
}
if amountLoss.IsNegative() {
pos.loss = pos.loss.Add(amountLoss)
} else {
pos.adjustment = pos.adjustment.Add(amountLoss)
}
pos.RealisedPnlFP = pos.RealisedPnlFP.Add(amountLoss)
pos.RealisedPnl = pos.RealisedPnl.Add(amountLoss)
pos.Position.UpdatedAt = e.Timestamp()
p.data[marketID][partyID] = pos
}
func (p *Positions) updatePosition(e SPE) {
mID, tID := e.MarketID(), e.PartyID()
if _, ok := p.data[mID]; !ok {
p.data[mID] = map[string]Position{}
}
calc, ok := p.data[mID][tID]
if !ok {
calc = seToProto(e)
}
updateSettlePosition(&calc, e)
calc.Position.UpdatedAt = e.Timestamp()
p.data[mID][tID] = calc
}
func (p *Positions) updateSettleDestressed(e SDE) {
mID, tID := e.MarketID(), e.PartyID()
if _, ok := p.data[mID]; !ok {
p.data[mID] = map[string]Position{}
}
calc, ok := p.data[mID][tID]
if !ok {
calc = seToProto(e)
}
margin := e.Margin()
calc.RealisedPnl = calc.RealisedPnl.Add(calc.UnrealisedPnl)
calc.RealisedPnlFP = calc.RealisedPnlFP.Add(calc.UnrealisedPnlFP)
calc.OpenVolume = 0
calc.UnrealisedPnl = num.DecimalZero()
calc.AverageEntryPrice = num.UintZero()
// realised P&L includes whatever we had in margin account at this point
dMargin := num.DecimalFromUint(margin)
calc.RealisedPnl = calc.RealisedPnl.Sub(dMargin)
calc.RealisedPnlFP = calc.RealisedPnlFP.Sub(dMargin)
// @TODO average entry price shouldn't be affected(?)
// the volume now is zero, though, so we'll end up moving this position to storage
calc.UnrealisedPnlFP = num.DecimalZero()
calc.AverageEntryPriceFP = num.DecimalZero()
calc.Position.UpdatedAt = e.Timestamp()
calc.state = vega.PositionStatus_POSITION_STATUS_CLOSED_OUT
p.data[mID][tID] = calc
}
// GetPositionsByMarketAndParty get the position of a single party in a given market.
func (p *Positions) GetPositionsByMarketAndParty(market, party string) (*types.Position, error) {
p.mu.RLock()
defer p.mu.RUnlock()
mp, ok := p.data[market]
if !ok {
return nil, nil
}
pos, ok := mp[party]
if !ok {
return nil, nil
}
return &pos.Position, nil
}
func (p *Positions) GetStateByMarketAndParty(market, party string) (vega.PositionStatus, error) {
p.mu.RLock()
defer p.mu.RUnlock()
mp, ok := p.data[market]
if !ok {
return vega.PositionStatus_POSITION_STATUS_UNSPECIFIED, nil
}
if pos, ok := mp[party]; ok {
return pos.state, nil
}
return vega.PositionStatus_POSITION_STATUS_UNSPECIFIED, nil
}
// GetPositionsByParty get all positions for a given party.
func (p *Positions) GetPositionsByParty(party string) ([]*types.Position, error) {
p.mu.RLock()
defer p.mu.RUnlock()
// at most, party is active in all markets
positions := make([]*types.Position, 0, len(p.data))
for _, parties := range p.data {
if pos, ok := parties[party]; ok {
positions = append(positions, &pos.Position)
}
}
if len(positions) == 0 {
return nil, nil
// return nil, ErrPartyNotFound
}
return positions, nil
}
func (p *Positions) GetPositionStatesByParty(party string) ([]vega.PositionStatus, error) {
p.mu.RLock()
defer p.mu.RUnlock()
// max 1 state per market
states := make([]vega.PositionStatus, 0, len(p.data))
for _, parties := range p.data {
if pos, ok := parties[party]; ok {
states = append(states, pos.state)
}
}
return states, nil
}
// GetAllPositions returns all positions, across markets.
func (p *Positions) GetAllPositions() ([]*types.Position, error) {
p.mu.RLock()
defer p.mu.RUnlock()
var pos []*types.Position
for k := range p.data {
// guesstimate what the slice cap ought to be: number of markets * number of parties in 1 market
pos = make([]*types.Position, 0, len(p.data)*len(p.data[k]))
break
}
for _, parties := range p.data {
for _, tp := range parties {
tp := tp
pos = append(pos, &tp.Position)
}
}
return pos, nil
}
// GetPositionsByMarket get all party positions in a given market.
func (p *Positions) GetPositionsByMarket(market string) ([]*types.Position, error) {
p.mu.RLock()
defer p.mu.RUnlock()
mp, ok := p.data[market]
if !ok {
return nil, ErrMarketNotFound
}
s := make([]*types.Position, 0, len(mp))
for _, tp := range mp {
tp := tp
s = append(s, &tp.Position)
}
return s, nil
}
func calculateOpenClosedVolume(currentOpenVolume, tradedVolume int64) (int64, int64) {
if currentOpenVolume != 0 && ((currentOpenVolume > 0) != (tradedVolume > 0)) {
var closedVolume int64
if absUint64(tradedVolume) > absUint64(currentOpenVolume) {
closedVolume = currentOpenVolume
} else {
closedVolume = -tradedVolume
}
return tradedVolume + closedVolume, closedVolume
}
return tradedVolume, 0
}
func closeV(p *Position, closedVolume int64, tradedPrice *num.Uint, positionFactor num.Decimal) num.Decimal {
if closedVolume == 0 {
return num.DecimalZero()
}
realisedPnlDelta := num.DecimalFromUint(tradedPrice).Sub(p.AverageEntryPriceFP).Mul(num.DecimalFromInt64(closedVolume)).Div(positionFactor)
p.RealisedPnlFP = p.RealisedPnlFP.Add(realisedPnlDelta)
p.OpenVolume -= closedVolume
return realisedPnlDelta
}
func updateVWAP(vwap num.Decimal, volume int64, addVolume int64, addPrice *num.Uint) num.Decimal {
if volume+addVolume == 0 {
return num.DecimalZero()
}
volumeDec := num.DecimalFromInt64(volume)
addVolumeDec := num.DecimalFromInt64(addVolume)
addPriceDec := num.DecimalFromUint(addPrice)
// return ((vwap * float64(volume)) + (float64(addPrice) * float64(addVolume))) / (float64(volume) + float64(addVolume))
return vwap.Mul(volumeDec).Add(addPriceDec.Mul(addVolumeDec)).Div(volumeDec.Add(addVolumeDec))
}
func openV(p *Position, openedVolume int64, tradedPrice *num.Uint) {
// calculate both average entry price here.
p.AverageEntryPriceFP = updateVWAP(p.AverageEntryPriceFP, p.OpenVolume, openedVolume, tradedPrice)
p.OpenVolume += openedVolume
}
func mtm(p *Position, markPrice *num.Uint, positionFactor num.Decimal) {
if p.OpenVolume == 0 {
p.UnrealisedPnlFP = num.DecimalZero()
p.UnrealisedPnl = num.DecimalZero()
return
}
markPriceDec := num.DecimalFromUint(markPrice)
openVolumeDec := num.DecimalFromInt64(p.OpenVolume)
// p.UnrealisedPnlFP = float64(p.OpenVolume) * (float64(markPrice) - p.AverageEntryPriceFP)
p.UnrealisedPnlFP = openVolumeDec.Mul(markPriceDec.Sub(p.AverageEntryPriceFP)).Div(positionFactor)
}
func updateSettlePosition(p *Position, e SPE) {
for _, t := range e.Trades() {
pr := t.Price()
openedVolume, closedVolume := calculateOpenClosedVolume(p.OpenVolume, t.Size())
_ = closeV(p, closedVolume, pr, e.PositionFactor())
openV(p, openedVolume, pr)
p.AverageEntryPrice, _ = num.UintFromDecimal(p.AverageEntryPriceFP.Round(0))
p.RealisedPnl = p.RealisedPnlFP.Round(0)
}
mtm(p, e.Price(), e.PositionFactor())
p.UnrealisedPnl = p.UnrealisedPnlFP.Round(0)
}
type Position struct {
types.Position
AverageEntryPriceFP num.Decimal
RealisedPnlFP num.Decimal
UnrealisedPnlFP num.Decimal
// what the party lost because of loss socialization
loss num.Decimal
// what a party was missing which triggered loss socialization
adjustment num.Decimal
state vega.PositionStatus
}
func seToProto(e SE) Position {
return Position{
Position: types.Position{
MarketID: e.MarketID(),
PartyID: e.PartyID(),
},
AverageEntryPriceFP: num.DecimalZero(),
RealisedPnlFP: num.DecimalZero(),
UnrealisedPnlFP: num.DecimalZero(),
}
}
func absUint64(v int64) uint64 {
if v < 0 {
v *= -1
}
return uint64(v)
}
func (p *Positions) Types() []events.Type {
return []events.Type{
events.SettlePositionEvent,
events.SettleDistressedEvent,
events.LossSocializationEvent,
events.DistressedOrdersClosedEvent,
events.DistressedPositionsEvent,
}
}