-
Notifications
You must be signed in to change notification settings - Fork 21
/
engine.go
1082 lines (908 loc) · 29.8 KB
/
engine.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"
"sort"
"time"
"code.vegaprotocol.io/vega/core/assets"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/metrics"
"code.vegaprotocol.io/vega/core/monitor"
"code.vegaprotocol.io/vega/core/oracles"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/core/types/statevar"
"code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
)
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/execution TimeService,Assets,StateVarEngine,Collateral,OracleEngine,EpochEngine
var (
// ErrMarketDoesNotExist is returned when the market does not exist.
ErrMarketDoesNotExist = errors.New("market does not exist")
// ErrNoMarketID is returned when invalid (empty) market id was supplied during market creation.
ErrNoMarketID = errors.New("no valid market id was supplied")
// ErrInvalidOrderCancellation is returned when an incomplete order cancellation request is used.
ErrInvalidOrderCancellation = errors.New("invalid order cancellation")
)
// TimeService ...
type TimeService interface {
GetTimeNow() time.Time
}
// OracleEngine ...
type OracleEngine interface {
ListensToSigners(oracles.OracleData) bool
Subscribe(context.Context, oracles.OracleSpec, oracles.OnMatchedOracleData) (oracles.SubscriptionID, oracles.Unsubscriber)
Unsubscribe(context.Context, oracles.SubscriptionID)
}
// Broker (no longer need to mock this, use the broker/mocks wrapper).
type Broker interface {
Send(event events.Event)
SendBatch(events []events.Event)
}
type Collateral interface {
MarketCollateral
AssetExists(string) bool
CreateMarketAccounts(context.Context, string, string) (string, string, error)
}
type StateVarEngine interface {
RegisterStateVariable(asset, market, name string, converter statevar.Converter, startCalculation func(string, statevar.FinaliseCalculation), trigger []statevar.EventType, result func(context.Context, statevar.StateVariableResult) error) error
UnregisterStateVariable(asset, market string)
NewEvent(asset, market string, eventType statevar.EventType)
ReadyForTimeTrigger(asset, mktID string)
}
type Assets interface {
Get(assetID string) (*assets.Asset, error)
}
type IDGenerator interface {
NextID() string
}
// Engine is the execution engine.
type Engine struct {
Config
log *logging.Logger
markets map[string]*Market
marketsCpy []*Market
collateral Collateral
assets Assets
broker Broker
timeService TimeService
stateVarEngine StateVarEngine
marketActivityTracker *MarketActivityTracker
oracle OracleEngine
npv netParamsValues
snapshotSerialised []byte
newGeneratedProviders []types.StateProvider // new providers generated during the last state change
// Map of all active snapshot providers that the execution engine has generated
generatedProviders map[string]struct{}
}
type netParamsValues struct {
shapesMaxSize int64
feeDistributionTimeStep time.Duration
marketValueWindowLength time.Duration
suppliedStakeToObligationFactor num.Decimal
infrastructureFee num.Decimal
makerFee num.Decimal
scalingFactors *types.ScalingFactors
maxLiquidityFee num.Decimal
bondPenaltyFactor num.Decimal
auctionMinDuration time.Duration
probabilityOfTradingTauScaling num.Decimal
minProbabilityOfTradingLPOrders num.Decimal
minLpStakeQuantumMultiple num.Decimal
marketCreationQuantumMultiple num.Decimal
}
func defaultNetParamsValues() netParamsValues {
return netParamsValues{
shapesMaxSize: -1,
feeDistributionTimeStep: -1,
marketValueWindowLength: -1,
suppliedStakeToObligationFactor: num.DecimalFromInt64(-1),
infrastructureFee: num.DecimalFromInt64(-1),
makerFee: num.DecimalFromInt64(-1),
scalingFactors: nil,
maxLiquidityFee: num.DecimalFromInt64(-1),
bondPenaltyFactor: num.DecimalFromInt64(-1),
auctionMinDuration: -1,
probabilityOfTradingTauScaling: num.DecimalFromInt64(-1),
minProbabilityOfTradingLPOrders: num.DecimalFromInt64(-1),
minLpStakeQuantumMultiple: num.DecimalFromInt64(-1),
marketCreationQuantumMultiple: num.DecimalFromInt64(-1),
}
}
// NewEngine takes stores and engines and returns
// a new execution engine to process new orders, etc.
func NewEngine(
log *logging.Logger,
executionConfig Config,
ts TimeService,
collateral Collateral,
oracle OracleEngine,
broker Broker,
stateVarEngine StateVarEngine,
marketActivityTracker *MarketActivityTracker,
assets Assets,
) *Engine {
// setup logger
log = log.Named(namedLogger)
log.SetLevel(executionConfig.Level.Get())
e := &Engine{
log: log,
Config: executionConfig,
markets: map[string]*Market{},
timeService: ts,
collateral: collateral,
assets: assets,
broker: broker,
oracle: oracle,
npv: defaultNetParamsValues(),
generatedProviders: map[string]struct{}{},
stateVarEngine: stateVarEngine,
marketActivityTracker: marketActivityTracker,
}
// set the eligibility for proposer bonus checker
e.marketActivityTracker.SetEligibilityChecker(e)
return e
}
// ReloadConf updates the internal configuration of the execution
// engine and its dependencies.
func (e *Engine) ReloadConf(cfg Config) {
e.log.Debug("reloading configuration")
if e.log.GetLevel() != cfg.Level.Get() {
e.log.Info("updating log level",
logging.String("old", e.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
e.log.SetLevel(cfg.Level.Get())
}
e.Config = cfg
for _, mkt := range e.marketsCpy {
mkt.ReloadConf(e.Matching, e.Risk, e.Position, e.Settlement, e.Fee)
}
}
func (e *Engine) Hash() []byte {
e.log.Debug("hashing markets")
hashes := make([]string, 0, len(e.marketsCpy))
for _, m := range e.marketsCpy {
hash := m.Hash()
e.log.Debug("market app state hash", logging.Hash(hash), logging.String("market-id", m.GetID()))
hashes = append(hashes, string(hash))
}
sort.Strings(hashes)
// get the accounts hash + add it at end of all markets hash
accountsHash := e.collateral.Hash()
e.log.Debug("accounts state hash", logging.Hash(accountsHash))
bytes := []byte{}
for _, h := range append(hashes, string(accountsHash)) {
bytes = append(bytes, []byte(h)...)
}
return crypto.Hash(bytes)
}
// RejectMarket will stop the execution of the market
// and refund into the general account any funds in margins accounts from any parties
// This works only if the market is in a PROPOSED STATE.
func (e *Engine) RejectMarket(ctx context.Context, marketID string) error {
if e.log.IsDebug() {
e.log.Debug("reject market", logging.MarketID(marketID))
}
mkt, ok := e.markets[marketID]
if !ok {
return ErrMarketDoesNotExist
}
if err := mkt.Reject(ctx); err != nil {
return err
}
e.removeMarket(marketID)
return nil
}
// StartOpeningAuction will start the opening auction of the given market.
// This will work only if the market is currently in a PROPOSED state.
func (e *Engine) StartOpeningAuction(ctx context.Context, marketID string) error {
if e.log.IsDebug() {
e.log.Debug("start opening auction", logging.MarketID(marketID))
}
mkt, ok := e.markets[marketID]
if !ok {
return ErrMarketDoesNotExist
}
return mkt.StartOpeningAuction(ctx)
}
// IsEligibleForProposerBonus checks if the given value is greater than that market quantum * quantum_multiplier.
func (e *Engine) IsEligibleForProposerBonus(marketID string, value *num.Uint) bool {
if _, ok := e.markets[marketID]; !ok {
return false
}
asset, err := e.markets[marketID].mkt.GetAsset()
if err != nil {
return false
}
quantum, err := e.collateral.GetAssetQuantum(asset)
if err != nil {
return false
}
return value.ToDecimal().GreaterThan(quantum.Mul(e.npv.marketCreationQuantumMultiple))
}
// SubmitMarket submits a new market configuration to the network.
func (e *Engine) SubmitMarket(ctx context.Context, marketConfig *types.Market, proposer string) error {
return e.submitOrRestoreMarket(ctx, marketConfig, proposer, true)
}
// RestoreMarket restores a new market from proposal checkpoint.
func (e *Engine) RestoreMarket(ctx context.Context, marketConfig *types.Market) error {
proposer := e.marketActivityTracker.GetProposer(marketConfig.ID)
if len(proposer) == 0 {
return ErrMarketDoesNotExist
}
return e.submitOrRestoreMarket(ctx, marketConfig, "", false)
}
func (e *Engine) submitOrRestoreMarket(ctx context.Context, marketConfig *types.Market, proposer string, isNewMarket bool) error {
if e.log.IsDebug() {
msg := "submit market"
if !isNewMarket {
msg = "restore market"
}
e.log.Debug(msg, logging.Market(*marketConfig))
}
if err := e.submitMarket(ctx, marketConfig); err != nil {
return err
}
if isNewMarket {
asset, err := marketConfig.GetAsset()
if err != nil {
e.log.Panic("failed to get asset from market config", logging.String("market", marketConfig.ID), logging.String("error", err.Error()))
}
e.marketActivityTracker.MarketProposed(asset, marketConfig.ID, proposer)
}
// keep state in pending, opening auction is triggered when proposal is enacted
mkt := e.markets[marketConfig.ID]
e.publishNewMarketInfos(ctx, mkt)
return nil
}
// UpdateMarket will update an existing market configuration.
func (e *Engine) UpdateMarket(ctx context.Context, marketConfig *types.Market) error {
e.log.Info("update market", logging.Market(*marketConfig))
mkt := e.markets[marketConfig.ID]
if err := mkt.Update(ctx, marketConfig, e.oracle); err != nil {
return err
}
e.publishUpdateMarketInfos(ctx, mkt)
return nil
}
func (e *Engine) publishNewMarketInfos(ctx context.Context, mkt *Market) {
// we send a market data event for this market when it's created so graphql does not fail
e.broker.Send(events.NewMarketDataEvent(ctx, mkt.GetMarketData()))
e.broker.Send(events.NewMarketCreatedEvent(ctx, *mkt.mkt))
e.broker.Send(events.NewMarketUpdatedEvent(ctx, *mkt.mkt))
}
func (e *Engine) publishUpdateMarketInfos(ctx context.Context, mkt *Market) {
// we send a market data event for this market when it's created so graphql does not fail
e.broker.Send(events.NewMarketDataEvent(ctx, mkt.GetMarketData()))
e.broker.Send(events.NewMarketUpdatedEvent(ctx, *mkt.mkt))
}
// submitMarket will submit a new market configuration to the network.
func (e *Engine) submitMarket(ctx context.Context, marketConfig *types.Market) error {
if len(marketConfig.ID) == 0 {
return ErrNoMarketID
}
now := e.timeService.GetTimeNow()
// ensure the asset for this new market exists
asset, err := marketConfig.GetAsset()
if err != nil {
return err
}
if !e.collateral.AssetExists(asset) {
e.log.Error("unable to create a market with an invalid asset",
logging.MarketID(marketConfig.ID),
logging.AssetID(asset))
}
// create market auction state
mas := monitor.NewAuctionState(marketConfig, now)
ad, err := e.assets.Get(asset)
if err != nil {
e.log.Error("Failed to create a new market, unknown asset",
logging.MarketID(marketConfig.ID),
logging.String("asset-id", asset),
logging.Error(err),
)
return err
}
mkt, err := NewMarket(
ctx,
e.log,
e.Risk,
e.Position,
e.Settlement,
e.Matching,
e.Fee,
e.Liquidity,
e.collateral,
e.oracle,
marketConfig,
e.timeService,
e.broker,
mas,
e.stateVarEngine,
e.marketActivityTracker,
ad,
)
if err != nil {
e.log.Error("failed to instantiate market",
logging.MarketID(marketConfig.ID),
logging.Error(err),
)
return err
}
e.markets[marketConfig.ID] = mkt
e.marketsCpy = append(e.marketsCpy, mkt)
// we ignore the response, this cannot fail as the asset
// is already proven to exists a few line before
_, _, _ = e.collateral.CreateMarketAccounts(ctx, marketConfig.ID, asset)
if err := e.propagateInitialNetParams(ctx, mkt); err != nil {
return err
}
return nil
}
func (e *Engine) propagateInitialNetParams(ctx context.Context, mkt *Market) error {
if !e.npv.probabilityOfTradingTauScaling.Equal(num.DecimalFromInt64(-1)) {
mkt.OnMarketProbabilityOfTradingTauScalingUpdate(ctx, e.npv.probabilityOfTradingTauScaling)
}
if !e.npv.minProbabilityOfTradingLPOrders.Equal(num.DecimalFromInt64(-1)) {
mkt.OnMarketMinProbabilityOfTradingLPOrdersUpdate(ctx, e.npv.minProbabilityOfTradingLPOrders)
}
if !e.npv.minLpStakeQuantumMultiple.Equal(num.DecimalFromInt64(-1)) {
mkt.OnMarketMinLpStakeQuantumMultipleUpdate(ctx, e.npv.minLpStakeQuantumMultiple)
}
if e.npv.auctionMinDuration != -1 {
mkt.OnMarketAuctionMinimumDurationUpdate(ctx, e.npv.auctionMinDuration)
}
if e.npv.shapesMaxSize != -1 {
if err := mkt.OnMarketLiquidityProvisionShapesMaxSizeUpdate(e.npv.shapesMaxSize); err != nil {
return err
}
}
if !e.npv.infrastructureFee.Equal(num.DecimalFromInt64(-1)) {
if err := mkt.OnFeeFactorsInfrastructureFeeUpdate(ctx, e.npv.infrastructureFee); err != nil {
return err
}
}
if !e.npv.makerFee.Equal(num.DecimalFromInt64(-1)) {
if err := mkt.OnFeeFactorsMakerFeeUpdate(ctx, e.npv.makerFee); err != nil {
return err
}
}
if e.npv.scalingFactors != nil {
if err := mkt.OnMarginScalingFactorsUpdate(ctx, e.npv.scalingFactors); err != nil {
return err
}
}
if e.npv.feeDistributionTimeStep != -1 {
mkt.OnMarketLiquidityProvidersFeeDistribitionTimeStep(e.npv.feeDistributionTimeStep)
}
if e.npv.marketValueWindowLength != -1 {
mkt.OnMarketValueWindowLengthUpdate(e.npv.marketValueWindowLength)
}
if !e.npv.suppliedStakeToObligationFactor.Equal(num.DecimalFromInt64(-1)) {
mkt.OnSuppliedStakeToObligationFactorUpdate(e.npv.suppliedStakeToObligationFactor)
}
if !e.npv.bondPenaltyFactor.Equal(num.DecimalFromInt64(-1)) {
mkt.BondPenaltyFactorUpdate(ctx, e.npv.bondPenaltyFactor)
}
if !e.npv.maxLiquidityFee.Equal(num.DecimalFromInt64(-1)) {
mkt.OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate(e.npv.maxLiquidityFee)
}
return nil
}
func (e *Engine) removeMarket(mktID string) {
e.log.Debug("removing market", logging.String("id", mktID))
delete(e.markets, mktID)
for i, mkt := range e.marketsCpy {
if mkt.GetID() == mktID {
mkt.matching.StopSnapshots()
mkt.position.StopSnapshots()
mkt.liquidity.StopSnapshots()
mkt.tsCalc.StopSnapshots()
copy(e.marketsCpy[i:], e.marketsCpy[i+1:])
e.marketsCpy[len(e.marketsCpy)-1] = nil
e.marketsCpy = e.marketsCpy[:len(e.marketsCpy)-1]
e.marketActivityTracker.RemoveMarket(mktID)
e.log.Debug("removed in total", logging.String("id", mktID))
return
}
}
}
// SubmitOrder checks the incoming order and submits it to a Vega market.
func (e *Engine) SubmitOrder(
ctx context.Context,
submission *types.OrderSubmission,
party string,
idgen IDGenerator,
orderID string,
) (confirmation *types.OrderConfirmation, returnedErr error) {
timer := metrics.NewTimeCounter(submission.MarketID, "execution", "SubmitOrder")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("submit order", logging.OrderSubmission(submission))
}
mkt, ok := e.markets[submission.MarketID]
if !ok {
return nil, types.ErrInvalidMarketID
}
metrics.OrderGaugeAdd(1, submission.MarketID)
conf, err := mkt.SubmitOrderWithIDGeneratorAndOrderID(
ctx, submission, party, idgen, orderID)
if err != nil {
return nil, err
}
e.decrementOrderGaugeMetrics(submission.MarketID, conf.Order, conf.PassiveOrdersAffected)
return conf, nil
}
// AmendOrder takes order amendment details and attempts to amend the order
// if it exists and is in a editable state.
func (e *Engine) AmendOrder(
ctx context.Context,
amendment *types.OrderAmendment,
party string,
idgen IDGenerator,
) (confirmation *types.OrderConfirmation, returnedErr error) {
timer := metrics.NewTimeCounter(amendment.MarketID, "execution", "AmendOrder")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("amend order", logging.OrderAmendment(amendment))
}
mkt, ok := e.markets[amendment.MarketID]
if !ok {
return nil, types.ErrInvalidMarketID
}
conf, err := mkt.AmendOrderWithIDGenerator(ctx, amendment, party, idgen)
if err != nil {
return nil, err
}
e.decrementOrderGaugeMetrics(amendment.MarketID, conf.Order, conf.PassiveOrdersAffected)
return conf, nil
}
func (e *Engine) decrementOrderGaugeMetrics(
market string,
order *types.Order,
passive []*types.Order,
) {
// order was active, not anymore -> decrement gauge
if order.Status != types.OrderStatusActive {
metrics.OrderGaugeAdd(-1, market)
}
var passiveCount int
for _, v := range passive {
if v.IsFinished() {
passiveCount++
}
}
if passiveCount > 0 {
metrics.OrderGaugeAdd(-passiveCount, market)
}
}
// CancelOrder takes order details and attempts to cancel if it exists in matching engine, stores etc.
func (e *Engine) CancelOrder(
ctx context.Context,
cancel *types.OrderCancellation,
party string,
idgen IDGenerator,
) (_ []*types.OrderCancellationConfirmation, returnedErr error) {
timer := metrics.NewTimeCounter(cancel.MarketID, "execution", "CancelOrder")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("cancel order", logging.OrderCancellation(cancel))
}
// ensure that if orderID is specified marketId is as well
if len(cancel.OrderID) > 0 && len(cancel.MarketID) <= 0 {
return nil, ErrInvalidOrderCancellation
}
if len(cancel.MarketID) > 0 {
if len(cancel.OrderID) > 0 {
return e.cancelOrder(ctx, party, cancel.MarketID, cancel.OrderID, idgen)
}
return e.cancelOrderByMarket(ctx, party, cancel.MarketID)
}
return e.cancelAllPartyOrders(ctx, party)
}
func (e *Engine) cancelOrder(
ctx context.Context,
party, market, orderID string,
idgen IDGenerator,
) ([]*types.OrderCancellationConfirmation, error) {
mkt, ok := e.markets[market]
if !ok {
return nil, types.ErrInvalidMarketID
}
conf, err := mkt.CancelOrderWithIDGenerator(ctx, party, orderID, idgen)
if err != nil {
return nil, err
}
if conf.Order.Status == types.OrderStatusCancelled {
metrics.OrderGaugeAdd(-1, market)
}
return []*types.OrderCancellationConfirmation{conf}, nil
}
func (e *Engine) cancelOrderByMarket(ctx context.Context, party, market string) ([]*types.OrderCancellationConfirmation, error) {
mkt, ok := e.markets[market]
if !ok {
return nil, types.ErrInvalidMarketID
}
confirmations, err := mkt.CancelAllOrders(ctx, party)
if err != nil {
return nil, err
}
var confirmed int
for _, conf := range confirmations {
if conf.Order.Status == types.OrderStatusCancelled {
confirmed++
}
}
metrics.OrderGaugeAdd(-confirmed, market)
return confirmations, nil
}
func (e *Engine) cancelAllPartyOrders(ctx context.Context, party string) ([]*types.OrderCancellationConfirmation, error) {
confirmations := []*types.OrderCancellationConfirmation{}
for _, mkt := range e.marketsCpy {
confs, err := mkt.CancelAllOrders(ctx, party)
if err != nil && err != ErrTradingNotAllowed {
return nil, err
}
confirmations = append(confirmations, confs...)
var confirmed int
for _, conf := range confs {
if conf.Order.Status == types.OrderStatusCancelled {
confirmed++
}
}
metrics.OrderGaugeAdd(-confirmed, mkt.GetID())
}
return confirmations, nil
}
func (e *Engine) SubmitLiquidityProvision(
ctx context.Context,
sub *types.LiquidityProvisionSubmission,
party, deterministicID string,
) (returnedErr error) {
timer := metrics.NewTimeCounter(sub.MarketID, "execution", "LiquidityProvisionSubmission")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("submit liquidity provision",
logging.LiquidityProvisionSubmission(*sub),
logging.PartyID(party),
logging.LiquidityID(deterministicID),
)
}
mkt, ok := e.markets[sub.MarketID]
if !ok {
return types.ErrInvalidMarketID
}
return mkt.SubmitLiquidityProvision(ctx, sub, party, deterministicID)
}
func (e *Engine) AmendLiquidityProvision(ctx context.Context, lpa *types.LiquidityProvisionAmendment, party string,
deterministicID string,
) (returnedErr error) {
timer := metrics.NewTimeCounter(lpa.MarketID, "execution", "LiquidityProvisionAmendment")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("amend liquidity provision",
logging.LiquidityProvisionAmendment(*lpa),
logging.PartyID(party),
logging.MarketID(lpa.MarketID),
)
}
mkt, ok := e.markets[lpa.MarketID]
if !ok {
return types.ErrInvalidMarketID
}
return mkt.AmendLiquidityProvision(ctx, lpa, party, deterministicID)
}
func (e *Engine) CancelLiquidityProvision(ctx context.Context, cancel *types.LiquidityProvisionCancellation, party string) (returnedErr error) {
timer := metrics.NewTimeCounter(cancel.MarketID, "execution", "LiquidityProvisionCancellation")
defer func() {
timer.EngineTimeCounterAdd()
}()
if e.log.IsDebug() {
e.log.Debug("cancel liquidity provision",
logging.LiquidityProvisionCancellation(*cancel),
logging.PartyID(party),
logging.MarketID(cancel.MarketID),
)
}
mkt, ok := e.markets[cancel.MarketID]
if !ok {
return types.ErrInvalidMarketID
}
return mkt.CancelLiquidityProvision(ctx, cancel, party)
}
func (e *Engine) OnTick(ctx context.Context, t time.Time) {
timer := metrics.NewTimeCounter("-", "execution", "OnTick")
e.log.Debug("updating engine on new time update")
// notify markets of the time expiration
toDelete := []string{}
evts := make([]events.Event, 0, len(e.marketsCpy))
for _, mkt := range e.marketsCpy {
mkt := mkt
closing := mkt.OnTick(ctx, t)
if closing {
e.log.Info("market is closed, removing from execution engine",
logging.MarketID(mkt.GetID()))
toDelete = append(toDelete, mkt.GetID())
}
evts = append(evts, events.NewMarketDataEvent(ctx, mkt.GetMarketData()))
}
e.broker.SendBatch(evts)
for _, id := range toDelete {
e.removeMarket(id)
}
timer.EngineTimeCounterAdd()
}
func (e *Engine) GetMarketState(mktID string) (types.MarketState, error) {
mkt, ok := e.markets[mktID]
if !ok {
return types.MarketStateUnspecified, types.ErrInvalidMarketID
}
return mkt.GetMarketState(), nil
}
func (e *Engine) GetMarketData(mktID string) (types.MarketData, error) {
mkt, ok := e.markets[mktID]
if !ok {
return types.MarketData{}, types.ErrInvalidMarketID
}
return mkt.GetMarketData(), nil
}
func (e *Engine) OnMarketAuctionMinimumDurationUpdate(ctx context.Context, d time.Duration) error {
for _, mkt := range e.markets {
mkt.OnMarketAuctionMinimumDurationUpdate(ctx, d)
}
e.npv.auctionMinDuration = d
return nil
}
func (e *Engine) OnMarketLiquidityBondPenaltyUpdate(ctx context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update market liquidity bond penalty",
logging.Decimal("bond-penalty-factor", d),
)
}
for _, mkt := range e.markets {
mkt.BondPenaltyFactorUpdate(ctx, d)
}
e.npv.bondPenaltyFactor = d
return nil
}
func (e *Engine) OnMarketMarginScalingFactorsUpdate(ctx context.Context, v interface{}) error {
if e.log.IsDebug() {
e.log.Debug("update market scaling factors",
logging.Reflect("scaling-factors", v),
)
}
pscalingFactors, ok := v.(*vega.ScalingFactors)
if !ok {
return errors.New("invalid types for Margin ScalingFactors")
}
scalingFactors := types.ScalingFactorsFromProto(pscalingFactors)
for _, mkt := range e.marketsCpy {
if err := mkt.OnMarginScalingFactorsUpdate(ctx, scalingFactors); err != nil {
return err
}
}
e.npv.scalingFactors = scalingFactors
return nil
}
func (e *Engine) OnMarketFeeFactorsMakerFeeUpdate(ctx context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update maker fee in market fee factors",
logging.Decimal("maker-fee", d),
)
}
for _, mkt := range e.marketsCpy {
if err := mkt.OnFeeFactorsMakerFeeUpdate(ctx, d); err != nil {
return err
}
}
e.npv.makerFee = d
return nil
}
func (e *Engine) OnMarketFeeFactorsInfrastructureFeeUpdate(ctx context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update infrastructure fee in market fee factors",
logging.Decimal("infrastructure-fee", d),
)
}
for _, mkt := range e.marketsCpy {
if err := mkt.OnFeeFactorsInfrastructureFeeUpdate(ctx, d); err != nil {
return err
}
}
e.npv.infrastructureFee = d
return nil
}
func (e *Engine) OnSuppliedStakeToObligationFactorUpdate(_ context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update supplied stake to obligation factor",
logging.Decimal("factor", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnSuppliedStakeToObligationFactorUpdate(d)
}
e.npv.suppliedStakeToObligationFactor = d
return nil
}
func (e *Engine) OnMarketValueWindowLengthUpdate(_ context.Context, d time.Duration) error {
if e.log.IsDebug() {
e.log.Debug("update market value window length",
logging.Duration("window-length", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnMarketValueWindowLengthUpdate(d)
}
e.npv.marketValueWindowLength = d
return nil
}
func (e *Engine) OnMarketTargetStakeScalingFactorUpdate(_ context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update market stake scaling factor",
logging.Decimal("scaling-factor", d),
)
}
for _, mkt := range e.marketsCpy {
if err := mkt.OnMarketTargetStakeScalingFactorUpdate(d); err != nil {
return err
}
}
return nil
}
func (e *Engine) OnMarketTargetStakeTimeWindowUpdate(_ context.Context, d time.Duration) error {
if e.log.IsDebug() {
e.log.Debug("update market stake time window",
logging.Duration("time-window", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnMarketTargetStakeTimeWindowUpdate(d)
}
return nil
}
func (e *Engine) OnMarketLiquidityProvidersFeeDistributionTimeStep(_ context.Context, d time.Duration) error {
if e.log.IsDebug() {
e.log.Debug("update liquidity providers fee distribution time step",
logging.Duration("time-window", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnMarketLiquidityProvidersFeeDistribitionTimeStep(d)
}
e.npv.feeDistributionTimeStep = d
return nil
}
func (e *Engine) OnMarketLiquidityProvisionShapesMaxSizeUpdate(
_ context.Context, v int64,
) error {
if e.log.IsDebug() {
e.log.Debug("update liquidity provision max shape",
logging.Int64("max-shape", v),
)
}
for _, mkt := range e.marketsCpy {
_ = mkt.OnMarketLiquidityProvisionShapesMaxSizeUpdate(v)
}
e.npv.shapesMaxSize = v
return nil
}
func (e *Engine) OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate(
_ context.Context, d num.Decimal,
) error {
if e.log.IsDebug() {
e.log.Debug("update liquidity provision max liquidity fee factor",
logging.Decimal("max-liquidity-fee", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate(d)
}
e.npv.maxLiquidityFee = d
return nil
}
func (e *Engine) OnMarketLiquidityTargetStakeTriggeringRatio(ctx context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update target stake triggering ratio",
logging.Decimal("max-liquidity-fee", d),
)
}
for _, mkt := range e.marketsCpy {
mkt.OnMarketLiquidityTargetStakeTriggeringRatio(ctx, d)
}
return nil
}
func (e *Engine) OnMarketProbabilityOfTradingTauScalingUpdate(ctx context.Context, d num.Decimal) error {
if e.log.IsDebug() {
e.log.Debug("update probability of trading tau scaling",
logging.Decimal("probability-of-trading-tau-scaling", d),