-
Notifications
You must be signed in to change notification settings - Fork 21
/
market.go
3452 lines (2987 loc) · 115 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) 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 execution
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
"code.vegaprotocol.io/vega/core/assets"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/fee"
"code.vegaprotocol.io/vega/core/idgeneration"
"code.vegaprotocol.io/vega/core/liquidity"
liquiditytarget "code.vegaprotocol.io/vega/core/liquidity/target"
"code.vegaprotocol.io/vega/core/markets"
"code.vegaprotocol.io/vega/core/matching"
"code.vegaprotocol.io/vega/core/metrics"
"code.vegaprotocol.io/vega/core/monitor"
lmon "code.vegaprotocol.io/vega/core/monitor/liquidity"
"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/logging"
)
// InitialOrderVersion is set on `Version` field for every new order submission read from the network.
const InitialOrderVersion = 1
var (
// ErrMarketClosed signals that an action have been tried to be applied on a closed market.
ErrMarketClosed = errors.New("market closed")
// ErrPartyDoNotExists signals that the party used does not exists.
ErrPartyDoNotExists = errors.New("party does not exist")
// ErrMarginCheckFailed signals that a margin check for a position failed.
ErrMarginCheckFailed = errors.New("margin check failed")
// ErrMarginCheckInsufficient signals that a margin had not enough funds.
ErrMarginCheckInsufficient = errors.New("insufficient margin")
// ErrMissingGeneralAccountForParty ...
ErrMissingGeneralAccountForParty = errors.New("missing general account for party")
// ErrNotEnoughVolumeToZeroOutNetworkOrder ...
ErrNotEnoughVolumeToZeroOutNetworkOrder = errors.New("not enough volume to zero out network order")
// ErrInvalidAmendRemainQuantity signals incorrect remaining qty for a reduce by amend.
ErrInvalidAmendRemainQuantity = errors.New("incorrect remaining qty for a reduce by amend")
// ErrEmptyMarketID is returned if processed market has an empty id.
ErrEmptyMarketID = errors.New("invalid market id (empty)")
// ErrInvalidOrderType is returned if processed order has an invalid order type.
ErrInvalidOrderType = errors.New("invalid order type")
// ErrInvalidExpiresAtTime is returned if the expire time is before the createdAt time.
ErrInvalidExpiresAtTime = errors.New("invalid expiresAt time")
// ErrGFAOrderReceivedDuringContinuousTrading is returned is a gfa order hits the market when the market is in continuous trading state.
ErrGFAOrderReceivedDuringContinuousTrading = errors.New("gfa order received during continuous trading")
// ErrGFNOrderReceivedAuctionTrading is returned if a gfn order hits the market when in auction state.
ErrGFNOrderReceivedAuctionTrading = errors.New("gfn order received during auction trading")
// ErrIOCOrderReceivedAuctionTrading is returned if a ioc order hits the market when in auction state.
ErrIOCOrderReceivedAuctionTrading = errors.New("ioc order received during auction trading")
// ErrFOKOrderReceivedAuctionTrading is returned if a fok order hits the market when in auction state.
ErrFOKOrderReceivedAuctionTrading = errors.New("fok order received during auction trading")
// ErrUnableToReprice we are unable to get a price required to reprice.
ErrUnableToReprice = errors.New("unable to reprice")
// ErrOrderNotFound we cannot find the order in the market.
ErrOrderNotFound = errors.New("unable to find the order in the market")
// ErrTradingNotAllowed no trading related functionalities are allowed in the current state.
ErrTradingNotAllowed = errors.New("trading not allowed")
// ErrCommitmentSubmissionNotAllowed no commitment submission are permitted in the current state.
ErrCommitmentSubmissionNotAllowed = errors.New("commitment submission not allowed")
// ErrNotEnoughStake is returned when a LP update results in not enough commitment.
ErrNotEnoughStake = errors.New("commitment submission rejected, not enough stake")
// ErrPartyNotLiquidityProvider is returned when a LP update or cancel does not match an LP party.
ErrPartyNotLiquidityProvider = errors.New("party is not a liquidity provider")
// ErrPartyAlreadyLiquidityProvider is returned when a LP is submitted by a party which is already LP.
ErrPartyAlreadyLiquidityProvider = errors.New("party is already a liquidity provider")
// ErrCannotRejectMarketNotInProposedState.
ErrCannotRejectMarketNotInProposedState = errors.New("cannot reject a market not in proposed state")
// ErrCannotStateOpeningAuctionForMarketNotInProposedState.
ErrCannotStartOpeningAuctionForMarketNotInProposedState = errors.New("cannot start the opening auction for a market not in proposed state")
// ErrCannotRepriceDuringAuction.
ErrCannotRepriceDuringAuction = errors.New("cannot reprice during auction")
// ErrPartyInsufficientAssetBalance is returned when a party does not have sufficient balance of the required asset to perform an action.
ErrPartyInsufficientAssetBalance = errors.New("party has insufficient balance in asset")
one = num.UintOne()
)
// PriceMonitor interface to handle price monitoring/auction triggers
// @TODO the interface shouldn't be imported here.
type PriceMonitor interface {
OnTimeUpdate(now time.Time)
CheckPrice(ctx context.Context, as price.AuctionState, trades []*types.Trade, persistent bool) bool
GetCurrentBounds() []*types.PriceMonitoringBounds
SetMinDuration(d time.Duration)
GetValidPriceRange() (num.WrappedDecimal, num.WrappedDecimal)
// Snapshot
GetState() *types.PriceMonitor
Changed() bool
IsBoundFactorsInitialised() bool
Initialised() bool
UpdateSettings(risk.Model, *types.PriceMonitoringSettings)
}
// LiquidityMonitor.
type LiquidityMonitor interface {
CheckLiquidity(as lmon.AuctionState, t time.Time, currentStake *num.Uint, trades []*types.Trade, rf types.RiskFactor, markPrice *num.Uint, bestStaticBidVolume, bestStaticAskVolume uint64, persistent bool) bool
SetMinDuration(d time.Duration)
UpdateTargetStakeTriggerRatio(ctx context.Context, ratio num.Decimal)
UpdateParameters(*types.LiquidityMonitoringParameters)
}
// 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)
}
//nolint:interfacebloat
type MarketCollateral interface {
Deposit(ctx context.Context, party, asset string, amount *num.Uint) (*types.LedgerMovement, error)
Withdraw(ctx context.Context, party, asset string, amount *num.Uint) (*types.LedgerMovement, error)
EnableAsset(ctx context.Context, asset types.Asset) error
GetPartyGeneralAccount(party, asset string) (*types.Account, error)
GetPartyBondAccount(market, partyID, asset string) (*types.Account, error)
BondUpdate(ctx context.Context, market string, transfer *types.Transfer) (*types.LedgerMovement, error)
MarginUpdateOnOrder(ctx context.Context, marketID string, update events.Risk) (*types.LedgerMovement, events.Margin, error)
GetPartyMargin(pos events.MarketPosition, asset, marketID string) (events.Margin, error)
GetPartyMarginAccount(market, party, asset string) (*types.Account, error)
RollbackMarginUpdateOnOrder(ctx context.Context, marketID string, assetID string, transfer *types.Transfer) (*types.LedgerMovement, error)
GetOrCreatePartyBondAccount(ctx context.Context, partyID, marketID, asset string) (*types.Account, error)
CreatePartyMarginAccount(ctx context.Context, partyID, marketID, asset string) (string, error)
FinalSettlement(ctx context.Context, marketID string, transfers []*types.Transfer) ([]*types.LedgerMovement, error)
ClearMarket(ctx context.Context, mktID, asset string, parties []string) ([]*types.LedgerMovement, error)
HasGeneralAccount(party, asset string) bool
ClearPartyMarginAccount(ctx context.Context, party, market, asset string) (*types.LedgerMovement, error)
CanCoverBond(market, party, asset string, amount *num.Uint) bool
Hash() []byte
TransferFeesContinuousTrading(ctx context.Context, marketID string, assetID string, ft events.FeesTransfer) ([]*types.LedgerMovement, error)
TransferFees(ctx context.Context, marketID string, assetID string, ft events.FeesTransfer) ([]*types.LedgerMovement, error)
MarginUpdate(ctx context.Context, marketID string, updates []events.Risk) ([]*types.LedgerMovement, []events.Margin, []events.Margin, error)
MarkToMarket(ctx context.Context, marketID string, transfers []events.Transfer, asset string) ([]events.Margin, []*types.LedgerMovement, error)
RemoveDistressed(ctx context.Context, parties []events.MarketPosition, marketID, asset string) (*types.LedgerMovement, error)
GetMarketLiquidityFeeAccount(market, asset string) (*types.Account, error)
GetAssetQuantum(asset string) (num.Decimal, error)
}
// AuctionState ...
//
//nolint:interfacebloat
type AuctionState interface {
price.AuctionState
lmon.AuctionState
// are we in auction, and what auction are we in?
InAuction() bool
IsOpeningAuction() bool
IsPriceAuction() bool
IsLiquidityAuction() bool
IsFBA() bool
IsMonitorAuction() bool
// is it the start/end of an auction
AuctionStart() bool
CanLeave() bool
// when does the auction start/end
ExpiresAt() *time.Time
Start() time.Time
// signal we've started/ended the auction
AuctionStarted(ctx context.Context, time time.Time) *events.Auction
AuctionExtended(ctx context.Context, time time.Time) *events.Auction
ExtendAuction(delta types.AuctionDuration)
Left(ctx context.Context, now time.Time) *events.Auction
// get some data
Mode() types.MarketTradingMode
Trigger() types.AuctionTrigger
ExtensionTrigger() types.AuctionTrigger
// UpdateMinDuration works out whether or not the current auction period (if applicable) should be extended
UpdateMinDuration(ctx context.Context, d time.Duration) *events.Auction
// Snapshot
GetState() *types.AuctionState
Changed() bool
}
// 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 IDGenerator
mkt *types.Market
closingAt time.Time
timeService TimeService
mu sync.Mutex
lastTradedPrice *num.Uint
markPrice *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
liquidity *liquidity.SnapshotEngine
// deps engines
collateral MarketCollateral
broker Broker
closed bool
parties map[string]struct{}
pMonitor PriceMonitor
lMonitor LiquidityMonitor
lpPriceRange num.Decimal
linearSlippageFactor num.Decimal
quadraticSlippageFactor num.Decimal
tsCalc TargetStakeCalculator
as AuctionState
peggedOrders *PeggedOrders
expiringOrders *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
lastMarketValueProxy num.Decimal
bondPenaltyFactor num.Decimal
marketValueWindowLength time.Duration
// Liquidity Fee
feeSplitter *FeeSplitter
lpFeeDistributionTimeStep time.Duration
lastEquityShareDistributed time.Time
equityShares *EquityShares
minLPStakeQuantumMultiple num.Decimal
stateVarEngine StateVarEngine
marketActivityTracker *MarketActivityTracker
positionFactor num.Decimal // 10^pdp
assetDP uint32
settlementDataInMarket *num.Numeric
nextMTM time.Time
mtmDelta time.Duration
}
// 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 MarketCollateral,
oracleEngine products.OracleEngine,
mkt *types.Market,
timeService TimeService,
broker Broker,
as *monitor.AuctionState,
stateVarEngine StateVarEngine,
marketActivityTracker *MarketActivityTracker,
assetDetails *assets.Asset,
peggedOrderNotify func(int64),
) (*Market, error) {
if len(mkt.ID) == 0 {
return nil, ErrEmptyMarketID
}
positionFactor := num.DecimalFromFloat(10).Pow(num.DecimalFromInt64(mkt.PositionDecimalPlaces))
tradableInstrument, err := markets.NewTradableInstrument(ctx, log, mkt.TradableInstrument, oracleEngine)
if err != nil {
return nil, fmt.Errorf("unable to instantiate a new market: %w", err)
}
priceFactor := num.NewUint(1)
if exp := assetDetails.DecimalPlaces() - 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, as.InAuction(), peggedOrderNotify)
asset := tradableInstrument.Instrument.Product.GetAsset()
riskEngine := risk.NewEngine(log,
riskConfig,
tradableInstrument.MarginCalculator,
tradableInstrument.RiskModel,
book,
as,
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, as, mkt.PriceMonitoringSettings, stateVarEngine, log)
if err != nil {
return nil, fmt.Errorf("unable to instantiate price monitoring engine: %w", err)
}
lMonitor := lmon.NewMonitor(tsCalc, mkt.LiquidityMonitoringParameters)
now := timeService.GetTimeNow()
liqEngine := liquidity.NewSnapshotEngine(
liquidityConfig, log, timeService, broker, tradableInstrument.RiskModel, pMonitor, book, asset, mkt.ID, stateVarEngine, priceFactor.Clone(), positionFactor)
// The market is initially created in a proposed state
mkt.State = types.MarketStateProposed
mkt.TradingMode = types.MarketTradingModeNoTrading
// Populate the market timestamps
ts := &types.MarketTimestamps{
Proposed: now.UnixNano(),
Pending: now.UnixNano(),
}
if mkt.OpeningAuction != nil {
ts.Open = now.Add(time.Duration(mkt.OpeningAuction.Duration)).UnixNano()
} else {
ts.Open = now.UnixNano()
}
mkt.MarketTimestamps = ts
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: liqEngine,
parties: map[string]struct{}{},
as: as,
pMonitor: pMonitor,
lMonitor: lMonitor,
tsCalc: tsCalc,
peggedOrders: NewPeggedOrders(log, timeService),
expiringOrders: NewExpiringOrders(),
feeSplitter: NewFeeSplitter(),
equityShares: NewEquityShares(num.DecimalZero()),
lastBestAskPrice: num.UintZero(),
lastMidSellPrice: num.UintZero(),
lastMidBuyPrice: num.UintZero(),
lastBestBidPrice: num.UintZero(),
stateVarEngine: stateVarEngine,
marketActivityTracker: marketActivityTracker,
priceFactor: priceFactor,
minLPStakeQuantumMultiple: num.MustDecimalFromString("1"),
positionFactor: positionFactor,
nextMTM: time.Time{}, // default to zero time
lpPriceRange: mkt.LPPriceRange,
linearSlippageFactor: mkt.LinearSlippageFactor,
quadraticSlippageFactor: mkt.QuadraticSlippageFactor,
}
liqEngine.SetGetStaticPricesFunc(market.getBestStaticPricesDecimal)
market.tradableInstrument.Instrument.Product.NotifyOnTradingTerminated(market.tradingTerminated)
market.tradableInstrument.Instrument.Product.NotifyOnSettlementData(market.settlementData)
market.assetDP = uint32(assetDetails.DecimalPlaces())
return market, nil
}
func (m *Market) Update(ctx context.Context, config *types.Market, oracleEngine products.OracleEngine) error {
config.TradingMode = m.mkt.TradingMode
config.State = m.mkt.State
config.MarketTimestamps = m.mkt.MarketTimestamps
recalcMargins := !config.TradableInstrument.RiskModel.Equal(m.mkt.TradableInstrument.RiskModel)
asset, err := m.mkt.GetAsset()
if err != nil {
return err
}
config.SetAsset(asset)
m.mkt = config
if m.mkt.State == types.MarketStateTradingTerminated {
m.tradableInstrument.Instrument.UnsubscribeSettlementData(ctx)
} else {
m.tradableInstrument.Instrument.Unsubscribe(ctx)
}
if err := m.tradableInstrument.UpdateInstrument(ctx, m.log, m.mkt.TradableInstrument, oracleEngine); err != nil {
return err
}
m.risk.UpdateModel(m.stateVarEngine, m.tradableInstrument.MarginCalculator, m.tradableInstrument.RiskModel)
m.settlement.UpdateProduct(m.tradableInstrument.Instrument.Product)
m.tsCalc.UpdateParameters(*m.mkt.LiquidityMonitoringParameters.TargetStakeParameters)
m.pMonitor.UpdateSettings(m.tradableInstrument.RiskModel, m.mkt.PriceMonitoringSettings)
m.lpPriceRange = m.mkt.LPPriceRange
m.linearSlippageFactor = m.mkt.LinearSlippageFactor
m.quadraticSlippageFactor = m.mkt.QuadraticSlippageFactor
m.lMonitor.UpdateParameters(m.mkt.LiquidityMonitoringParameters)
m.liquidity.UpdateMarketConfig(m.tradableInstrument.RiskModel, m.pMonitor)
// if we're already in trading terminated, not point to listen to trading termination oracle
if m.mkt.State != types.MarketStateTradingTerminated {
m.tradableInstrument.Instrument.Product.NotifyOnTradingTerminated(m.tradingTerminated)
} else {
m.tradableInstrument.Instrument.UnsubscribeTradingTerminated(ctx)
}
m.tradableInstrument.Instrument.Product.NotifyOnSettlementData(m.settlementData)
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())
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) 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)
if m.priceFactor.NEQ(one) {
b.MinValidPrice.AddSum(one) // ceil
}
}
return 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: m.as.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: lpsToLiquidityProviderFeeShare(m.equityShares.lps, m.liquidity.GetAverageLiquidityScores()),
NextMTM: m.nextMTM.UnixNano(),
}
}
// 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.mkt.State != types.MarketStateProposed {
return 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) 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.IsPoTInitialised()
riskFactorsInitialised := m.risk.IsRiskFactorInitialised()
canLeave := boundFactorsInitialised && potInitialised && riskFactorsInitialised
if !canLeave {
m.log.Info("Cannot leave opening auction", logging.String("market", m.mkt.ID), logging.Bool("bound-factors-initialised", boundFactorsInitialised), logging.Bool("pot-initialised", potInitialised), logging.Bool("risk-factors-initialised", riskFactorsInitialised))
}
return canLeave
}
func (m *Market) StartOpeningAuction(ctx context.Context) error {
if m.mkt.State != types.MarketStateProposed {
return 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
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
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)
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 expire orders
if !m.closed && m.canTrade() {
expired := m.removeExpiredOrders(ctx, t.UnixNano())
metrics.OrderGaugeAdd(-len(expired), m.GetID())
}
// some engines still needs to get updates:
m.pMonitor.OnTimeUpdate(t)
m.feeSplitter.SetCurrentTime(t)
// TODO(): This also assume that the market is not
// being closed before the market is leaving
// the opening auction, but settlement at expiry is
// not even specced or implemented as of now...
// if the state of the market is just PROPOSED,
// we will just skip everything there as nothing apply.
if m.mkt.State == types.MarketStateProposed {
return false
}
// if trading is terminated, we have nothing to do here.
// we just need to wait for the settlementData to arrive through oracle
if m.mkt.State == types.MarketStateTradingTerminated {
return false
}
// distribute liquidity fees each `m.lpFeeDistributionTimeStep`
if t.Sub(m.lastEquityShareDistributed) > m.lpFeeDistributionTimeStep {
m.lastEquityShareDistributed = t
if err := m.distributeLiquidityFees(ctx); err != nil {
m.log.Panic("liquidity fee distribution error", logging.Error(err))
}
}
// check auction, if any. If we leave auction, MTM is performed in this call
m.checkAuction(ctx, t)
timer.EngineTimeCounterAdd()
m.updateMarketValueProxy()
m.updateLiquidityScores()
m.updateLiquidityFee(ctx)
m.broker.Send(events.NewMarketTick(ctx, m.mkt.ID, t))
return m.closed
}
func (m *Market) blockEnd(ctx context.Context) {
defer m.onTxProcessed()
// MTM if enough time has elapsed, we are not in auction, and we have a non-zero mark price.
// we MTM in leaveAuction before deploying LP orders like we did before, but we do update nextMTM there
var tID string
ctx, tID = vegacontext.TraceIDFromContext(ctx)
m.idgen = idgeneration.New(tID + crypto.HashStrToHex("blockend"+m.GetID()))
defer func() {
m.idgen = nil
}()
hasTraded := m.settlement.HasTraded()
mp := m.getLastTradedPrice()
if !hasTraded && m.markPrice != nil {
// no trades happened, make sure we're just using the current mark price
mp = m.markPrice.Clone()
}
t := m.timeService.GetTimeNow()
if mp != nil && !mp.IsZero() && !m.as.InAuction() && (m.nextMTM.IsZero() || !m.nextMTM.After(t)) {
m.markPrice = mp.Clone()
m.nextMTM = t.Add(m.mtmDelta) // add delta here
if hasTraded {
// only MTM if we have traded
m.confirmMTM(ctx, false)
}
closedWithoutLP := []events.MarketPosition{}
closedPositions := m.position.GetClosedPositions()
for _, p := range closedPositions {
// if the party doesn't have a potential position anymore?
// and it's not an LP (they could just be undeployed)
if !m.liquidity.IsLiquidityProvider(p.Party()) {
closedWithoutLP = append(closedWithoutLP, p)
}
}
if len(closedWithoutLP) > 0 {
m.releaseExcessMargin(ctx, closedWithoutLP...)
}
// last traded price should not reflect the closeout trades
m.lastTradedPrice = mp.Clone()
}
m.releaseExcessMargin(ctx, m.position.Positions()...)
// send position events
m.position.FlushPositionEvents(ctx)
}
func (m *Market) updateMarketValueProxy() {
// if windows length is reached, reset fee splitter
if mvwl := m.marketValueWindowLength; m.feeSplitter.Elapsed() > mvwl {
// AvgTradeValue calculates the rolling average trade value to include the current window (which is ending)
m.equityShares.AvgTradeValue(m.feeSplitter.AvgTradeValue())
// this increments the internal window counter
m.feeSplitter.TimeWindowStart(m.timeService.GetTimeNow())
// m.equityShares.UpdateVirtualStake() // this should always set the vStake >= physical stake?
}
// these need to happen every block
// but also when new LP is submitted just so we are sure we do
// not have a mvp of 0
ts := m.liquidity.ProvisionsPerParty().TotalStake()
m.lastMarketValueProxy = m.feeSplitter.MarketValueProxy(
m.marketValueWindowLength, ts)
}
func (m *Market) removeOrders(ctx context.Context) {
// remove all order from the book
// and send events with the stopped status
orders := append(m.matching.Settled(), m.peggedOrders.Settled()...)
orderEvents := make([]events.Event, 0, len(orders))
for _, v := range orders {
orderEvents = append(orderEvents, events.NewOrderEvent(ctx, v))
}
m.broker.SendBatch(orderEvents)
}
func (m *Market) cleanMarketWithState(ctx context.Context, mktState types.MarketState) error {
parties := make([]string, 0, len(m.parties))
for k := range m.parties {
parties = append(parties, k)
}
asset, _ := m.mkt.GetAsset()
sort.Strings(parties)
clearMarketTransfers, err := m.collateral.ClearMarket(ctx, m.GetID(), asset, parties)
if err != nil {
m.log.Error("Clear market error",
logging.MarketID(m.GetID()),
logging.Error(err))
return err
}
// unregister state-variables
m.stateVarEngine.UnregisterStateVariable(asset, m.mkt.ID)
m.broker.Send(events.NewLedgerMovements(ctx, clearMarketTransfers))
m.mkt.State = mktState
m.mkt.TradingMode = types.MarketTradingModeNoTrading
m.broker.Send(events.NewMarketUpdatedEvent(ctx, *m.mkt))
return nil
}
func (m *Market) closeCancelledMarket(ctx context.Context) error {
// we got here because trading was terminated, so we've already unsubscribed that oracle data source.
m.tradableInstrument.Instrument.UnsubscribeSettlementData(ctx)
if err := m.cleanMarketWithState(ctx, types.MarketStateCancelled); err != nil {
return err
}
if err := m.stopAllLiquidityProvisionOnReject(ctx); err != nil {
m.log.Debug("could not stop all liquidity provision on market rejection",
logging.MarketID(m.GetID()),
logging.Error(err))
}
m.closed = true
return nil
}
func (m *Market) closeMarket(ctx context.Context, t time.Time) error {
positions, err := m.settlement.Settle(t, m.assetDP)
if err != nil {
m.log.Error("Failed to get settle positions on market closed",
logging.Error(err))
return err
}
transfers, err := m.collateral.FinalSettlement(ctx, m.GetID(), positions)
if err != nil {
m.log.Error("Failed to get ledger movements after settling closed market",
logging.MarketID(m.GetID()),
logging.Error(err))
return err
}
m.tradableInstrument.Instrument.UnsubscribeSettlementData(ctx)
// @TODO pass in correct context -> Previous or next block?
// Which is most appropriate here?
// this will be next block
m.broker.Send(events.NewLedgerMovements(ctx, transfers))
// final distribution of liquidity fees
m.distributeLiquidityFees(ctx)
err = m.cleanMarketWithState(ctx, types.MarketStateSettled)
if err != nil {
return err
}
m.removeOrders(ctx)
for _, party := range m.liquidity.ProvisionsPerParty().Slice() {
// we don't care about the actual orders as they will be cancelled in the book as part of settlement anyways.
err := m.liquidity.StopLiquidityProvision(ctx, party.Party)
if err != nil {
return err
}
}
return nil
}
func (m *Market) unregisterAndReject(ctx context.Context, order *types.Order, err error) error {
_ = m.position.UnregisterOrder(ctx, order)
order.UpdatedAt = m.timeService.GetTimeNow().UnixNano()
order.Status = types.OrderStatusRejected
if oerr, ok := types.IsOrderError(err); ok {
// the order wasn't invalid, so stopped is a better status, rather than rejected.
if oerr == types.OrderErrorNonPersistentOrderOutOfPriceBounds {
order.Status = types.OrderStatusStopped
}
order.Reason = oerr
} else {
// should not happened but still...
order.Reason = types.OrderErrorInternalError
}
m.broker.Send(events.NewOrderEvent(ctx, order))
if m.log.GetLevel() == logging.DebugLevel {
m.log.Debug("Failure after submitting order to matching engine",
logging.Order(*order),
logging.Error(err))
}
return err
}
func (m *Market) getNewPeggedPrice(order *types.Order) (*num.Uint, error) {
if m.as.InAuction() {
return num.UintZero(), ErrCannotRepriceDuringAuction
}
var (
err error
price *num.Uint
)
switch order.PeggedOrder.Reference {
case types.PeggedReferenceMid:
price, err = m.getStaticMidPrice(order.Side)
case types.PeggedReferenceBestBid:
price, err = m.getBestStaticBidPrice()
case types.PeggedReferenceBestAsk:
price, err = m.getBestStaticAskPrice()
}
if err != nil {
return num.UintZero(), ErrUnableToReprice
}
offset := num.UintZero().Mul(order.PeggedOrder.Offset, m.priceFactor)
if order.Side == types.SideSell {
return price.AddSum(offset), nil
}
if price.LTE(offset) {
return num.UintZero(), ErrUnableToReprice
}
return num.UintZero().Sub(price, offset), nil
}
// Reprice a pegged order. This only updates the price on the order.
func (m *Market) repricePeggedOrder(order *types.Order) error {
// Work out the new price of the order
price, err := m.getNewPeggedPrice(order)
if err != nil {
return err
}
original := price.Clone()
order.OriginalPrice = original.Div(original, m.priceFactor) // set original price in market precision
order.Price = price
return nil
}
func (m *Market) parkAllPeggedOrders(ctx context.Context) []*types.Order {
toParkIDs := m.matching.GetActivePeggedOrderIDs()
parked := make([]*types.Order, 0, len(toParkIDs))
for _, order := range toParkIDs {
parked = append(parked, m.parkOrder(ctx, order))
}
return parked
}
// EnterAuction : Prepare the order book to be run as an auction.
func (m *Market) enterAuction(ctx context.Context) {
// Change market type to auction
ordersToCancel := m.matching.EnterAuction()
// Move into auction mode to prevent pegged order repricing
event := m.as.AuctionStarted(ctx, m.timeService.GetTimeNow())
// this is at least the size of the orders to be cancelled
updatedOrders := make([]*types.Order, 0, len(ordersToCancel))
// Cancel all the orders that were invalid
for _, order := range ordersToCancel {
_, err := m.cancelOrder(ctx, order.Party, order.ID)