-
Notifications
You must be signed in to change notification settings - Fork 19
/
market_activity_tracker.go
1071 lines (966 loc) · 40.3 KB
/
market_activity_tracker.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) 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 common
import (
"context"
"encoding/hex"
"fmt"
"sort"
"strings"
"time"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
lproto "code.vegaprotocol.io/vega/libs/proto"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
proto "code.vegaprotocol.io/vega/protos/vega"
)
const (
// this the maximum supported window size for any metric.
maxWindowSize = 100
// to avoid using decimal calculation we're scaling the time weight by the scaling factor and keep working with integers.
scalingFactor = int64(10000000)
u64ScalingFactor = uint64(scalingFactor)
)
var (
uScalingFactor = num.NewUint(u64ScalingFactor)
dSscalingFactor = num.DecimalFromInt64(scalingFactor)
)
type twPosition struct {
position uint64 // abs last recorded position
t time.Time // time of last recorded position
currentEpochTWPosition uint64 // current epoch's running time weighted position (scaled by scaling factor)
}
type twNotional struct {
notional *num.Uint // last position's price
t time.Time // time of last recorded notional position
currentEpochTWNotional *num.Uint // current epoch's running time weightd notional position
}
// marketTracker tracks the activity in the markets in terms of fees and value.
type marketTracker struct {
asset string
makerFeesReceived map[string]*num.Uint
makerFeesPaid map[string]*num.Uint
lpFees map[string]*num.Uint
totalMakerFeesReceived *num.Uint
totalMakerFeesPaid *num.Uint
totalLpFees *num.Uint
twPosition map[string]*twPosition
partyM2M map[string]num.Decimal
twNotional map[string]*twNotional
// historical data.
epochMakerFeesReceived []map[string]*num.Uint
epochMakerFeesPaid []map[string]*num.Uint
epochLpFees []map[string]*num.Uint
epochTotalMakerFeesReceived []*num.Uint
epochTotalMakerFeesPaid []*num.Uint
epochTotalLpFees []*num.Uint
epochTimeWeightedPosition []map[string]uint64
epochTimeWeightedNotional []map[string]*num.Uint
epochPartyM2M []map[string]num.Decimal
valueTraded *num.Uint
proposersPaid map[string]struct{} // identifier of payout_asset : funder : markets_in_scope
proposer string
readyToDelete bool
allPartiesCache map[string]struct{}
}
// MarketActivityTracker tracks how much fees are paid and received for a market by parties by epoch.
type MarketActivityTracker struct {
log *logging.Logger
assetToMarketTrackers map[string]map[string]*marketTracker
eligibilityChecker EligibilityChecker
currentEpoch uint64
epochStartTime time.Time
ss *snapshotState
teams Teams
balanceChecker AccountBalanceChecker
minEpochsInTeamForRewardEligibility uint64
partyContributionCache map[string][]*types.PartyContributionScore
partyTakerNotionalVolume map[string]*num.Uint
}
// NewMarketActivityTracker instantiates the fees tracker.
func NewMarketActivityTracker(log *logging.Logger, teams Teams, balanceChecker AccountBalanceChecker) *MarketActivityTracker {
mat := &MarketActivityTracker{
assetToMarketTrackers: map[string]map[string]*marketTracker{},
ss: &snapshotState{},
log: log,
balanceChecker: balanceChecker,
teams: teams,
partyContributionCache: map[string][]*types.PartyContributionScore{},
partyTakerNotionalVolume: map[string]*num.Uint{},
}
return mat
}
func (mat *MarketActivityTracker) OnMinEpochsInTeamForRewardEligibilityUpdated(_ context.Context, value int64) error {
mat.minEpochsInTeamForRewardEligibility = uint64(value)
return nil
}
// NeedsInitialisation is a heuristc migration - if there is no time weighted position data when restoring from snapshot, we will restore
// positions from the market. This will only happen on the one time migration from a version preceding the new metrics. If we're already on a
// new version, either there are no timeweighted positions and no positions or there are time weighted positions and they will not be restored.
func (mat *MarketActivityTracker) NeedsInitialisation(asset, market string) bool {
if tracker, ok := mat.getMarketTracker(asset, market); ok {
return len(tracker.twPosition) == 0
}
return false
}
// GetProposer returns the proposer of the market or empty string if the market doesn't exist.
func (mat *MarketActivityTracker) GetProposer(market string) string {
for _, markets := range mat.assetToMarketTrackers {
m, ok := markets[market]
if ok {
return m.proposer
}
}
return ""
}
func (mat *MarketActivityTracker) SetEligibilityChecker(eligibilityChecker EligibilityChecker) {
mat.eligibilityChecker = eligibilityChecker
}
// MarketProposed is called when the market is proposed and adds the market to the tracker.
func (mat *MarketActivityTracker) MarketProposed(asset, marketID, proposer string) {
markets, ok := mat.assetToMarketTrackers[asset]
if ok {
if _, ok := markets[marketID]; ok {
return
}
}
tracker := &marketTracker{
asset: asset,
proposer: proposer,
proposersPaid: map[string]struct{}{},
readyToDelete: false,
valueTraded: num.UintZero(),
makerFeesReceived: map[string]*num.Uint{},
makerFeesPaid: map[string]*num.Uint{},
lpFees: map[string]*num.Uint{},
totalMakerFeesReceived: num.UintZero(),
totalMakerFeesPaid: num.UintZero(),
totalLpFees: num.UintZero(),
twPosition: map[string]*twPosition{},
partyM2M: map[string]num.Decimal{},
twNotional: map[string]*twNotional{},
epochTotalMakerFeesReceived: []*num.Uint{},
epochTotalMakerFeesPaid: []*num.Uint{},
epochTotalLpFees: []*num.Uint{},
epochMakerFeesReceived: []map[string]*num.Uint{},
epochMakerFeesPaid: []map[string]*num.Uint{},
epochLpFees: []map[string]*num.Uint{},
epochPartyM2M: []map[string]num.Decimal{},
epochTimeWeightedPosition: []map[string]uint64{},
epochTimeWeightedNotional: []map[string]*num.Uint{},
allPartiesCache: map[string]struct{}{},
}
if ok {
markets[marketID] = tracker
} else {
mat.assetToMarketTrackers[asset] = map[string]*marketTracker{marketID: tracker}
}
}
// AddValueTraded records the value of a trade done in the given market.
func (mat *MarketActivityTracker) AddValueTraded(asset, marketID string, value *num.Uint) {
markets, ok := mat.assetToMarketTrackers[asset]
if !ok || markets[marketID] == nil {
return
}
markets[marketID].valueTraded.AddSum(value)
}
// GetMarketsWithEligibleProposer gets all the markets within the given asset (or just all the markets in scope passed as a parameter) that
// are eligible for proposer bonus.
func (mat *MarketActivityTracker) GetMarketsWithEligibleProposer(asset string, markets []string, payoutAsset string, funder string) []*types.MarketContributionScore {
var mkts []string
if len(markets) > 0 {
mkts = markets
} else {
if len(asset) > 0 {
for m := range mat.assetToMarketTrackers[asset] {
mkts = append(mkts, m)
}
} else {
for _, markets := range mat.assetToMarketTrackers {
for mkt := range markets {
mkts = append(mkts, mkt)
}
}
}
sort.Strings(mkts)
}
assets := []string{}
if len(asset) > 0 {
assets = append(assets, asset)
} else {
for k := range mat.assetToMarketTrackers {
assets = append(assets, k)
}
sort.Strings(assets)
}
eligibleMarkets := []string{}
for _, a := range assets {
for _, v := range mkts {
if t, ok := mat.getMarketTracker(a, v); ok && (len(asset) == 0 || t.asset == asset) && mat.IsMarketEligibleForBonus(a, v, payoutAsset, markets, funder) {
eligibleMarkets = append(eligibleMarkets, v)
}
}
}
if len(eligibleMarkets) <= 0 {
return nil
}
scores := make([]*types.MarketContributionScore, 0, len(eligibleMarkets))
numMarkets := num.DecimalFromInt64(int64(len(eligibleMarkets)))
totalScore := num.DecimalZero()
for _, v := range eligibleMarkets {
score := num.DecimalFromInt64(1).Div(numMarkets)
scores = append(scores, &types.MarketContributionScore{
Asset: asset,
Market: v,
Score: score,
Metric: proto.DispatchMetric_DISPATCH_METRIC_MARKET_VALUE,
})
totalScore = totalScore.Add(score)
}
mat.clipScoresAt1(scores, totalScore)
scoresString := ""
for _, mcs := range scores {
scoresString += mcs.Market + ":" + mcs.Score.String() + ","
}
mat.log.Info("markets contibutions:", logging.String("asset", asset), logging.String("metric", proto.DispatchMetric_name[int32(proto.DispatchMetric_DISPATCH_METRIC_MARKET_VALUE)]), logging.String("market-scores", scoresString[:len(scoresString)-1]))
return scores
}
func (mat *MarketActivityTracker) clipScoresAt1(scores []*types.MarketContributionScore, totalScore num.Decimal) {
if totalScore.LessThanOrEqual(num.DecimalFromInt64(1)) {
return
}
// if somehow the total scores are > 1 clip the largest one
sort.SliceStable(scores, func(i, j int) bool { return scores[i].Score.GreaterThan(scores[j].Score) })
delta := totalScore.Sub(num.DecimalFromInt64(1))
scores[0].Score = num.MaxD(num.DecimalZero(), scores[0].Score.Sub(delta))
// sort by market id for consistency
sort.SliceStable(scores, func(i, j int) bool { return scores[i].Market < scores[j].Market })
}
// MarkProposerPaid marks the proposer of the market as having been paid proposer bonus.
func (mat *MarketActivityTracker) MarkPaidProposer(asset, market, payoutAsset string, marketsInScope []string, funder string) {
markets := strings.Join(marketsInScope[:], "_")
if len(marketsInScope) == 0 {
markets = "all"
}
if mts, ok := mat.assetToMarketTrackers[asset]; ok {
t, ok := mts[market]
if !ok {
return
}
ID := fmt.Sprintf("%s:%s:%s", payoutAsset, funder, markets)
if _, ok := t.proposersPaid[ID]; !ok {
t.proposersPaid[ID] = struct{}{}
}
}
}
// IsMarketEligibleForBonus returns true is the market proposer is eligible for market proposer bonus and has not been
// paid for the combination of payout asset and marketsInScope.
// The proposer is not market as having been paid until told to do so (if actually paid).
func (mat *MarketActivityTracker) IsMarketEligibleForBonus(asset, market, payoutAsset string, marketsInScope []string, funder string) bool {
t, ok := mat.getMarketTracker(asset, market)
if !ok {
return false
}
markets := strings.Join(marketsInScope[:], "_")
if len(marketsInScope) == 0 {
markets = "all"
}
marketIsInScope := false
for _, v := range marketsInScope {
if v == market {
marketIsInScope = true
break
}
}
if len(marketsInScope) == 0 {
markets = "all"
marketIsInScope = true
}
if !marketIsInScope {
return false
}
ID := fmt.Sprintf("%s:%s:%s", payoutAsset, funder, markets)
_, paid := t.proposersPaid[ID]
return !paid && mat.eligibilityChecker.IsEligibleForProposerBonus(market, t.valueTraded)
}
// GetAllMarketIDs returns all the current market IDs.
func (mat *MarketActivityTracker) GetAllMarketIDs() []string {
mIDs := []string{}
for _, markets := range mat.assetToMarketTrackers {
for k := range markets {
mIDs = append(mIDs, k)
}
}
sort.Strings(mIDs)
return mIDs
}
// MarketTrackedForAsset returns whether the given market is seen to have the given asset by the tracker.
func (mat *MarketActivityTracker) MarketTrackedForAsset(market, asset string) bool {
if markets, ok := mat.assetToMarketTrackers[asset]; ok {
if _, ok = markets[market]; ok {
return true
}
}
return false
}
// removeMarket is called when the market is removed from the network. It is not immediately removed to give a chance for rewards to be paid at the end of the epoch for activity during the epoch.
// Instead it is marked for removal and will be removed at the beginning of the next epoch.
func (mat *MarketActivityTracker) RemoveMarket(asset, marketID string) {
if markets, ok := mat.assetToMarketTrackers[asset]; ok {
if m, ok := markets[marketID]; ok {
m.readyToDelete = true
}
}
}
// onEpochEvent is called when the state of the epoch changes, we only care about new epochs starting.
func (mat *MarketActivityTracker) OnEpochEvent(_ context.Context, epoch types.Epoch) {
if epoch.Action == proto.EpochAction_EPOCH_ACTION_START {
mat.epochStartTime = epoch.StartTime
mat.partyContributionCache = map[string][]*types.PartyContributionScore{}
mat.clearDeletedMarkets()
mat.clearNotionalTakerVolume()
}
if epoch.Action == proto.EpochAction_EPOCH_ACTION_END {
for _, market := range mat.assetToMarketTrackers {
for _, mt := range market {
mt.processNotionalEndOfEpoch(epoch.StartTime, epoch.EndTime)
mt.processPositionEndOfEpoch(epoch.StartTime, epoch.EndTime)
mt.processM2MEndOfEpoch()
mt.clearFeeActivity()
}
}
}
mat.currentEpoch = epoch.Seq
}
func (mat *MarketActivityTracker) clearDeletedMarkets() {
for _, mts := range mat.assetToMarketTrackers {
for k, mt := range mts {
if mt.readyToDelete {
delete(mts, k)
}
}
}
}
// clearFeeActivity is called at the end of the epoch. It deletes markets that are pending to be removed and resets the fees paid for the epoch.
func (mt *marketTracker) clearFeeActivity() {
if len(mt.epochMakerFeesReceived) == maxWindowSize {
mt.epochMakerFeesReceived = mt.epochMakerFeesReceived[1:]
mt.epochMakerFeesPaid = mt.epochMakerFeesPaid[1:]
mt.epochLpFees = mt.epochLpFees[1:]
mt.epochTotalMakerFeesReceived = mt.epochTotalMakerFeesReceived[1:]
mt.epochTotalMakerFeesPaid = mt.epochTotalMakerFeesPaid[1:]
mt.epochTotalLpFees = mt.epochTotalLpFees[1:]
}
mt.epochMakerFeesReceived = append(mt.epochMakerFeesReceived, mt.makerFeesReceived)
mt.epochMakerFeesPaid = append(mt.epochMakerFeesReceived, mt.makerFeesPaid)
mt.epochLpFees = append(mt.epochLpFees, mt.lpFees)
mt.makerFeesReceived = map[string]*num.Uint{}
mt.makerFeesPaid = map[string]*num.Uint{}
mt.lpFees = map[string]*num.Uint{}
mt.epochTotalMakerFeesReceived = append(mt.epochTotalMakerFeesReceived, mt.totalMakerFeesReceived)
mt.epochTotalMakerFeesPaid = append(mt.epochTotalMakerFeesPaid, mt.totalMakerFeesPaid)
mt.epochTotalLpFees = append(mt.epochTotalLpFees, mt.totalLpFees)
mt.totalMakerFeesReceived = num.UintZero()
mt.totalMakerFeesPaid = num.UintZero()
mt.totalLpFees = num.UintZero()
}
// UpdateFeesFromTransfers takes a slice of transfers and if they represent fees it updates the market fee tracker.
// market is guaranteed to exist in the mapping as it is added when proposed.
func (mat *MarketActivityTracker) UpdateFeesFromTransfers(asset, market string, transfers []*types.Transfer) {
for _, t := range transfers {
mt, ok := mat.getMarketTracker(asset, market)
if !ok {
continue
}
mt.allPartiesCache[t.Owner] = struct{}{}
switch t.Type {
case types.TransferTypeMakerFeePay:
mat.addFees(mt.makerFeesPaid, t.Owner, t.Amount.Amount, mt.totalMakerFeesPaid)
case types.TransferTypeMakerFeeReceive:
mat.addFees(mt.makerFeesReceived, t.Owner, t.Amount.Amount, mt.totalMakerFeesReceived)
case types.TransferTypeLiquidityFeeNetDistribute, types.TransferTypeSlaPerformanceBonusDistribute:
mat.addFees(mt.lpFees, t.Owner, t.Amount.Amount, mt.totalLpFees)
default:
}
}
}
// addFees records fees paid/received in a given metric to a given party.
func (mat *MarketActivityTracker) addFees(m map[string]*num.Uint, party string, amount *num.Uint, total *num.Uint) {
if _, ok := m[party]; !ok {
m[party] = amount.Clone()
total.AddSum(amount)
return
}
m[party].AddSum(amount)
total.AddSum(amount)
}
// getMarketTracker finds the market tracker for a market if one exists (one must exist if the market is active).
func (mat *MarketActivityTracker) getMarketTracker(asset, market string) (*marketTracker, bool) {
if _, ok := mat.assetToMarketTrackers[asset]; !ok {
return nil, false
}
tracker, ok := mat.assetToMarketTrackers[asset][market]
if !ok {
return nil, false
}
return tracker, true
}
// RestorePosition restores a position as if it were acquired at the beginning of the epoch. This is purely for migration from an old version.
func (mat *MarketActivityTracker) RestorePosition(asset, party, market string, pos int64, price *num.Uint, positionFactor num.Decimal) {
mat.RecordPosition(asset, party, market, pos, price, positionFactor, mat.epochStartTime)
}
// RecordPosition passes the position of the party in the asset/market to the market tracker to be recorded.
func (mat *MarketActivityTracker) RecordPosition(asset, party, market string, pos int64, price *num.Uint, positionFactor num.Decimal, time time.Time) {
if tracker, ok := mat.getMarketTracker(asset, market); ok {
tracker.allPartiesCache[party] = struct{}{}
absPos := uint64(0)
if pos > 0 {
absPos = uint64(pos)
} else if pos < 0 {
absPos = uint64(-pos)
}
notional, _ := num.UintFromDecimal(num.UintZero().Mul(num.NewUint(absPos), price).ToDecimal().Div(positionFactor))
tracker.recordPosition(party, absPos, positionFactor, time, mat.epochStartTime)
tracker.recordNotional(party, notional, time, mat.epochStartTime)
}
}
// RecordM2M passes the mark to market win/loss transfer amount to the asset/market tracker to be recorded.
func (mat *MarketActivityTracker) RecordM2M(asset, party, market string, amount num.Decimal) {
if tracker, ok := mat.getMarketTracker(asset, market); ok {
tracker.allPartiesCache[party] = struct{}{}
tracker.recordM2M(party, amount)
}
}
func (mat *MarketActivityTracker) getAllParties(asset string, mkts []string) map[string]struct{} {
parties := map[string]struct{}{}
includedMarkets := mkts
if len(mkts) == 0 {
includedMarkets = mat.GetAllMarketIDs()
}
if len(includedMarkets) > 0 {
trackers, ok := mat.assetToMarketTrackers[asset]
if !ok {
return map[string]struct{}{}
}
for _, mkt := range includedMarkets {
mt, ok := trackers[mkt]
if !ok {
continue
}
mktParties := mt.allPartiesCache
for k := range mktParties {
parties[k] = struct{}{}
}
}
}
return parties
}
func (mat *MarketActivityTracker) getPartiesInScope(ds *vega.DispatchStrategy) []string {
var parties []string
if ds.IndividualScope == vega.IndividualScope_INDIVIDUAL_SCOPE_IN_TEAM {
parties = mat.teams.GetAllPartiesInTeams(mat.minEpochsInTeamForRewardEligibility)
} else if ds.IndividualScope == vega.IndividualScope_INDIVIDUAL_SCOPE_ALL {
parties = sortedK(mat.getAllParties(ds.AssetForMetric, ds.Markets))
} else if ds.IndividualScope == vega.IndividualScope_INDIVIDUAL_SCOPE_NOT_IN_TEAM {
parties = sortedK(excludePartiesInTeams(mat.getAllParties(ds.AssetForMetric, ds.Markets), mat.teams.GetAllPartiesInTeams(mat.minEpochsInTeamForRewardEligibility)))
}
return parties
}
// CalculateMetricForIndividuals calculates the metric corresponding to the dispatch strategy and returns a slice of the contribution scores of the parties.
// Markets in scope are the ones passed in the dispatch strategy if any or all available markets for the asset for metric.
// Parties in scope depend on the `IndividualScope_INDIVIDUAL_SCOPE_IN_TEAM` and can include all parties, only those in teams, and only those not in teams.
func (mat *MarketActivityTracker) CalculateMetricForIndividuals(ds *vega.DispatchStrategy) []*types.PartyContributionScore {
p, _ := lproto.Marshal(ds)
hash := hex.EncodeToString(crypto.Hash(p))
if pc, ok := mat.partyContributionCache[hash]; ok {
return pc
}
parties := mat.getPartiesInScope(ds)
stakingRequirement, _ := num.UintFromString(ds.StakingRequirement, 10)
notionalRequirement, _ := num.UintFromString(ds.NotionalTimeWeightedAveragePositionRequirement, 10)
partyContributions := mat.calculateMetricForIndividuals(ds.AssetForMetric, parties, ds.Markets, ds.Metric, stakingRequirement, notionalRequirement, int(ds.WindowLength))
// we do this calculation at the end of the epoch and clear it in the beginning of the next epoch, i.e. within the same block therefore it saves us
// redundant calculation and has no snapshot implication
mat.partyContributionCache[hash] = partyContributions
return partyContributions
}
// CalculateMetricForTeams calculates the metric for teams and their respective team members for markets in scope of the dispatch strategy.
func (mat *MarketActivityTracker) CalculateMetricForTeams(ds *vega.DispatchStrategy) ([]*types.PartyContributionScore, map[string][]*types.PartyContributionScore) {
var teamMembers map[string][]string
if tsl := len(ds.TeamScope); tsl > 0 {
teamMembers = make(map[string][]string, len(ds.TeamScope))
for _, team := range ds.TeamScope {
teamMembers[team] = mat.teams.GetTeamMembers(team, mat.minEpochsInTeamForRewardEligibility)
}
} else {
teamMembers = mat.teams.GetAllTeamsWithParties(mat.minEpochsInTeamForRewardEligibility)
}
stakingRequirement, _ := num.UintFromString(ds.StakingRequirement, 10)
notionalRequirement, _ := num.UintFromString(ds.NotionalTimeWeightedAveragePositionRequirement, 10)
topNDecimal := num.MustDecimalFromString(ds.NTopPerformers)
return mat.calculateMetricForTeams(ds.AssetForMetric, teamMembers, ds.Markets, ds.Metric, stakingRequirement, notionalRequirement, int(ds.WindowLength), topNDecimal)
}
func (mat *MarketActivityTracker) isEligibleForReward(asset, party string, markets []string, minStakingBalanceRequired *num.Uint, notionalTimeWeightedAveragePositionRequired *num.Uint) bool {
if !minStakingBalanceRequired.IsZero() {
balance, err := mat.balanceChecker.GetAvailableBalance(party)
if err != nil || balance.LT(minStakingBalanceRequired) {
return false
}
}
if !notionalTimeWeightedAveragePositionRequired.IsZero() {
if mat.getTWNotionalPosition(asset, party, markets).LT(notionalTimeWeightedAveragePositionRequired) {
return false
}
}
return true
}
func (mat *MarketActivityTracker) calculateMetricForIndividuals(asset string, parties []string, markets []string, metric vega.DispatchMetric, minStakingBalanceRequired *num.Uint, notionalTimeWeightedAveragePositionRequired *num.Uint, windowSize int) []*types.PartyContributionScore {
ret := make([]*types.PartyContributionScore, 0, len(parties))
for _, party := range parties {
if !mat.isEligibleForReward(asset, party, markets, minStakingBalanceRequired, notionalTimeWeightedAveragePositionRequired) {
continue
}
score := mat.calculateMetricForParty(asset, party, markets, metric, windowSize)
if score.IsZero() {
continue
}
ret = append(ret, &types.PartyContributionScore{Party: party, Score: score})
}
return ret
}
// CalculateMetricForTeams returns a slice of metrics for the team and a slice of metrics for each team member.
func (mat *MarketActivityTracker) calculateMetricForTeams(asset string, teams map[string][]string, marketsInScope []string, metric vega.DispatchMetric, minStakingBalanceRequired *num.Uint, notionalTimeWeightedAveragePositionRequired *num.Uint, windowSize int, topN num.Decimal) ([]*types.PartyContributionScore, map[string][]*types.PartyContributionScore) {
teamScores := make([]*types.PartyContributionScore, 0, len(teams))
teamKeys := make([]string, 0, len(teams))
for k := range teams {
teamKeys = append(teamKeys, k)
}
sort.Strings(teamKeys)
ps := make(map[string][]*types.PartyContributionScore, len(teamScores))
for _, t := range teamKeys {
ts, teamMemberScores := mat.calculateMetricForTeam(asset, teams[t], marketsInScope, metric, minStakingBalanceRequired, notionalTimeWeightedAveragePositionRequired, windowSize, topN)
if ts.IsZero() {
continue
}
teamScores = append(teamScores, &types.PartyContributionScore{Party: t, Score: ts})
ps[t] = teamMemberScores
}
return teamScores, ps
}
// calculateMetricForTeam returns the metric score for team and a slice of the score for each of its members.
func (mat *MarketActivityTracker) calculateMetricForTeam(asset string, parties []string, marketsInScope []string, metric vega.DispatchMetric, minStakingBalanceRequired *num.Uint, notionalTimeWeightedAveragePositionRequired *num.Uint, windowSize int, topN num.Decimal) (num.Decimal, []*types.PartyContributionScore) {
return calculateMetricForTeamUtil(asset, parties, marketsInScope, metric, minStakingBalanceRequired, notionalTimeWeightedAveragePositionRequired, windowSize, topN, mat.isEligibleForReward, mat.calculateMetricForParty)
}
func calculateMetricForTeamUtil(asset string,
parties []string,
marketsInScope []string,
metric vega.DispatchMetric,
minStakingBalanceRequired *num.Uint,
notionalTimeWeightedAveragePositionRequired *num.Uint,
windowSize int,
topN num.Decimal,
isEligibleForReward func(asset, party string, markets []string, minStakingBalanceRequired *num.Uint, notionalTimeWeightedAveragePositionRequired *num.Uint) bool,
calculateMetricForParty func(asset, party string, marketsInScope []string, metric vega.DispatchMetric, windowSize int) num.Decimal,
) (num.Decimal, []*types.PartyContributionScore) {
teamPartyScores := []*types.PartyContributionScore{}
for _, party := range parties {
if !isEligibleForReward(asset, party, marketsInScope, minStakingBalanceRequired, notionalTimeWeightedAveragePositionRequired) {
continue
}
teamPartyScores = append(teamPartyScores, &types.PartyContributionScore{Party: party, Score: calculateMetricForParty(asset, party, marketsInScope, metric, windowSize)})
}
if len(teamPartyScores) == 0 {
return num.DecimalZero(), []*types.PartyContributionScore{}
}
sort.Slice(teamPartyScores, func(i, j int) bool {
return teamPartyScores[i].Score.GreaterThan(teamPartyScores[j].Score)
})
maxIndex := int(topN.Mul(num.DecimalFromInt64(int64(len(parties)))).IntPart())
// ensure non-zero, otherwise we have a divide-by-zero panic on our hands
if maxIndex == 0 {
maxIndex = 1
}
if len(teamPartyScores) < maxIndex {
maxIndex = len(teamPartyScores)
}
if maxIndex == 0 {
return num.DecimalZero(), teamPartyScores
}
total := num.DecimalZero()
for i := 0; i < maxIndex; i++ {
total = total.Add(teamPartyScores[i].Score)
}
return total.Div(num.DecimalFromInt64(int64(maxIndex))), teamPartyScores
}
// calculateMetricForParty returns the value of a reward metric score for the given party for markets of the givem assets which are in scope over the given window size.
func (mat *MarketActivityTracker) calculateMetricForParty(asset, party string, marketsInScope []string, metric vega.DispatchMetric, windowSize int) num.Decimal {
// exclude unsupported metrics
if metric == vega.DispatchMetric_DISPATCH_METRIC_MARKET_VALUE {
mat.log.Panic("unexpected disaptch metric market value here")
}
if metric == vega.DispatchMetric_DISPATCH_METRIC_VALIDATOR_RANKING {
mat.log.Panic("unexpected disaptch metric validator ranking here")
}
uTotal := uint64(0)
total := num.DecimalZero()
marketTotal := num.DecimalZero()
returns := make([]num.Decimal, windowSize)
assetTrackers, ok := mat.assetToMarketTrackers[asset]
if !ok {
return num.DecimalZero()
}
markets := marketsInScope
if len(markets) == 0 {
markets = make([]string, 0, len(assetTrackers))
for k := range assetTrackers {
markets = append(markets, k)
}
}
// for each market in scope, for each epoch in the time window get the metric entry, sum up for each epoch in the time window and divide by window size (or calculate variance - for volatility)
for _, market := range markets {
marketTracker := assetTrackers[market]
if marketTracker == nil {
continue
}
switch metric {
case vega.DispatchMetric_DISPATCH_METRIC_AVERAGE_POSITION:
uTotal += marketTracker.getPositionMetricTotal(party, windowSize)
case vega.DispatchMetric_DISPATCH_METRIC_RELATIVE_RETURN:
total = total.Add(marketTracker.getRelativeReturnMetricTotal(party, windowSize))
case vega.DispatchMetric_DISPATCH_METRIC_RETURN_VOLATILITY:
r, ok := marketTracker.getReturns(party, windowSize)
if !ok {
continue
}
for i, ret := range r {
returns[i] = returns[i].Add(ret)
}
case vega.DispatchMetric_DISPATCH_METRIC_MAKER_FEES_PAID:
total = total.Add(getFees(marketTracker.epochMakerFeesPaid, party, windowSize))
marketTotal = marketTotal.Add(getTotalFees(marketTracker.epochTotalMakerFeesPaid, windowSize))
case vega.DispatchMetric_DISPATCH_METRIC_MAKER_FEES_RECEIVED:
total = total.Add(getFees(marketTracker.epochMakerFeesReceived, party, windowSize))
marketTotal = marketTotal.Add(getTotalFees(marketTracker.epochTotalMakerFeesReceived, windowSize))
case vega.DispatchMetric_DISPATCH_METRIC_LP_FEES_RECEIVED:
total = total.Add(getFees(marketTracker.epochLpFees, party, windowSize))
marketTotal = marketTotal.Add(getTotalFees(marketTracker.epochTotalLpFees, windowSize))
}
}
switch metric {
case vega.DispatchMetric_DISPATCH_METRIC_AVERAGE_POSITION:
// descaling the total tw position metric by dividing by the scaling factor
return num.DecimalFromInt64(int64(uTotal)).Div(num.DecimalFromInt64(int64(windowSize) * scalingFactor))
case vega.DispatchMetric_DISPATCH_METRIC_RELATIVE_RETURN:
return num.MaxD(num.DecimalZero(), total.Div(num.DecimalFromInt64(int64(windowSize))))
case vega.DispatchMetric_DISPATCH_METRIC_RETURN_VOLATILITY:
filteredReturns := []num.Decimal{}
for _, d := range returns {
if d.IsPositive() {
filteredReturns = append(filteredReturns, d)
}
}
if len(filteredReturns) == 0 {
return num.DecimalZero()
}
variance, _ := num.Variance(filteredReturns)
return variance
case vega.DispatchMetric_DISPATCH_METRIC_MAKER_FEES_PAID, vega.DispatchMetric_DISPATCH_METRIC_MAKER_FEES_RECEIVED, vega.DispatchMetric_DISPATCH_METRIC_LP_FEES_RECEIVED:
if marketTotal.IsZero() {
return num.DecimalZero()
}
return total.Div(marketTotal)
default:
mat.log.Panic("unexpected metric")
}
return num.DecimalZero()
}
func (mat *MarketActivityTracker) RecordNotionalTakerVolume(party string, volumeToAdd *num.Uint) {
if _, ok := mat.partyTakerNotionalVolume[party]; !ok {
mat.partyTakerNotionalVolume[party] = volumeToAdd
return
}
mat.partyTakerNotionalVolume[party].AddSum(volumeToAdd)
}
func (mat *MarketActivityTracker) clearNotionalTakerVolume() {
mat.partyTakerNotionalVolume = map[string]*num.Uint{}
}
func (mat *MarketActivityTracker) NotionalTakerVolumeForAllParties() map[types.PartyID]*num.Uint {
res := make(map[types.PartyID]*num.Uint, len(mat.partyTakerNotionalVolume))
for k, u := range mat.partyTakerNotionalVolume {
res[types.PartyID(k)] = u.Clone()
}
return res
}
func (mat *MarketActivityTracker) NotionalTakerVolumeForParty(party string) *num.Uint {
if _, ok := mat.partyTakerNotionalVolume[party]; !ok {
return num.UintZero()
}
return mat.partyTakerNotionalVolume[party].Clone()
}
func updateNotional(n *twNotional, notional *num.Uint, t, tn int64, time time.Time) {
tnOverT := num.UintZero()
tnOverTComp := uScalingFactor.Clone()
if t != 0 {
tnOverT = num.NewUint(uint64(tn / t))
tnOverTComp = tnOverTComp.Sub(tnOverTComp, tnOverT)
}
p1 := num.UintZero().Mul(n.currentEpochTWNotional, tnOverTComp)
p2 := num.UintZero().Mul(n.notional, tnOverT)
n.currentEpochTWNotional = num.UintZero().Div(p1.AddSum(p2), uScalingFactor)
n.notional = notional
n.t = time
}
// recordNotional tracks the time weighted average notional for the party per market.
// notional = abs(position) x price / position_factor
// price in asset decimals.
func (mt *marketTracker) recordNotional(party string, notional *num.Uint, time time.Time, epochStartTime time.Time) {
if _, ok := mt.twNotional[party]; !ok {
mt.twNotional[party] = &twNotional{
t: time,
notional: notional,
currentEpochTWNotional: num.UintZero(),
}
return
}
t := int64(time.Sub(epochStartTime).Seconds())
n := mt.twNotional[party]
tn := int64(time.Sub(n.t).Seconds()) * scalingFactor
updateNotional(n, notional, t, tn, time)
}
func (mt *marketTracker) processNotionalEndOfEpoch(epochStartTime time.Time, endEpochTime time.Time) {
t := int64(endEpochTime.Sub(epochStartTime).Seconds())
m := make(map[string]*num.Uint, len(mt.twNotional))
for party, twNotional := range mt.twNotional {
tn := int64(endEpochTime.Sub(twNotional.t).Seconds()) * scalingFactor
updateNotional(twNotional, twNotional.notional, t, tn, endEpochTime)
m[party] = twNotional.currentEpochTWNotional.Clone()
}
if len(mt.epochTimeWeightedNotional) == maxWindowSize {
mt.epochTimeWeightedNotional = mt.epochTimeWeightedNotional[1:]
}
mt.epochTimeWeightedNotional = append(mt.epochTimeWeightedNotional, m)
}
func (mat *MarketActivityTracker) getTWNotionalPosition(asset, party string, markets []string) *num.Uint {
total := num.UintZero()
mkts := markets
if len(mkts) == 0 {
mkts = make([]string, 0, len(mat.assetToMarketTrackers[asset]))
for k := range mat.assetToMarketTrackers[asset] {
mkts = append(mkts, k)
}
sort.Strings(mkts)
}
for _, mkt := range mkts {
if tracker, ok := mat.getMarketTracker(asset, mkt); ok {
if twNotional, ok := tracker.twNotional[party]; ok {
total.AddSum(twNotional.currentEpochTWNotional)
}
}
}
return total
}
func updatePosition(toi *twPosition, scaledAbsPos uint64, t, tn int64, time time.Time) {
tnOverT := uint64(0)
if t != 0 {
tnOverT = uint64(tn / t)
}
toi.currentEpochTWPosition = (toi.currentEpochTWPosition*(u64ScalingFactor-tnOverT) + (toi.position * tnOverT)) / u64ScalingFactor
toi.position = scaledAbsPos
toi.t = time
}
// recordPosition records the current position of a party and the time of change. If there is a previous position then it is time weight updated with respect to the time
// it has been in place during the epoch.
func (mt *marketTracker) recordPosition(party string, absPos uint64, positionFactor num.Decimal, time time.Time, epochStartTime time.Time) {
if party == "network" {
return
}
// scale by scaling factor and divide by position factor
// by design the scaling factor is greater than the max position factor which allows no loss of precision
scaledAbsPos := num.UintZero().Mul(num.NewUint(absPos), uScalingFactor).ToDecimal().Div(positionFactor).IntPart()
if _, ok := mt.twPosition[party]; !ok {
mt.twPosition[party] = &twPosition{
position: uint64(scaledAbsPos),
t: time,
currentEpochTWPosition: 0,
}
return
}
toi := mt.twPosition[party]
t := int64(time.Sub(epochStartTime).Seconds())
tn := int64(time.Sub(toi.t).Seconds()) * scalingFactor
updatePosition(toi, uint64(scaledAbsPos), t, tn, time)
}
// processPositionEndOfEpoch is called at the end of the epoch, calcualtes the time weight of the current position and moves it to the next epoch, and records
// the time weighted position of the current epoch in the history.
func (mt *marketTracker) processPositionEndOfEpoch(epochStartTime time.Time, endEpochTime time.Time) {
t := int64(endEpochTime.Sub(epochStartTime).Seconds())
m := make(map[string]uint64, len(mt.twPosition))
for party, toi := range mt.twPosition {
tn := int64(endEpochTime.Sub(toi.t).Seconds()) * scalingFactor
updatePosition(toi, toi.position, t, tn, endEpochTime)
m[party] = toi.currentEpochTWPosition
}
if len(mt.epochTimeWeightedPosition) == maxWindowSize {
mt.epochTimeWeightedPosition = mt.epochTimeWeightedPosition[1:]
}
mt.epochTimeWeightedPosition = append(mt.epochTimeWeightedPosition, m)
}
// //// return metric //////
// recordM2M records the amount corresponding to mark to market (profit or loss).
func (mt *marketTracker) recordM2M(party string, amount num.Decimal) {
if party == "network" {
return
}
if _, ok := mt.partyM2M[party]; !ok {
mt.partyM2M[party] = amount
return
}
mt.partyM2M[party] = mt.partyM2M[party].Add(amount)
}
// processM2MEndOfEpoch is called at the end of the epoch to reset the running total for the next epoch and record the total m2m in the ended epoch.
func (mt *marketTracker) processM2MEndOfEpoch() {
m := map[string]num.Decimal{}
for party, m2m := range mt.partyM2M {
p := mt.twPosition[party].currentEpochTWPosition
var v num.Decimal
if p == 0 {
v = num.DecimalZero()
} else {
v = m2m.Div(num.DecimalFromInt64(int64(p)).Div(dSscalingFactor))
}
m[party] = v
mt.partyM2M[party] = num.DecimalZero()
}
if len(mt.epochPartyM2M) == maxWindowSize {
mt.epochPartyM2M = mt.epochPartyM2M[1:]
}
mt.epochPartyM2M = append(mt.epochPartyM2M, m)
}
// getReturns returns a slice of the total of the party's return by epoch in the given window.
func (mt *marketTracker) getReturns(party string, windowSize int) ([]num.Decimal, bool) {
if _, ok := mt.partyM2M[party]; !ok {
return []num.Decimal{}, false
}
returns := make([]num.Decimal, 0, windowSize)
if len(mt.epochPartyM2M) == 0 {
return []num.Decimal{}, false
}
for i := 0; i < windowSize; i++ {
ind := len(mt.epochPartyM2M) - i - 1
if ind < 0 {
returns = append(returns, num.DecimalZero())
continue
}
epochData := mt.epochPartyM2M[ind]
returns = append(returns, epochData[party])
}
return returns, true
}
// getPositionMetricTotal returns the sum of the epoch's time weighted position over the time window.
func (mt *marketTracker) getPositionMetricTotal(party string, windowSize int) uint64 {
return calcTotalForWindowUint64(party, mt.epochTimeWeightedPosition, windowSize)
}
// getRelativeReturnMetricTotal returns the sum of the relative returns over the given window.
func (mt *marketTracker) getRelativeReturnMetricTotal(party string, windowSize int) num.Decimal {
return calcTotalForWindowD(party, mt.epochPartyM2M, windowSize)
}
// getFees returns the total fees paid/received (depending on what feeData represents) by the party over the given window size.
func getFees(feeData []map[string]*num.Uint, party string, windowSize int) num.Decimal {
return calcTotalForWindowU(party, feeData, windowSize)
}
// getTotalFees returns the total fees of the given type measured over the window size.
func getTotalFees(totalFees []*num.Uint, windowSize int) num.Decimal {
if len(totalFees) == 0 {
return num.DecimalZero()
}
total := num.UintZero()
for i := 0; i < windowSize; i++ {
ind := len(totalFees) - i - 1
if ind < 0 {
return total.ToDecimal()
}
total.AddSum(totalFees[ind])
}
return total.ToDecimal()
}
// calcTotalForWindowU returns the total relevant data from the given slice starting from the given dataIdx-1, going back <window_size> elements.