-
Notifications
You must be signed in to change notification settings - Fork 22
/
market.go
4962 lines (4328 loc) · 171 KB
/
market.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 future
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
"code.vegaprotocol.io/vega/core/assets"
"code.vegaprotocol.io/vega/core/collateral"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/execution/common"
"code.vegaprotocol.io/vega/core/execution/liquidation"
"code.vegaprotocol.io/vega/core/execution/stoporders"
"code.vegaprotocol.io/vega/core/fee"
"code.vegaprotocol.io/vega/core/idgeneration"
liquiditytarget "code.vegaprotocol.io/vega/core/liquidity/target"
"code.vegaprotocol.io/vega/core/liquidity/v2"
"code.vegaprotocol.io/vega/core/markets"
"code.vegaprotocol.io/vega/core/matching"
"code.vegaprotocol.io/vega/core/metrics"
"code.vegaprotocol.io/vega/core/monitor"
"code.vegaprotocol.io/vega/core/monitor/price"
"code.vegaprotocol.io/vega/core/positions"
"code.vegaprotocol.io/vega/core/products"
"code.vegaprotocol.io/vega/core/risk"
"code.vegaprotocol.io/vega/core/settlement"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/core/types/statevar"
vegacontext "code.vegaprotocol.io/vega/libs/context"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/libs/ptr"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
vegapb "code.vegaprotocol.io/vega/protos/vega"
eventspb "code.vegaprotocol.io/vega/protos/vega/events/v1"
"golang.org/x/exp/maps"
)
// TargetStakeCalculator interface.
type TargetStakeCalculator interface {
types.StateProvider
RecordOpenInterest(oi uint64, now time.Time) error
GetTargetStake(rf types.RiskFactor, now time.Time, markPrice *num.Uint) *num.Uint
GetTheoreticalTargetStake(rf types.RiskFactor, now time.Time, markPrice *num.Uint, trades []*types.Trade) *num.Uint
UpdateScalingFactor(sFactor num.Decimal) error
UpdateTimeWindow(tWindow time.Duration)
StopSnapshots()
UpdateParameters(types.TargetStakeParameters)
}
// Market represents an instance of a market in vega and is in charge of calling
// the engines in order to process all transactions.
type Market struct {
log *logging.Logger
idgen common.IDGenerator
mkt *types.Market
closingAt time.Time
timeService common.TimeService
mu sync.Mutex
lastTradedPrice *num.Uint
priceFactor *num.Uint
// own engines
matching *matching.CachedOrderBook
tradableInstrument *markets.TradableInstrument
risk *risk.Engine
position *positions.SnapshotEngine
settlement *settlement.SnapshotEngine
fee *fee.Engine
referralDiscountRewardService fee.ReferralDiscountRewardService
volumeDiscountService fee.VolumeDiscountService
liquidity *common.MarketLiquidity
liquidityEngine common.LiquidityEngine
// deps engines
collateral common.Collateral
banking common.Banking
broker common.Broker
closed bool
finalFeesDistributed bool
parties map[string]struct{}
pMonitor common.PriceMonitor
tsCalc TargetStakeCalculator
as common.AuctionState
peggedOrders *common.PeggedOrders
expiringOrders *common.ExpiringOrders
// Store the previous price values so we can see what has changed
lastBestBidPrice *num.Uint
lastBestAskPrice *num.Uint
lastMidBuyPrice *num.Uint
lastMidSellPrice *num.Uint
bondPenaltyFactor num.Decimal
lastMarketValueProxy num.Decimal
marketValueWindowLength time.Duration
// Liquidity Fee
feeSplitter *common.FeeSplitter
equityShares *common.EquityShares
stateVarEngine common.StateVarEngine
marketActivityTracker *common.MarketActivityTracker
positionFactor num.Decimal // 10^pdp
assetDP uint32
settlementDataInMarket *num.Numeric
nextMTM time.Time
nextInternalCompositePriceCalc time.Time
mtmDelta time.Duration
internalCompositePriceFrequency time.Duration
settlementAsset string
succeeded bool
maxStopOrdersPerParties *num.Uint
stopOrders *stoporders.Pool
expiringStopOrders *common.ExpiringOrders
minDuration time.Duration
perp bool
stats *types.MarketStats
liquidation *liquidation.Engine // @TODO probably should be an interface for unit testing
// set to false when started
// we'll use it only once after an upgrade
// to make sure the migraton from the upgrade
// are applied properly
ensuredMigration73 bool
epoch types.Epoch
// party ID to isolated margin factor
partyMarginFactor map[string]num.Decimal
markPriceCalculator *common.CompositePriceCalculator
internalCompositePriceCalculator *common.CompositePriceCalculator
}
// NewMarket creates a new market using the market framework configuration and creates underlying engines.
func NewMarket(
ctx context.Context,
log *logging.Logger,
riskConfig risk.Config,
positionConfig positions.Config,
settlementConfig settlement.Config,
matchingConfig matching.Config,
feeConfig fee.Config,
liquidityConfig liquidity.Config,
collateralEngine common.Collateral,
oracleEngine products.OracleEngine,
mkt *types.Market,
timeService common.TimeService,
broker common.Broker,
auctionState *monitor.AuctionState,
stateVarEngine common.StateVarEngine,
marketActivityTracker *common.MarketActivityTracker,
assetDetails *assets.Asset,
peggedOrderNotify func(int64),
referralDiscountRewardService fee.ReferralDiscountRewardService,
volumeDiscountService fee.VolumeDiscountService,
banking common.Banking,
) (*Market, error) {
if len(mkt.ID) == 0 {
return nil, common.ErrEmptyMarketID
}
assetDecimals := assetDetails.DecimalPlaces()
positionFactor := num.DecimalFromFloat(10).Pow(num.DecimalFromInt64(mkt.PositionDecimalPlaces))
tradableInstrument, err := markets.NewTradableInstrument(ctx, log, mkt.TradableInstrument, mkt.ID, timeService, oracleEngine, broker, uint32(assetDecimals))
if err != nil {
return nil, fmt.Errorf("unable to instantiate a new market: %w", err)
}
priceFactor := num.NewUint(1)
if exp := assetDecimals - mkt.DecimalPlaces; exp != 0 {
priceFactor.Exp(num.NewUint(10), num.NewUint(exp))
}
// @TODO -> the raw auctionstate shouldn't be something exposed to the matching engine
// as far as matching goes: it's either an auction or not
book := matching.NewCachedOrderBook(log, matchingConfig, mkt.ID, auctionState.InAuction(), peggedOrderNotify)
asset := tradableInstrument.Instrument.Product.GetAsset()
riskEngine := risk.NewEngine(log,
riskConfig,
tradableInstrument.MarginCalculator,
tradableInstrument.RiskModel,
book,
auctionState,
timeService,
broker,
mkt.ID,
asset,
stateVarEngine,
positionFactor,
false,
nil,
mkt.LinearSlippageFactor,
mkt.QuadraticSlippageFactor,
)
settleEngine := settlement.NewSnapshotEngine(
log,
settlementConfig,
tradableInstrument.Instrument.Product,
mkt.ID,
timeService,
broker,
positionFactor,
)
positionEngine := positions.NewSnapshotEngine(log, positionConfig, mkt.ID, broker)
feeEngine, err := fee.New(log, feeConfig, *mkt.Fees, asset, positionFactor)
if err != nil {
return nil, fmt.Errorf("unable to instantiate fee engine: %w", err)
}
tsCalc := liquiditytarget.NewSnapshotEngine(*mkt.LiquidityMonitoringParameters.TargetStakeParameters, positionEngine, mkt.ID, positionFactor)
pMonitor, err := price.NewMonitor(asset, mkt.ID, tradableInstrument.RiskModel, auctionState, mkt.PriceMonitoringSettings, stateVarEngine, log)
if err != nil {
return nil, fmt.Errorf("unable to instantiate price monitoring engine: %w", err)
}
now := timeService.GetTimeNow()
liquidityEngine := liquidity.NewSnapshotEngine(
liquidityConfig, log, timeService, broker, tradableInstrument.RiskModel,
pMonitor, book, auctionState, asset, mkt.ID, stateVarEngine, positionFactor, mkt.LiquiditySLAParams)
equityShares := common.NewEquityShares(num.DecimalZero())
marketLiquidity := common.NewMarketLiquidity(
log, liquidityEngine, collateralEngine, broker, book, equityShares, marketActivityTracker,
feeEngine, common.FutureMarketType, mkt.ID, asset, priceFactor, mkt.LiquiditySLAParams.PriceRange,
)
// The market is initially created in a proposed state
mkt.State = types.MarketStateProposed
mkt.TradingMode = types.MarketTradingModeNoTrading
pending, open := auctionState.GetAuctionBegin(), auctionState.GetAuctionEnd()
// Populate the market timestamps
ts := &types.MarketTimestamps{
Proposed: now.UnixNano(),
Pending: now.UnixNano(),
}
if pending != nil {
ts.Pending = pending.UnixNano()
}
if open != nil {
ts.Open = open.UnixNano()
}
mkt.MarketTimestamps = ts
// @TODO remove this once liquidation strategy is no longer optional
// consider mkt.LiquidationStrategy is currently still treated as optional, but we use
// mkt in the events we're sending to data-node, let's set the default strategy here
// and update the mkt object so the events will accurately reflect what this is being set to
if mkt.LiquidationStrategy == nil {
mkt.LiquidationStrategy = liquidation.GetLegacyStrat()
}
le := liquidation.New(log, mkt.LiquidationStrategy, mkt.GetID(), broker, book, auctionState, timeService, marketLiquidity, positionEngine, pMonitor)
marketType := mkt.MarketType()
market := &Market{
log: log,
idgen: nil,
mkt: mkt,
matching: book,
tradableInstrument: tradableInstrument,
risk: riskEngine,
position: positionEngine,
settlement: settleEngine,
collateral: collateralEngine,
timeService: timeService,
broker: broker,
fee: feeEngine,
liquidity: marketLiquidity,
liquidityEngine: liquidityEngine, // TODO karel - consider not having this
parties: map[string]struct{}{},
as: auctionState,
pMonitor: pMonitor,
tsCalc: tsCalc,
peggedOrders: common.NewPeggedOrders(log, timeService),
expiringOrders: common.NewExpiringOrders(),
feeSplitter: common.NewFeeSplitter(),
equityShares: equityShares,
lastBestAskPrice: num.UintZero(),
lastMidSellPrice: num.UintZero(),
lastMidBuyPrice: num.UintZero(),
lastBestBidPrice: num.UintZero(),
stateVarEngine: stateVarEngine,
marketActivityTracker: marketActivityTracker,
priceFactor: priceFactor,
positionFactor: positionFactor,
nextMTM: time.Time{}, // default to zero time
maxStopOrdersPerParties: num.UintZero(),
stopOrders: stoporders.New(log),
expiringStopOrders: common.NewExpiringOrders(),
perp: marketType == types.MarketTypePerp,
referralDiscountRewardService: referralDiscountRewardService,
volumeDiscountService: volumeDiscountService,
partyMarginFactor: map[string]num.Decimal{},
liquidation: le,
banking: banking,
markPriceCalculator: common.NewCompositePriceCalculator(ctx, mkt.MarkPriceConfiguration, oracleEngine, timeService),
}
market.markPriceCalculator.SetOraclePriceScalingFunc(market.scaleOracleData)
if market.IsPerp() {
internalCompositePriceConfig := mkt.TradableInstrument.Instrument.GetPerps().InternalCompositePriceConfig
if internalCompositePriceConfig != nil {
market.internalCompositePriceCalculator = common.NewCompositePriceCalculator(ctx, internalCompositePriceConfig, oracleEngine, timeService)
market.internalCompositePriceCalculator.SetOraclePriceScalingFunc(market.scaleOracleData)
}
}
assets, _ := mkt.GetAssets()
market.settlementAsset = assets[0]
liquidityEngine.SetGetStaticPricesFunc(market.getBestStaticPricesDecimal)
switch marketType {
case types.MarketTypeFuture:
market.tradableInstrument.Instrument.Product.NotifyOnTradingTerminated(market.tradingTerminated)
market.tradableInstrument.Instrument.Product.NotifyOnSettlementData(market.settlementData)
case types.MarketTypePerp:
market.tradableInstrument.Instrument.Product.NotifyOnSettlementData(market.settlementDataPerp)
case types.MarketTypeSpot:
default:
log.Panic("unexpected market type", logging.Int("type", int(marketType)))
}
market.assetDP = uint32(assetDecimals)
return market, nil
}
func (m *Market) OnEpochEvent(ctx context.Context, epoch types.Epoch) {
if m.closed {
return
}
switch epoch.Action {
case vegapb.EpochAction_EPOCH_ACTION_START:
m.liquidity.UpdateSLAParameters(m.mkt.LiquiditySLAParams)
m.liquidity.OnEpochStart(ctx, m.timeService.GetTimeNow(), m.markPriceCalculator.GetPrice(), m.midPrice(), m.getTargetStake(), m.positionFactor)
m.epoch = epoch
case vegapb.EpochAction_EPOCH_ACTION_END:
// compute parties stats for the previous epoch
m.onEpochEndPartiesStats()
if !m.finalFeesDistributed {
m.liquidity.OnEpochEnd(ctx, m.timeService.GetTimeNow(), epoch)
}
m.banking.RegisterTradingFees(ctx, m.settlementAsset, m.fee.TotalTradingFeesPerParty())
assetQuantum, _ := m.collateral.GetAssetQuantum(m.settlementAsset)
feesStats := m.fee.GetFeesStatsOnEpochEnd(assetQuantum)
feesStats.Market = m.GetID()
feesStats.EpochSeq = epoch.Seq
m.broker.Send(events.NewFeesStatsEvent(ctx, feesStats))
}
m.updateLiquidityFee(ctx)
}
func (m *Market) OnEpochRestore(ctx context.Context, epoch types.Epoch) {
m.epoch = epoch
m.liquidityEngine.OnEpochRestore(epoch)
}
func (m *Market) IsOpeningAuction() bool {
return m.as.IsOpeningAuction()
}
func (m *Market) onEpochEndPartiesStats() {
if m.markPriceCalculator.GetPrice() == nil {
// no mark price yet, so no reason to calculate any of those
return
}
if m.stats == nil {
m.stats = &types.MarketStats{}
}
m.stats.PartiesOpenNotionalVolume = map[string]*num.Uint{}
m.stats.PartiesTotalTradeVolume = map[string]*num.Uint{}
assetQuantum, err := m.collateral.GetAssetQuantum(m.settlementAsset)
if err != nil {
m.log.Panic("couldn't get quantum for asset",
logging.MarketID(m.mkt.ID),
logging.AssetID(m.settlementAsset),
)
}
// first get the open interest per party
partiesOpenInterest := m.position.GetPartiesLowestOpenInterestForEpoch()
for p, oi := range partiesOpenInterest {
// volume
openInterestVolume := num.UintZero().Mul(num.NewUint(oi), m.markPriceCalculator.GetPrice())
// scale to position decimal
scaledOpenInterest := openInterestVolume.ToDecimal().Div(m.positionFactor)
// apply quantum
m.stats.PartiesOpenNotionalVolume[p], _ = num.UintFromDecimal(
scaledOpenInterest.Div(assetQuantum),
)
}
// first get the open interest per party
partiesTradedVolume := m.position.GetPartiesTradedVolumeForEpoch()
for p, oi := range partiesTradedVolume {
// volume
tradedVolume := num.UintZero().Mul(num.NewUint(oi), m.markPriceCalculator.GetPrice())
// scale to position decimal
scaledOpenInterest := tradedVolume.ToDecimal().Div(m.positionFactor)
// apply quantum
m.stats.PartiesTotalTradeVolume[p], _ = num.UintFromDecimal(
scaledOpenInterest.Div(assetQuantum),
)
}
}
func (m *Market) BeginBlock(ctx context.Context) {
if m.ensuredMigration73 {
return
}
m.ensuredMigration73 = true
// TODO(jeremy): remove this after the 72 upgrade
oevents := []events.Event{}
for _, oid := range m.liquidityEngine.GetLegacyOrders() {
order, foundOnBook, err := m.getOrderByID(oid)
if err != nil {
continue // err here is ErrOrderNotFound
}
if !foundOnBook {
m.log.Panic("lp order was in the pegged order list?", logging.Order(order))
}
cancellation, err := m.matching.CancelOrder(order)
if cancellation == nil || err != nil {
m.log.Panic("Failure after cancel order from matching engine",
logging.String("party-id", order.Party),
logging.String("order-id", oid),
logging.String("market", m.mkt.ID),
logging.Error(err))
}
_ = m.position.UnregisterOrder(ctx, order)
order.Status = types.OrderStatusCancelled
oevents = append(oevents, events.NewOrderEvent(ctx, order))
}
if len(oevents) > 0 {
m.broker.SendBatch(oevents)
}
// TODO(jeremy): This bit is here specifically to create account
// which should have been create with the normal process of
// submitting liquidity provisions for the market.
// should probably be removed in the near future (aft this release)
lpParties := maps.Keys(m.liquidityEngine.ProvisionsPerParty())
sort.Strings(lpParties)
for _, p := range lpParties {
_, err := m.collateral.GetOrCreatePartyLiquidityFeeAccount(
ctx, p, m.GetID(), m.GetSettlementAsset())
if err != nil {
m.log.Panic("couldn't create party liquidity fee account")
}
}
_, err := m.collateral.GetOrCreateLiquidityFeesBonusDistributionAccount(ctx, m.GetID(), m.GetSettlementAsset())
if err != nil {
m.log.Panic("failed to get bonus distribution account", logging.Error(err))
}
}
// GetPartiesStats is called at the end of the epoch, only once to
// be sent to the activity streak engine. This is using the calculated
// at the end of the epoch based on the countrer in the position engine.
// This is never sent into a snapshot as it relies on the order the
// epoch callback are executed. We expect the market OnEpoch to be called
// first, and compute the data, then the activity tracker callback to be
// called next, and retrieve the data through this method.
// The stats are reseted before being returned.
func (m *Market) GetPartiesStats() (stats *types.MarketStats) {
stats, m.stats = m.stats, &types.MarketStats{}
return stats
}
func (m *Market) IsSucceeded() bool {
return m.succeeded
}
func (m *Market) IsPerp() bool {
return m.perp
}
func (m *Market) StopSnapshots() {
m.matching.StopSnapshots()
m.position.StopSnapshots()
m.liquidityEngine.StopSnapshots()
m.settlement.StopSnapshots()
m.tsCalc.StopSnapshots()
m.liquidation.StopSnapshots()
}
func (m *Market) Mkt() *types.Market {
return m.mkt
}
func (m *Market) GetEquityShares() *common.EquityShares {
return m.equityShares
}
func (m *Market) ResetParentIDAndInsurancePoolFraction() {
m.mkt.ParentMarketID = ""
m.mkt.InsurancePoolFraction = num.DecimalZero()
}
func (m *Market) GetParentMarketID() string {
return m.mkt.ParentMarketID
}
func (m *Market) GetInsurancePoolFraction() num.Decimal {
return m.mkt.InsurancePoolFraction
}
func (m *Market) SetSucceeded() {
m.succeeded = true
}
func (m *Market) SetNextInternalCompositePriceCalc(tm time.Time) {
m.nextInternalCompositePriceCalc = tm
}
func (m *Market) SetNextMTM(tm time.Time) {
m.nextMTM = tm
}
func (m *Market) GetNextMTM() time.Time {
return m.nextMTM
}
func (m *Market) GetSettlementAsset() string {
return m.settlementAsset
}
func (m *Market) Update(ctx context.Context, config *types.Market, oracleEngine products.OracleEngine) error {
tickSizeChanged := config.TickSize.NEQ(m.mkt.TickSize)
config.TradingMode = m.mkt.TradingMode
config.State = m.mkt.State
config.MarketTimestamps = m.mkt.MarketTimestamps
recalcMargins := !config.TradableInstrument.RiskModel.Equal(m.mkt.TradableInstrument.RiskModel)
// update the liquidation strategy if required, ideally we want to use .LiquidationStrategy.EQ(), but that breaks the integration tests
// as the market config pointer is shared
if config.LiquidationStrategy != nil {
m.liquidation.Update(config.LiquidationStrategy)
}
m.mkt = config
assets, _ := config.GetAssets()
m.settlementAsset = assets[0]
if err := m.tradableInstrument.UpdateInstrument(ctx, m.log, m.mkt.TradableInstrument, m.GetID(), oracleEngine, m.broker); err != nil {
return err
}
m.risk.UpdateModel(m.stateVarEngine, m.tradableInstrument.MarginCalculator, m.tradableInstrument.RiskModel, m.mkt.LinearSlippageFactor, m.mkt.QuadraticSlippageFactor)
m.settlement.UpdateProduct(m.tradableInstrument.Instrument.Product)
m.tsCalc.UpdateParameters(*m.mkt.LiquidityMonitoringParameters.TargetStakeParameters)
m.pMonitor.UpdateSettings(m.tradableInstrument.RiskModel, m.mkt.PriceMonitoringSettings)
m.liquidity.UpdateMarketConfig(m.tradableInstrument.RiskModel, m.pMonitor)
if err := m.markPriceCalculator.UpdateConfig(ctx, oracleEngine, m.mkt.MarkPriceConfiguration); err != nil {
m.markPriceCalculator.SetOraclePriceScalingFunc(m.scaleOracleData)
return err
}
if m.IsPerp() {
internalCompositePriceConfig := m.mkt.TradableInstrument.Instrument.GetPerps().InternalCompositePriceConfig
if internalCompositePriceConfig == nil && m.internalCompositePriceCalculator != nil {
// unsubscribe existing oracles if any
m.internalCompositePriceCalculator.UpdateConfig(ctx, oracleEngine, nil)
m.internalCompositePriceCalculator = nil
} else if m.internalCompositePriceCalculator != nil {
// there was previously a intenal composite price calculator
if err := m.internalCompositePriceCalculator.UpdateConfig(ctx, oracleEngine, internalCompositePriceConfig); err != nil {
m.internalCompositePriceCalculator.SetOraclePriceScalingFunc(m.scaleOracleData)
return err
}
} else if internalCompositePriceConfig != nil {
// it's a new index calculator
m.internalCompositePriceCalculator = common.NewCompositePriceCalculator(ctx, internalCompositePriceConfig, oracleEngine, m.timeService)
m.internalCompositePriceCalculator.SetOraclePriceScalingFunc(m.scaleOracleData)
}
}
// we should not need to rebind a replacement oracle here, the m.tradableInstrument.UpdateInstrument
// call handles the callbacks for us. We only need to check the market state and unbind if needed
switch m.mkt.State {
case types.MarketStateTradingTerminated:
if !m.perp {
m.tradableInstrument.Instrument.UnsubscribeTradingTerminated(ctx)
// never hurts to check margins on a terminated, but unsettled market
recalcMargins = true
}
case types.MarketStateSettled:
// market is settled, unsubscribe all
m.tradableInstrument.Instrument.Unsubscribe(ctx)
}
if tickSizeChanged {
peggedOrders := m.matching.GetActivePeggedOrderIDs()
peggedOrders = append(peggedOrders, m.peggedOrders.GetParkedIDs()...)
for _, po := range peggedOrders {
order, err := m.matching.GetOrderByID(po)
if err != nil {
order = m.peggedOrders.GetParkedByID(po)
if order == nil {
continue
}
}
if !num.UintZero().Mod(order.PeggedOrder.Offset, m.mkt.TickSize).IsZero() {
m.cancelOrder(ctx, order.Party, order.ID)
}
}
}
m.updateLiquidityFee(ctx)
// risk model hasn't changed -> return
if !recalcMargins {
return nil
}
// We know the risk model has been updated, so we have to recalculate margin requirements
m.recheckMargin(ctx, m.position.Positions())
// update immediately during opening auction
if m.as.IsOpeningAuction() {
m.liquidity.UpdateSLAParameters(m.mkt.LiquiditySLAParams)
}
return nil
}
func (m *Market) IntoType() types.Market {
return *m.mkt.DeepClone()
}
func (m *Market) Hash() []byte {
mID := logging.String("market-id", m.GetID())
matchingHash := m.matching.Hash()
m.log.Debug("orderbook state hash", logging.Hash(matchingHash), mID)
positionHash := m.position.Hash()
m.log.Debug("positions state hash", logging.Hash(positionHash), mID)
return crypto.Hash(append(matchingHash, positionHash...))
}
func (m *Market) GetMarketState() types.MarketState {
return m.mkt.State
}
// priceToMarketPrecision
// It should never return a nil pointer.
func (m *Market) priceToMarketPrecision(price *num.Uint) *num.Uint {
// we assume the price is cloned correctly already
return price.Div(price, m.priceFactor)
}
func (m *Market) midPrice() *num.Uint {
bestBidPrice, _, _ := m.matching.BestBidPriceAndVolume()
bestOfferPrice, _, _ := m.matching.BestOfferPriceAndVolume()
two := num.NewUint(2)
midPrice := num.UintZero()
if !bestBidPrice.IsZero() && !bestOfferPrice.IsZero() {
midPrice = midPrice.Div(num.Sum(bestBidPrice, bestOfferPrice), two)
}
return midPrice
}
func (m *Market) GetMarketData() types.MarketData {
bestBidPrice, bestBidVolume, _ := m.matching.BestBidPriceAndVolume()
bestOfferPrice, bestOfferVolume, _ := m.matching.BestOfferPriceAndVolume()
bestStaticBidPrice, bestStaticBidVolume, _ := m.getBestStaticBidPriceAndVolume()
bestStaticOfferPrice, bestStaticOfferVolume, _ := m.getBestStaticAskPriceAndVolume()
// Auction related values
indicativePrice := num.UintZero()
indicativeVolume := uint64(0)
var auctionStart, auctionEnd int64
if m.as.InAuction() {
indicativePrice, indicativeVolume, _ = m.matching.GetIndicativePriceAndVolume()
if t := m.as.Start(); !t.IsZero() {
auctionStart = t.UnixNano()
}
if t := m.as.ExpiresAt(); t != nil {
auctionEnd = t.UnixNano()
}
}
// If we do not have one of the best_* prices, leave the mid price as zero
two := num.NewUint(2)
midPrice := num.UintZero()
if !bestBidPrice.IsZero() && !bestOfferPrice.IsZero() {
midPrice = midPrice.Div(num.Sum(bestBidPrice, bestOfferPrice), two)
}
staticMidPrice := num.UintZero()
if !bestStaticBidPrice.IsZero() && !bestStaticOfferPrice.IsZero() {
staticMidPrice = staticMidPrice.Div(num.Sum(bestStaticBidPrice, bestStaticOfferPrice), two)
}
var targetStake string
if m.as.InAuction() {
targetStake = m.getTheoreticalTargetStake().String()
} else {
targetStake = m.getTargetStake().String()
}
bounds := m.pMonitor.GetCurrentBounds()
for _, b := range bounds {
m.priceToMarketPrecision(b.MaxValidPrice) // effictively floors this
m.priceToMarketPrecision(b.MinValidPrice)
rp, _ := num.UintFromDecimal(b.ReferencePrice)
m.priceToMarketPrecision(rp)
b.ReferencePrice = num.DecimalFromUint(rp)
if m.priceFactor.NEQ(common.One) {
b.MinValidPrice.AddSum(common.One) // ceil
}
}
mode := m.as.Mode()
if m.mkt.TradingMode == types.MarketTradingModeNoTrading {
mode = m.mkt.TradingMode
}
var internalCompositePrice *num.Uint
var nextInternalCompositePriceCalc int64
var internalCompositePriceType vega.CompositePriceType
var internalCompositePriceState *types.CompositePriceState
pd := m.tradableInstrument.Instrument.Product.GetData(m.timeService.GetTimeNow().UnixNano())
if m.perp && pd != nil {
if m.internalCompositePriceCalculator != nil {
internalCompositePriceState = m.internalCompositePriceCalculator.GetData()
internalCompositePriceType = m.internalCompositePriceCalculator.GetConfig().CompositePriceType
internalCompositePrice = m.internalCompositePriceCalculator.GetPrice()
if internalCompositePrice == nil {
internalCompositePrice = num.UintZero()
} else {
internalCompositePrice = m.priceToMarketPrecision(internalCompositePrice)
}
nextInternalCompositePriceCalc = m.nextInternalCompositePriceCalc.UnixNano()
} else {
internalCompositePriceState = m.markPriceCalculator.GetData()
internalCompositePriceType = m.markPriceCalculator.GetConfig().CompositePriceType
internalCompositePrice = m.priceToMarketPrecision(m.getCurrentMarkPrice())
nextInternalCompositePriceCalc = m.nextMTM.UnixNano()
}
perpData := pd.Data.(*types.PerpetualData)
perpData.InternalCompositePrice = internalCompositePrice
perpData.NextInternalCompositePriceCalc = nextInternalCompositePriceCalc
perpData.InternalCompositePriceType = internalCompositePriceType
perpData.InternalCompositePriceState = internalCompositePriceState
}
md := types.MarketData{
Market: m.GetID(),
BestBidPrice: m.priceToMarketPrecision(bestBidPrice),
BestBidVolume: bestBidVolume,
BestOfferPrice: m.priceToMarketPrecision(bestOfferPrice),
BestOfferVolume: bestOfferVolume,
BestStaticBidPrice: m.priceToMarketPrecision(bestStaticBidPrice),
BestStaticBidVolume: bestStaticBidVolume,
BestStaticOfferPrice: m.priceToMarketPrecision(bestStaticOfferPrice),
BestStaticOfferVolume: bestStaticOfferVolume,
MidPrice: m.priceToMarketPrecision(midPrice),
StaticMidPrice: m.priceToMarketPrecision(staticMidPrice),
MarkPrice: m.priceToMarketPrecision(m.getCurrentMarkPrice()),
LastTradedPrice: m.priceToMarketPrecision(m.getLastTradedPrice()),
Timestamp: m.timeService.GetTimeNow().UnixNano(),
OpenInterest: m.position.GetOpenInterest(),
IndicativePrice: m.priceToMarketPrecision(indicativePrice),
IndicativeVolume: indicativeVolume,
AuctionStart: auctionStart,
AuctionEnd: auctionEnd,
MarketTradingMode: mode,
MarketState: m.mkt.State,
Trigger: m.as.Trigger(),
ExtensionTrigger: m.as.ExtensionTrigger(),
TargetStake: targetStake,
SuppliedStake: m.getSuppliedStake().String(),
PriceMonitoringBounds: bounds,
MarketValueProxy: m.lastMarketValueProxy.BigInt().String(),
LiquidityProviderFeeShare: m.equityShares.LpsToLiquidityProviderFeeShare(m.liquidityEngine.GetAverageLiquidityScores()),
LiquidityProviderSLA: m.liquidityEngine.LiquidityProviderSLAStats(m.timeService.GetTimeNow()),
NextMTM: m.nextMTM.UnixNano(),
MarketGrowth: m.equityShares.GetMarketGrowth(),
ProductData: pd,
NextNetClose: m.liquidation.GetNextCloseoutTS(),
MarkPriceType: m.markPriceCalculator.GetConfig().CompositePriceType,
MarkPriceState: m.markPriceCalculator.GetData(),
}
return md
}
// ReloadConf will trigger a reload of all the config settings in the market and all underlying engines
// this is required when hot-reloading any config changes, eg. logger level.
func (m *Market) ReloadConf(
matchingConfig matching.Config,
riskConfig risk.Config,
positionConfig positions.Config,
settlementConfig settlement.Config,
feeConfig fee.Config,
) {
m.log.Info("reloading configuration")
m.matching.ReloadConf(matchingConfig)
m.risk.ReloadConf(riskConfig)
m.position.ReloadConf(positionConfig)
m.settlement.ReloadConf(settlementConfig)
m.fee.ReloadConf(feeConfig)
}
func (m *Market) Reject(ctx context.Context) error {
if !m.canReject() {
return common.ErrCannotRejectMarketNotInProposedState
}
// we closed all parties accounts
m.cleanupOnReject(ctx)
m.mkt.State = types.MarketStateRejected
m.mkt.TradingMode = types.MarketTradingModeNoTrading
m.broker.Send(events.NewMarketUpdatedEvent(ctx, *m.mkt))
return nil
}
func (m *Market) canReject() bool {
if m.mkt.State == types.MarketStateProposed {
return true
}
if len(m.mkt.ParentMarketID) == 0 {
return false
}
// parent market is set, market can be in pending state when it is rejected.
return m.mkt.State == types.MarketStatePending
}
func (m *Market) onTxProcessed() {
m.risk.FlushMarginLevelsEvents()
}
// CanLeaveOpeningAuction checks if the market can leave the opening auction based on whether floating point consensus has been reached on all 3 vars.
func (m *Market) CanLeaveOpeningAuction() bool {
boundFactorsInitialised := m.pMonitor.IsBoundFactorsInitialised()
potInitialised := m.liquidity.IsProbabilityOfTradingInitialised()
riskFactorsInitialised := m.risk.IsRiskFactorInitialised()
canLeave := boundFactorsInitialised && riskFactorsInitialised && potInitialised
if !canLeave {
m.log.Info("Cannot leave opening auction", logging.String("market", m.mkt.ID), logging.Bool("bound-factors-initialised", boundFactorsInitialised), logging.Bool("risk-factors-initialised", riskFactorsInitialised))
}
return canLeave
}
func (m *Market) InheritParent(ctx context.Context, pstate *types.CPMarketState) {
// parent is in opening auction, do not inherit any state
if pstate.State == types.MarketStatePending {
return
}
// add the trade value from the parent
m.feeSplitter.SetTradeValue(pstate.LastTradeValue)
m.equityShares.InheritELS(pstate.Shares)
}
func (m *Market) RestoreELS(ctx context.Context, pstate *types.CPMarketState) {
m.equityShares.RestoreELS(pstate.Shares)
}
func (m *Market) RollbackInherit(ctx context.Context) {
// the InheritParent call has to be made before checking if the market can leave opening auction
// if the market did not leave opening auction, market state needs to be resored to what it was
// before the call to InheritParent was made. Market is still in opening auction, therefore
// feeSplitter trade value is zero, and equity shares are linear stake/vstake/ELS
// do make sure this call is not made when the market is active
if m.mkt.State == types.MarketStatePending || m.mkt.State == types.MarketStateProposed {
m.feeSplitter.SetTradeValue(num.UintZero())
m.equityShares.RollbackParentELS()
}
}
func (m *Market) StartOpeningAuction(ctx context.Context) error {
if m.mkt.State != types.MarketStateProposed {
return common.ErrCannotStartOpeningAuctionForMarketNotInProposedState
}
defer m.onTxProcessed()
// now we start the opening auction
if m.as.AuctionStart() {
// we are now in a pending state
m.mkt.State = types.MarketStatePending
// this should no longer be needed
// m.mkt.MarketTimestamps.Pending = m.timeService.GetTimeNow().UnixNano()
m.mkt.TradingMode = types.MarketTradingModeOpeningAuction
m.enterAuction(ctx)
} else {
// TODO(): to be removed once we don't have market starting
// without an opening auction - this is only used in unit tests
// validation on the proposal ensures opening auction duration is always >= 1 (or whatever the min duration is)
m.mkt.State = types.MarketStateActive
m.mkt.TradingMode = types.MarketTradingModeContinuous
}
m.broker.Send(events.NewMarketUpdatedEvent(ctx, *m.mkt))
return nil
}
// GetID returns the id of the given market.
func (m *Market) GetID() string {
return m.mkt.ID
}
func (m *Market) PostRestore(ctx context.Context) error {
// tell the matching engine about the markets price factor so it can finish restoring orders
m.matching.RestoreWithMarketPriceFactor(m.priceFactor)
// if loading from an old snapshot we're restoring positions using the position engine
if m.marketActivityTracker.NeedsInitialisation(m.settlementAsset, m.mkt.ID) {
for _, mp := range m.position.Positions() {
if mp.Size() != 0 {
m.marketActivityTracker.RestorePosition(m.settlementAsset, mp.Party(), m.mkt.ID, mp.Size(), mp.Price(), m.positionFactor)
}
}
}
return nil
}
// OnTick notifies the market of a new time event/update.
// todo: make this a more generic function name e.g. OnTimeUpdateEvent
func (m *Market) OnTick(ctx context.Context, t time.Time) bool {
defer m.onTxProcessed()
timer := metrics.NewTimeCounter(m.mkt.ID, "market", "OnTick")
m.mu.Lock()
defer m.mu.Unlock()
_, blockHash := vegacontext.TraceIDFromContext(ctx)
// make deterministic ID for this market, concatenate
// the block hash and the market ID
m.idgen = idgeneration.New(blockHash + crypto.HashStrToHex(m.GetID()))
// and we call next ID on this directly just so we don't have an ID which have
// a different from others, we basically burn the first ID.
_ = m.idgen.NextID()
defer func() { m.idgen = nil }()
if m.closed {
return true
}
// first we check if we should reduce the network position, then we expire orders
if !m.closed && m.canTrade() {
m.checkNetwork(ctx, t)
expired := m.removeExpiredOrders(ctx, t.UnixNano())
metrics.OrderGaugeAdd(-len(expired), m.GetID())
confirmations := m.removeExpiredStopOrders(ctx, t.UnixNano(), m.idgen)
stopsExpired := 0
for _, v := range confirmations {
stopsExpired++