common

package
v0.79.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2024 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// PriceMoveMid used to indicate that the mid price has moved.
	PriceMoveMid = 1

	// PriceMoveBestBid used to indicate that the best bid price has moved.
	PriceMoveBestBid = 2

	// PriceMoveBestAsk used to indicate that the best ask price has moved.
	PriceMoveBestAsk = 4

	// PriceMoveAll used to indicate everything has moved.
	PriceMoveAll = PriceMoveMid + PriceMoveBestBid + PriceMoveBestAsk
)
View Source
const (
	FutureMarketType marketType = iota
	SpotMarketType
)
View Source
const (
	TradePriceIndex       = 0
	BookPriceIndex        = 1
	FirstOraclePriceIndex = 2
)
View Source
const InitialOrderVersion = 1

InitialOrderVersion is set on `Version` field for every new order submission read from the network.

Variables

View Source
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")
	ErrMaxStopOrdersPerPartyReached                         = errors.New("max stop orders per party reached")
	ErrStopOrderSubmissionNotAllowedWithoutExistingPosition = errors.New("stop order submission not allowed without existing position")
	ErrStopOrderSideNotClosingThePosition                   = errors.New("side used in stop order does not close the position")
	ErrStopOrderMustBeReduceOnly                            = errors.New("stop order must be reduce only")
	ErrStopOrderExpiryInThePast                             = errors.New("stop order expiry in the past")
	ErrStopOrderSizeOverridePercentageInvalid               = errors.New("stop order size override percentage value is invalid")
	ErrPartyHasNoExistingLiquidityProvision                 = errors.New("party has no existing liquidity provision")
	// ErrStopOrderNotAllowedDuringOpeningAuction is returned if a trader attempts to send a stop order to a market that is in opening auction.
	ErrStopOrderNotAllowedDuringOpeningAuction = errors.New("stop orders are not accepted during the opening auction")
	// ErrStopOrderNotAllowedSameExpiryTimeForOCO is returned if both sides of an OCO have the same expiry time.
	ErrStopOrderNotAllowedSameExpiry = errors.New("stop order OCOs must not have the same expiry time")
	// ErrStopOrderSizeOverrideNotSupportedForSpots is returned when a stop order is received with size override for a spot product.
	ErrStopOrderSizeOverrideNotSupportedForSpots = errors.New("stop order size override is not supported for spot product")
	ErrAMMCannotRebase                           = errors.New("not enough liquidity for AMM to rebase")
	// ErrInvalidOrderPrice is returned when an order is submitted to a capped future with a price > max price.
	ErrInvalidOrderPrice = errors.New("invalid order price")
	// ErrIsolatedMarginFullyCollateralised is returned when a party tries to switch margin modes on a fully collateralised market.
	ErrIsolatedMarginFullyCollateralised = errors.New("isolated margin not permitted on fully collateralised markets")
	// ErrSettlementDataOutOfRange is returned when a capped future receives settlement data that is outside of the acceptable range (either > max price, or neither 0 nor max for binary settlements).
	ErrSettlementDataOutOfRange = errors.New("settlement data is outside of the price cap")
	ErrAMMBoundsOutsidePriceCap = errors.New("an AMM bound is outside of the price cap")
	// ErrSellOrderNotAllowed no sell orders are allowed in the current state.
	ErrSellOrderNotAllowed = errors.New("sell order not allowed")
)
View Source
var ErrCommitmentAmountTooLow = errors.New("commitment amount is too low")
View Source
var (
	ErrSnapshotKeyDoesNotExist = errors.New("unknown key for market activity tracker snapshot")
)
View Source
var One = num.UintOne()

Functions

func CalculateTimeWeightedAverageBookPrice added in v0.74.2

func CalculateTimeWeightedAverageBookPrice(timeToPrice map[int64]*num.Uint, t int64, markPricePeriod int64) *num.Uint

CalculateTimeWeightedAverageBookPrice calculates the time weighted average of the timepoints where book price was calculated.

func CompositePriceByMedian added in v0.74.2

func CompositePriceByMedian(prices []*num.Uint, lastUpdate []int64, delta []time.Duration, t int64) *num.Uint

CompositePriceByMedian returns the median mark price out of the non stale ones or nil if there is none.

func CompositePriceByWeight added in v0.74.2

func CompositePriceByWeight(prices []*num.Uint, weights []num.Decimal, lastUpdateTime []int64, delta []time.Duration, t int64) *num.Uint

CompositePriceByWeight calculates the mid price out of the non-stale price by the weights assigned to each mid price.

func MedianPrice added in v0.74.2

func MedianPrice(prices []*num.Uint) *num.Uint

MedianPrice returns the median of the given prices (pBook, pTrades, pOracle1..n).

func PriceFromBookAtTime added in v0.74.2

func PriceFromBookAtTime(C *num.Uint, initialScalingFactor, slippageFactor, shortRiskFactor, longRiskFactor num.Decimal, orderBook *matching.CachedOrderBook) *num.Uint

PriceFromBookAtTime calculate the mark price as the average price of buying/selling the quantity implied by scaling C by the factors. If there is no bid or ask price for the required quantity, returns nil.

func PriceFromTrades added in v0.74.2

func PriceFromTrades(trades []*types.Trade, decayWeight, lambda, decayPower num.Decimal, t int64) *num.Uint

PriceFromTrades calculates the mark price from trades in the current price frequency.

Types

type AMM added in v0.77.0

type AMM interface {
	GetAMMPoolsBySubAccount() map[string]AMMPool
	GetAllSubAccounts() []string
	IsAMMPartyID(string) bool
}

type AMMPool added in v0.77.0

type AMMPool interface {
	OrderbookShape(from, to *num.Uint, idgen *idgeneration.IDGenerator) *types.OrderbookShapeResult
	LiquidityFee() num.Decimal
	CommitmentAmount() *num.Uint
}

type AMMState added in v0.77.0

type AMMState struct {
	// contains filtered or unexported fields
}

func (*AMMState) IncrementTick added in v0.77.0

func (a *AMMState) IncrementTick()

IncrementTick increments the internal tick/time counter.

func (*AMMState) StartEpoch added in v0.77.0

func (a *AMMState) StartEpoch()

StartEpoch resets the internal tick counter, ready for the new epoch to start.

func (*AMMState) UpdateScore added in v0.77.0

func (a *AMMState) UpdateScore(score num.Decimal)

UpdateScore updates the current epoch score.

func (*AMMState) UpdateStake added in v0.77.0

func (a *AMMState) UpdateStake(stake num.Decimal)

UpdateStake updates the time-weighted average stake during epoch.

func (*AMMState) UpdateTick added in v0.77.0

func (a *AMMState) UpdateTick(stake, score num.Decimal)

UpdateTick is equivalent to calls to UpdateStake, UpdateScore, and IncrementTick.

type AccountBalanceChecker added in v0.73.0

type AccountBalanceChecker interface {
	GetAvailableBalance(party string) (*num.Uint, error)
	GetAllStakingParties() []string
}

type Assets

type Assets interface {
	Get(assetID string) (*assets.Asset, error)
}

type AuctionState

type AuctionState interface {
	price.AuctionState
	// are we in auction, and what auction are we in?
	ExtendAuctionSuspension(delta types.AuctionDuration)
	ExtendAuctionLongBlock(delta types.AuctionDuration)
	ExtendAuctionAutomatedPurchase(delta types.AuctionDuration)
	InAuction() bool
	IsOpeningAuction() bool
	IsPriceAuction() bool
	IsFBA() bool
	IsMonitorAuction() bool
	IsPAPAuction() bool
	ExceededMaxOpening(time.Time) 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
	UpdateMaxDuration(ctx context.Context, d time.Duration)
	StartGovernanceSuspensionAuction(t time.Time)
	StartLongBlockAuction(t time.Time, d int64)
	StartAutomatedPurchaseAuction(t time.Time, d int64)
	EndGovernanceSuspensionAuction()
}

AuctionState ...

type Banking added in v0.74.0

type Banking interface {
	RegisterTradingFees(ctx context.Context, asset string, feesPerParty map[string]*num.Uint)
}

type Broker

type Broker interface {
	Send(event events.Event)
	SendBatch(events []events.Event)
	Stage(event events.Event)
}

Broker (no longer need to mock this, use the broker/mocks wrapper).

type Collateral

type Collateral 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)
	GetOrCreatePartyOrderMarginAccount(ctx context.Context, partyID, marketID, asset string) (string, error)
	BondUpdate(ctx context.Context, market string, transfer *types.Transfer) (*types.LedgerMovement, error)
	BondSpotUpdate(ctx context.Context, market string, transfer *types.Transfer) (*types.LedgerMovement, error)
	RemoveBondAccount(partyID, marketID, asset string) 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, factor *num.Uint, useGeneralAccountForMarginSearch func(string) bool) ([]*types.LedgerMovement, error)
	ClearMarket(ctx context.Context, mktID, asset string, parties []string, keepInsurance bool) ([]*types.LedgerMovement, error)
	HasGeneralAccount(party, asset string) bool
	ClearPartyMarginAccount(ctx context.Context, party, market, asset string) (*types.LedgerMovement, error)
	ClearPartyOrderMarginAccount(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)
	TransferSpotFees(ctx context.Context, marketID string, assetID string, ft events.FeesTransfer, sourceAccountType types.AccountType) ([]*types.LedgerMovement, error)
	TransferSpotFeesContinuousTrading(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)
	IsolatedMarginUpdate(updates []events.Risk) []events.Margin
	PerpsFundingSettlement(ctx context.Context, marketID string, transfers []events.Transfer, asset string, round *num.Uint, useGeneralAccountForMarginSearch func(string) bool) ([]events.Margin, []*types.LedgerMovement, error)
	MarkToMarket(ctx context.Context, marketID string, transfers []events.Transfer, asset string, useGeneralAccountForMarginSearch func(string) bool) ([]events.Margin, []*types.LedgerMovement, error)
	RemoveDistressed(ctx context.Context, parties []events.MarketPosition, marketID, asset string, useGeneralAccount func(string) bool) (*types.LedgerMovement, error)
	GetMarketLiquidityFeeAccount(market, asset string) (*types.Account, error)
	GetAssetQuantum(asset string) (num.Decimal, error)
	GetInsurancePoolBalance(marketID, asset string) (*num.Uint, bool)
	AssetExists(string) bool
	CreateMarketAccounts(context.Context, string, string) (string, string, error)
	CreateSpotMarketAccounts(ctx context.Context, marketID, quoteAsset string) error
	SuccessorInsuranceFraction(ctx context.Context, successor, parent, asset string, fraction num.Decimal) *types.LedgerMovement
	ClearInsurancepool(ctx context.Context, marketID string, asset string, clearFees bool) ([]*types.LedgerMovement, error)
	TransferToHoldingAccount(ctx context.Context, transfer *types.Transfer, accountType types.AccountType) (*types.LedgerMovement, error)
	ReleaseFromHoldingAccount(ctx context.Context, transfer *types.Transfer, toAccounType types.AccountType) (*types.LedgerMovement, error)
	ClearSpotMarket(ctx context.Context, mktID, quoteAsset string, parties []string) ([]*types.LedgerMovement, error)
	PartyHasSufficientBalance(asset, partyID string, amount *num.Uint, fromAccountType types.AccountType) error
	PartyCanCoverFees(asset, mktID, partyID string, amount *num.Uint) error
	TransferSpot(ctx context.Context, partyID, toPartyID, asset string, quantity *num.Uint, fromAccountType, toAccountType types.AccountType) (*types.LedgerMovement, error)
	GetOrCreatePartyLiquidityFeeAccount(ctx context.Context, partyID, marketID, asset string) (*types.Account, error)
	GetPartyLiquidityFeeAccount(market, partyID, asset string) (*types.Account, error)
	GetLiquidityFeesBonusDistributionAccount(marketID, asset string) (*types.Account, error)
	CreatePartyGeneralAccount(ctx context.Context, partyID, asset string) (string, error)
	GetOrCreateLiquidityFeesBonusDistributionAccount(ctx context.Context, marketID, asset string) (*types.Account, error)
	CheckOrderSpam(party, market string, assets []string) error
	CheckOrderSpamAllMarkets(party string) error
	GetAllParties() []string
	GetSystemAccountBalance(asset, market string, accountType types.AccountType) (*num.Uint, error)
	EarmarkForAutomatedPurchase(asset string, accountType types.AccountType, min, max *num.Uint) (*num.Uint, error)
	UnearmarkForAutomatedPurchase(asset string, accountType types.AccountType, releaseRequest *num.Uint) error

	// amm stuff
	SubAccountClosed(ctx context.Context, party, subAccount, asset, market string) ([]*types.LedgerMovement, error)
	SubAccountUpdate(
		ctx context.Context,
		party, subAccount, asset, market string,
		transferType types.TransferType,
		amount *num.Uint,
	) (*types.LedgerMovement, error)
	SubAccountRelease(
		ctx context.Context,
		party, subAccount, asset, market string, pos events.MarketPosition,
	) ([]*types.LedgerMovement, events.Margin, error)
	CreatePartyAMMsSubAccounts(
		ctx context.Context,
		party, subAccount, asset, market string,
	) (general *types.Account, margin *types.Account, err error)
}

type CommonMarket added in v0.73.0

type CommonMarket interface {
	GetID() string
	Hash() []byte
	GetAssets() []string
	Reject(context.Context) error
	GetMarketData() types.MarketData
	StartOpeningAuction(context.Context) error
	GetEquityShares() *EquityShares
	GetEquitySharesForParty(partyID string) num.Decimal
	IntoType() types.Market
	OnEpochEvent(ctx context.Context, epoch types.Epoch)
	OnEpochRestore(ctx context.Context, epoch types.Epoch)
	GetAssetForProposerBonus() string
	GetMarketCounters() *types.MarketCounters
	GetPartiesStats() *types.MarketStats
	GetMarketState() types.MarketState
	BlockEnd(context.Context)
	BeginBlock(context.Context)
	UpdateMarketState(ctx context.Context, changes *types.MarketStateUpdateConfiguration) error
	GetFillPrice(volume uint64, side types.Side) (*num.Uint, error)
	Mkt() *types.Market
	EnterLongBlockAuction(ctx context.Context, duration int64)

	IsOpeningAuction() bool

	// network param updates
	OnMarketPartiesMaximumStopOrdersUpdate(context.Context, *num.Uint)
	OnMarketMinLpStakeQuantumMultipleUpdate(context.Context, num.Decimal)
	OnMarketMinProbabilityOfTradingLPOrdersUpdate(context.Context, num.Decimal)
	OnMarketProbabilityOfTradingTauScalingUpdate(context.Context, num.Decimal)
	OnMarketValueWindowLengthUpdate(time.Duration)
	OnFeeFactorsInfrastructureFeeUpdate(context.Context, num.Decimal)
	OnFeeFactorsTreasuryFeeUpdate(context.Context, num.Decimal)
	OnFeeFactorsBuyBackFeeUpdate(context.Context, num.Decimal)
	OnFeeFactorsMakerFeeUpdate(context.Context, num.Decimal)
	OnMarkPriceUpdateMaximumFrequency(context.Context, time.Duration)
	OnMarketAuctionMinimumDurationUpdate(context.Context, time.Duration)
	OnMarketAuctionMaximumDurationUpdate(context.Context, time.Duration)
	OnMarketLiquidityV2EarlyExitPenaltyUpdate(num.Decimal)
	OnMarketLiquidityV2MaximumLiquidityFeeFactorLevelUpdate(num.Decimal)
	OnMarketLiquidityV2SLANonPerformanceBondPenaltySlopeUpdate(num.Decimal)
	OnMarketLiquidityV2SLANonPerformanceBondPenaltyMaxUpdate(num.Decimal)
	OnMarketLiquidityV2StakeToCCYVolume(d num.Decimal)
	OnMarketLiquidityV2BondPenaltyFactorUpdate(d num.Decimal)
	OnMarketLiquidityV2ProvidersFeeCalculationTimeStep(t time.Duration)
	OnMarketLiquidityEquityLikeShareFeeFractionUpdate(d num.Decimal)
	OnAMMMinCommitmentQuantumUpdate(context.Context, *num.Uint)
	OnMarketAMMMaxCalculationLevels(context.Context, *num.Uint)

	// liquidity provision
	CancelLiquidityProvision(context.Context, *types.LiquidityProvisionCancellation, string) error
	AmendLiquidityProvision(context.Context, *types.LiquidityProvisionAmendment, string, string) error
	SubmitLiquidityProvision(context.Context, *types.LiquidityProvisionSubmission, string, string) error

	// order management
	SubmitOrderWithIDGeneratorAndOrderID(context.Context, *types.OrderSubmission, string, IDGenerator, string, bool) (*types.OrderConfirmation, error)
	AmendOrderWithIDGenerator(context.Context, *types.OrderAmendment, string, IDGenerator) (*types.OrderConfirmation, error)
	CancelAllOrders(context.Context, string) ([]*types.OrderCancellationConfirmation, error)
	CancelOrderWithIDGenerator(context.Context, string, string, IDGenerator) (*types.OrderCancellationConfirmation, error)
	CancelAllStopOrders(context.Context, string) error
	CancelStopOrder(context.Context, string, string) error
	SubmitStopOrdersWithIDGeneratorAndOrderIDs(context.Context, *types.StopOrdersSubmission, string, IDGenerator, *string, *string) (*types.OrderConfirmation, error)

	SubmitAMM(context.Context, *types.SubmitAMM, string) error
	AmendAMM(context.Context, *types.AmendAMM, string) error
	CancelAMM(context.Context, *types.CancelAMM, string) error

	PostRestore(context.Context) error
	ValidateSettlementData(*num.Uint) bool
}

type CompositePriceCalculator added in v0.74.2

type CompositePriceCalculator struct {
	// contains filtered or unexported fields
}

func NewCompositePriceCalculator added in v0.74.2

func NewCompositePriceCalculator(ctx context.Context, config *types.CompositePriceConfiguration, oe products.OracleEngine, timeService TimeService) *CompositePriceCalculator

func NewCompositePriceCalculatorFromSnapshot added in v0.74.2

func NewCompositePriceCalculatorFromSnapshot(ctx context.Context, mp *num.Uint, timeService TimeService, oe OracleEngine, mpc *snapshot.CompositePriceCalculator) *CompositePriceCalculator

func (*CompositePriceCalculator) CalculateBookMarkPriceAtTimeT added in v0.74.2

func (mpc *CompositePriceCalculator) CalculateBookMarkPriceAtTimeT(initialScalingFactor, slippageFactor, shortRiskFactor, longRiskFactor num.Decimal, t int64, ob *matching.CachedOrderBook)

CalculateBookMarkPriceAtTimeT is called every interval (currently at the end of each block) to calculate the mark price implied by the book. If there is insufficient quantity in the book, ignore this price IF the market is in auction set the mark price to the indicative price if not zero.

func (*CompositePriceCalculator) CalculateMarkPrice added in v0.74.2

func (mpc *CompositePriceCalculator) CalculateMarkPrice(ctx context.Context, priceMonitor PriceMonitor, as AuctionState, t int64, ob *matching.CachedOrderBook, markPriceFrequency time.Duration, initialScalingFactor, slippageFactor, shortRiskFactor, longRiskFactor num.Decimal, checkPriceMonitor bool, resetPriceMonitoringEngine bool) (*num.Uint, error)

CalculateMarkPrice is called at the end of each mark price calculation interval and calculates the mark price using the mark price type methodology.

func (*CompositePriceCalculator) Close added in v0.74.2

func (mpc *CompositePriceCalculator) Close(ctx context.Context)

func (*CompositePriceCalculator) GetConfig added in v0.74.2

func (*CompositePriceCalculator) GetData added in v0.74.2

func (*CompositePriceCalculator) GetPrice added in v0.74.2

func (mpc *CompositePriceCalculator) GetPrice() *num.Uint

func (*CompositePriceCalculator) GetUpdateOraclePriceFunc added in v0.74.2

func (mpc *CompositePriceCalculator) GetUpdateOraclePriceFunc(oracleIndex int) func(ctx context.Context, data dscommon.Data) error

UpdateOraclePrice is called when a new oracle price is available.

func (*CompositePriceCalculator) IntoProto added in v0.74.2

func (*CompositePriceCalculator) NewTrade added in v0.74.2

func (mpc *CompositePriceCalculator) NewTrade(trade *types.Trade)

NewTrade is called to inform the mark price calculator on a new trade. All the trades for a given mark price calculation interval are saved until the end of the interval.

func (*CompositePriceCalculator) NotifyOnDataSourcePropagation added in v0.79.0

func (mpc *CompositePriceCalculator) NotifyOnDataSourcePropagation(listener func(context.Context, string, *num.Uint))

func (*CompositePriceCalculator) OverridePrice added in v0.74.2

func (mpc *CompositePriceCalculator) OverridePrice(p *num.Uint)

OverridePrice is called to set the price externally. This is used when leaving the opening auction if the methodology yielded no valid price.

func (*CompositePriceCalculator) SetBookPriceAtTimeT added in v0.75.0

func (mpc *CompositePriceCalculator) SetBookPriceAtTimeT(mp *num.Uint, t int64)

func (*CompositePriceCalculator) SetMaxPriceCap added in v0.77.0

func (mpc *CompositePriceCalculator) SetMaxPriceCap(mp *num.Uint)

SetMaxPriceCap is called from a capped future, to filter out price data that exceeds the max price.

func (*CompositePriceCalculator) SetOraclePriceScalingFunc added in v0.74.2

func (mpc *CompositePriceCalculator) SetOraclePriceScalingFunc(f func(context.Context, *num.Numeric, int64) *num.Uint)

func (*CompositePriceCalculator) UpdateConfig added in v0.74.2

type DelayTransactionsTarget added in v0.77.0

type DelayTransactionsTarget interface {
	MarketDelayRequiredUpdated(marketID string, required bool)
}

type EligibilityChecker

type EligibilityChecker interface {
	IsEligibleForProposerBonus(marketID string, volumeTraded *num.Uint) bool
}

type EpochEngine

type EpochEngine interface {
	NotifyOnEpoch(f func(context.Context, types.Epoch), r func(context.Context, types.Epoch))
}

type EquityLikeShares

type EquityLikeShares interface {
	AllShares() map[string]num.Decimal
	SetPartyStake(id string, newStakeU *num.Uint)
	HasShares(id string) bool
}

type EquityShares

type EquityShares struct {
	// contains filtered or unexported fields
}

EquityShares module controls the Equity sharing algorithm described on the spec: https://github.com/vegaprotocol/product/blob/02af55e048a92a204e9ee7b7ae6b4475a198c7ff/specs/0042-setting-fees-and-rewarding-lps.md#calculating-liquidity-provider-equity-like-share

func NewEquityShares

func NewEquityShares(mvp num.Decimal) *EquityShares

func NewEquitySharesFromSnapshot

func NewEquitySharesFromSnapshot(state *types.EquityShare) *EquityShares

func (*EquityShares) AllShares

func (es *EquityShares) AllShares() map[string]num.Decimal

AllShares returns the ratio of equity for each party on the market.

func (*EquityShares) AvgEntryValuation

func (es *EquityShares) AvgEntryValuation(id string) num.Decimal

AvgEntryValuation returns the Average Entry Valuation for a given party.

func (*EquityShares) AvgTradeValue

func (es *EquityShares) AvgTradeValue(avg num.Decimal) *EquityShares

func (EquityShares) Changed

func (es EquityShares) Changed() bool

func (*EquityShares) GetCPShares

func (es *EquityShares) GetCPShares() []*types.ELSShare

func (*EquityShares) GetLPSCount

func (es *EquityShares) GetLPSCount() int

func (*EquityShares) GetMarketGrowth

func (es *EquityShares) GetMarketGrowth() num.Decimal

func (*EquityShares) GetState

func (es *EquityShares) GetState() *types.EquityShare

func (*EquityShares) GetTotalVStake

func (es *EquityShares) GetTotalVStake() num.Decimal

func (*EquityShares) HasShares added in v0.77.0

func (es *EquityShares) HasShares(party string) bool

HasShares returns whether the given party is registered as an LP with ELS.

func (*EquityShares) InheritELS

func (es *EquityShares) InheritELS(shares []*types.ELSShare)

func (*EquityShares) LpsToLiquidityProviderFeeShare

func (es *EquityShares) LpsToLiquidityProviderFeeShare(ls map[string]num.Decimal) []*types.LiquidityProviderFeeShare

func (*EquityShares) OpeningAuctionEnded

func (es *EquityShares) OpeningAuctionEnded()

OpeningAuctionEnded signal to the EquityShare that the opening auction has ended.

func (*EquityShares) ResetAvgToLP added in v0.72.7

func (es *EquityShares) ResetAvgToLP(id string)

func (*EquityShares) RestoreELS

func (es *EquityShares) RestoreELS(shares []*types.ELSShare)

func (*EquityShares) RollbackParentELS

func (es *EquityShares) RollbackParentELS()

func (*EquityShares) SetCPShares

func (es *EquityShares) SetCPShares(shares []*types.ELSShare)

func (*EquityShares) SetPartyStake

func (es *EquityShares) SetPartyStake(id string, newStakeU *num.Uint)

SetPartyStake sets LP values for a given party.

func (*EquityShares) SharesExcept

func (es *EquityShares) SharesExcept(except map[string]struct{}) map[string]num.Decimal

SharesExcept returns the ratio of equity for each party on the market, except the ones listed in parameter.

func (*EquityShares) SharesFromParty

func (es *EquityShares) SharesFromParty(party string) num.Decimal

SharesFromParty returns the equity-like shares of a given party on the market.

func (*EquityShares) UpdateVStake

func (es *EquityShares) UpdateVStake()

type ExpiringOrders

type ExpiringOrders struct {
	// contains filtered or unexported fields
}

func NewExpiringOrders

func NewExpiringOrders() *ExpiringOrders

func NewExpiringOrdersFromState

func NewExpiringOrdersFromState(orders []*types.Order) *ExpiringOrders

func (ExpiringOrders) Changed

func (a ExpiringOrders) Changed() bool

func (*ExpiringOrders) Expire

func (a *ExpiringOrders) Expire(ts int64) []string

func (*ExpiringOrders) GetExpiryingOrderCount

func (a *ExpiringOrders) GetExpiryingOrderCount() int

func (*ExpiringOrders) GetState

func (a *ExpiringOrders) GetState() []*types.Order

func (*ExpiringOrders) Insert

func (a *ExpiringOrders) Insert(
	orderID string, ts int64,
)

func (*ExpiringOrders) RemoveOrder

func (a *ExpiringOrders) RemoveOrder(expiresAt int64, orderID string) bool

type FeeSplitter

type FeeSplitter struct {
	// contains filtered or unexported fields
}

func NewFeeSplitter

func NewFeeSplitter() *FeeSplitter

func NewFeeSplitterFromSnapshot

func NewFeeSplitterFromSnapshot(fs *types.FeeSplitter, now time.Time) *FeeSplitter

func (*FeeSplitter) AddTradeValue

func (fs *FeeSplitter) AddTradeValue(tv *num.Uint)

func (*FeeSplitter) AvgTradeValue

func (fs *FeeSplitter) AvgTradeValue() num.Decimal

func (*FeeSplitter) Changed

func (fs *FeeSplitter) Changed() bool

func (*FeeSplitter) Elapsed

func (fs *FeeSplitter) Elapsed() time.Duration

Elapsed returns the distance (in duration) from TimeWindowStart and CurrentTime.

func (*FeeSplitter) GetState

func (fs *FeeSplitter) GetState() *types.FeeSplitter

func (*FeeSplitter) MarketValueProxy

func (fs *FeeSplitter) MarketValueProxy(mvwl time.Duration, totalStakeU *num.Uint) num.Decimal

MarketValueProxy returns the market value proxy according to the spec: https://github.com/vegaprotocol/product/blob/master/specs/0042-setting-fees-and-rewarding-lps.md

func (*FeeSplitter) SetCurrentTime

func (fs *FeeSplitter) SetCurrentTime(t time.Time) error

func (*FeeSplitter) SetElapsed

func (fs *FeeSplitter) SetElapsed(e time.Duration)

func (*FeeSplitter) SetTradeValue

func (fs *FeeSplitter) SetTradeValue(tv *num.Uint)

func (*FeeSplitter) TimeWindowStart

func (fs *FeeSplitter) TimeWindowStart(t time.Time)

TimeWindowStart starts or restarts (if active) a current time window. This sets the internal timers to `t` and resets the accumulated trade values.

func (*FeeSplitter) TradeValue

func (fs *FeeSplitter) TradeValue() *num.Uint

type FeeTransfer

type FeeTransfer struct {
	// contains filtered or unexported fields
}

func NewFeeTransfer

func NewFeeTransfer(transfers []*types.Transfer, totalFeesPerParty map[string]*num.Uint) FeeTransfer

func (FeeTransfer) TotalFeesAmountPerParty

func (ft FeeTransfer) TotalFeesAmountPerParty() map[string]*num.Uint

func (FeeTransfer) Transfers

func (ft FeeTransfer) Transfers() []*types.Transfer

type IDGenerator

type IDGenerator interface {
	NextID() string
}

type LiquidityEngine

type LiquidityEngine interface {
	GetLegacyOrders() []string
	OnEpochRestore(ep types.Epoch)
	ResetSLAEpoch(t time.Time, markPrice *num.Uint, midPrice *num.Uint, positionFactor num.Decimal)
	ApplyPendingProvisions(ctx context.Context, now time.Time) liquidity.Provisions
	PendingProvision() liquidity.Provisions
	PendingProvisionByPartyID(party string) *types.LiquidityProvision
	CalculateSLAPenalties(time.Time) liquidity.SlaPenalties
	ResetAverageLiquidityScores()
	UpdateAverageLiquidityScores(num.Decimal, num.Decimal, *num.Uint, *num.Uint)
	GetAverageLiquidityScores() map[string]num.Decimal
	SubmitLiquidityProvision(context.Context, *types.LiquidityProvisionSubmission, string, liquidity.IDGen) (bool, error)
	RejectLiquidityProvision(context.Context, string) error
	AmendLiquidityProvision(ctx context.Context, lpa *types.LiquidityProvisionAmendment, party string, isCancel bool) (bool, error)
	CancelLiquidityProvision(context.Context, string) error
	ValidateLiquidityProvisionAmendment(*types.LiquidityProvisionAmendment) error
	StopLiquidityProvision(context.Context, string) error
	IsLiquidityProvider(string) bool
	ProvisionsPerParty() liquidity.ProvisionsPerParty
	LiquidityProvisionByPartyID(string) *types.LiquidityProvision
	CalculateSuppliedStake() *num.Uint
	CalculateSuppliedStakeWithoutPending() *num.Uint
	UpdatePartyCommitment(string, *num.Uint) (*types.LiquidityProvision, error)
	EndBlock(*num.Uint, *num.Uint, num.Decimal)
	UpdateMarketConfig(liquidity.RiskModel, liquidity.PriceMonitor)
	UpdateSLAParameters(*types.LiquiditySLAParams)
	OnNonPerformanceBondPenaltySlopeUpdate(num.Decimal)
	OnNonPerformanceBondPenaltyMaxUpdate(num.Decimal)
	OnMinProbabilityOfTradingLPOrdersUpdate(num.Decimal)
	OnProbabilityOfTradingTauScalingUpdate(num.Decimal)
	OnMaximumLiquidityFeeFactorLevelUpdate(num.Decimal)
	OnStakeToCcyVolumeUpdate(stakeToCcyVolume num.Decimal)
	OnProvidersFeeCalculationTimeStep(time.Duration)
	IsProbabilityOfTradingInitialised() bool
	GetPartyLiquidityScore(orders []*types.Order, bestBid, bestAsk num.Decimal, minP, maxP *num.Uint) num.Decimal

	LiquidityProviderSLAStats(t time.Time) []*types.LiquidityProviderSLA

	RegisterAllocatedFeesPerParty(feesPerParty map[string]*num.Uint)
	PaidLiquidityFeesStats() *types.PaidLiquidityFeesStats

	ReadyForFeesAllocation(time.Time) bool
	ResetFeeAllocationPeriod(t time.Time)

	V1StateProvider() types.StateProvider
	V2StateProvider() types.StateProvider
	StopSnapshots()
}

type MarketActivityTracker

type MarketActivityTracker struct {
	// contains filtered or unexported fields
}

MarketActivityTracker tracks how much fees are paid and received for a market by parties by epoch.

func NewMarketActivityTracker

func NewMarketActivityTracker(log *logging.Logger, teams Teams, balanceChecker AccountBalanceChecker, broker Broker, collateral QuantumGetter) *MarketActivityTracker

NewMarketActivityTracker instantiates the fees tracker.

func (*MarketActivityTracker) AddAMMSubAccount added in v0.77.0

func (mat *MarketActivityTracker) AddAMMSubAccount(asset, marketID, subAccount string)

AddAMMSubAccount records sub account entries for AMM in given market.

func (*MarketActivityTracker) AddValueTraded

func (mat *MarketActivityTracker) AddValueTraded(asset, marketID string, value *num.Uint)

AddValueTraded records the value of a trade done in the given market.

func (*MarketActivityTracker) CalculateMetricForIndividuals added in v0.73.0

func (mat *MarketActivityTracker) CalculateMetricForIndividuals(ctx context.Context, ds *vega.DispatchStrategy) []*types.PartyContributionScore

CalculateMetricForIndividuals calculates the metric corresponding to the dispatch strategy and returns a slice of the contribution scores of the parties. Markets in scope are the ones passed in the dispatch strategy if any or all available markets for the asset for metric. Parties in scope depend on the `IndividualScope_INDIVIDUAL_SCOPE_IN_TEAM` and can include all parties, only those in teams, and only those not in teams.

func (*MarketActivityTracker) CalculateMetricForTeams added in v0.73.0

CalculateMetricForTeams calculates the metric for teams and their respective team members for markets in scope of the dispatch strategy.

func (*MarketActivityTracker) CalculateTotalMakerContributionInQuantum added in v0.77.8

func (mat *MarketActivityTracker) CalculateTotalMakerContributionInQuantum(windowSize int) (map[string]*num.Uint, map[string]num.Decimal)

func (*MarketActivityTracker) Checkpoint

func (mat *MarketActivityTracker) Checkpoint() ([]byte, error)

func (*MarketActivityTracker) GameFinished added in v0.77.8

func (mat *MarketActivityTracker) GameFinished(gameID string)

func (*MarketActivityTracker) GetAllAMMParties added in v0.77.0

func (mat *MarketActivityTracker) GetAllAMMParties(asset string, mkts []string) map[string]struct{}

func (*MarketActivityTracker) GetAllMarketIDs

func (mat *MarketActivityTracker) GetAllMarketIDs() []string

GetAllMarketIDs returns all the current market IDs.

func (*MarketActivityTracker) GetLastEpochTakeFees added in v0.75.0

func (mat *MarketActivityTracker) GetLastEpochTakeFees(asset string, markets []string, epochs int32) map[string]*num.Uint

func (*MarketActivityTracker) GetMarketsWithEligibleProposer

func (mat *MarketActivityTracker) GetMarketsWithEligibleProposer(asset string, markets []string, payoutAsset string, funder string, eligibleKeys []string) []*types.MarketContributionScore

GetMarketsWithEligibleProposer gets all the markets within the given asset (or just all the markets in scope passed as a parameter) that are eligible for proposer bonus.

func (*MarketActivityTracker) GetNotionalVolumeForAsset added in v0.79.0

func (mat *MarketActivityTracker) GetNotionalVolumeForAsset(asset string, markets []string, windowSize int) *num.Uint

func (*MarketActivityTracker) GetProposer

func (mat *MarketActivityTracker) GetProposer(market string) string

GetProposer returns the proposer of the market or empty string if the market doesn't exist.

func (*MarketActivityTracker) GetState

func (mat *MarketActivityTracker) GetState(k string) ([]byte, []types.StateProvider, error)

func (*MarketActivityTracker) IsMarketEligibleForBonus

func (mat *MarketActivityTracker) IsMarketEligibleForBonus(asset, market, payoutAsset string, marketsInScope []string, funder string) bool

IsMarketEligibleForBonus returns true is the market proposer is eligible for market proposer bonus and has not been paid for the combination of payout asset and marketsInScope. The proposer is not market as having been paid until told to do so (if actually paid).

func (*MarketActivityTracker) Keys

func (mat *MarketActivityTracker) Keys() []string

func (*MarketActivityTracker) Load

func (mat *MarketActivityTracker) Load(_ context.Context, data []byte) error

func (*MarketActivityTracker) LoadState

func (*MarketActivityTracker) MarkPaidProposer

func (mat *MarketActivityTracker) MarkPaidProposer(asset, market, payoutAsset string, marketsInScope []string, funder string)

MarkPaidProposer marks the proposer of the market as having been paid proposer bonus.

func (*MarketActivityTracker) MarketProposed

func (mat *MarketActivityTracker) MarketProposed(asset, marketID, proposer string)

MarketProposed is called when the market is proposed and adds the market to the tracker.

func (*MarketActivityTracker) MarketTrackedForAsset added in v0.73.0

func (mat *MarketActivityTracker) MarketTrackedForAsset(market, asset string) bool

MarketTrackedForAsset returns whether the given market is seen to have the given asset by the tracker.

func (*MarketActivityTracker) Name

func (*MarketActivityTracker) Namespace

func (*MarketActivityTracker) NeedsInitialisation added in v0.73.0

func (mat *MarketActivityTracker) NeedsInitialisation(asset, market string) bool

NeedsInitialisation is a heuristic migration - if there is no time weighted position data when restoring from snapshot, we will restore positions from the market. This will only happen on the one time migration from a version preceding the new metrics. If we're already on a new version, either there are no time-weighted positions and no positions or there are time weighted positions and they will not be restored.

func (*MarketActivityTracker) NotionalTakerVolumeForAllParties added in v0.73.0

func (mat *MarketActivityTracker) NotionalTakerVolumeForAllParties() map[types.PartyID]*num.Uint

func (*MarketActivityTracker) NotionalTakerVolumeForParty added in v0.73.0

func (mat *MarketActivityTracker) NotionalTakerVolumeForParty(party string) *num.Uint

func (*MarketActivityTracker) OnEpochEvent added in v0.73.0

func (mat *MarketActivityTracker) OnEpochEvent(ctx context.Context, epoch types.Epoch)

OnEpochEvent is called when the state of the epoch changes, we only care about new epochs starting.

func (*MarketActivityTracker) OnEpochRestore added in v0.73.0

func (mat *MarketActivityTracker) OnEpochRestore(_ context.Context, epoch types.Epoch)

OnEpochRestore is called when the state of the epoch changes, we only care about new epochs starting.

func (*MarketActivityTracker) OnMinEpochsInTeamForRewardEligibilityUpdated added in v0.73.0

func (mat *MarketActivityTracker) OnMinEpochsInTeamForRewardEligibilityUpdated(_ context.Context, value int64) error

func (*MarketActivityTracker) PublishGameMetric added in v0.77.0

func (mat *MarketActivityTracker) PublishGameMetric(ctx context.Context, dispatchStrategy []*vega.DispatchStrategy, now time.Time)

func (*MarketActivityTracker) RecordFundingPayment added in v0.76.0

func (mat *MarketActivityTracker) RecordFundingPayment(asset, party, market string, amount num.Decimal)

RecordFundingPayment passes the mark to market win/loss transfer amount to the asset/market tracker to be recorded.

func (*MarketActivityTracker) RecordM2M added in v0.73.0

func (mat *MarketActivityTracker) RecordM2M(asset, party, market string, amount num.Decimal)

RecordM2M passes the mark to market win/loss transfer amount to the asset/market tracker to be recorded.

func (*MarketActivityTracker) RecordNotionalTakerVolume added in v0.73.0

func (mat *MarketActivityTracker) RecordNotionalTakerVolume(marketID string, party string, volumeToAdd *num.Uint)

func (*MarketActivityTracker) RecordNotionalTraded added in v0.79.0

func (mat *MarketActivityTracker) RecordNotionalTraded(asset, marketID string, notional *num.Uint)

func (*MarketActivityTracker) RecordPosition added in v0.73.0

func (mat *MarketActivityTracker) RecordPosition(asset, party, market string, pos int64, price *num.Uint, positionFactor num.Decimal, time time.Time)

RecordPosition passes the position of the party in the asset/market to the market tracker to be recorded.

func (*MarketActivityTracker) RecordRealisedPosition added in v0.76.0

func (mat *MarketActivityTracker) RecordRealisedPosition(asset, party, market string, positionDecrease num.Decimal)

RecordRealisedPosition updates the market tracker on decreased position.

func (*MarketActivityTracker) RemoveAMMParty added in v0.77.0

func (mat *MarketActivityTracker) RemoveAMMParty(asset, marketID, ammParty string)

RemoveAMMParty removes amm party entries for AMM in given market.

func (*MarketActivityTracker) RemoveMarket

func (mat *MarketActivityTracker) RemoveMarket(asset, marketID string)

RemoveMarket is called when the market is removed from the network. It is not immediately removed to give a chance for rewards to be paid at the end of the epoch for activity during the epoch. Instead it is marked for removal and will be removed at the beginning of the next epoch.

func (*MarketActivityTracker) RestoreMarkPrice added in v0.78.0

func (mat *MarketActivityTracker) RestoreMarkPrice(asset, market string, markPrice *num.Uint)

RestoreMarkPrice is called when a market is loaded from a snapshot and will set the price of the notional to the mark price is none is set (for migration).

func (*MarketActivityTracker) RestorePosition added in v0.73.0

func (mat *MarketActivityTracker) RestorePosition(asset, party, market string, pos int64, price *num.Uint, positionFactor num.Decimal)

RestorePosition restores a position as if it were acquired at the beginning of the epoch. This is purely for migration from an old version.

func (*MarketActivityTracker) SetEligibilityChecker

func (mat *MarketActivityTracker) SetEligibilityChecker(eligibilityChecker EligibilityChecker)

func (*MarketActivityTracker) Stopped

func (mat *MarketActivityTracker) Stopped() bool

func (*MarketActivityTracker) TeamStatsForMarkets added in v0.74.0

func (mat *MarketActivityTracker) TeamStatsForMarkets(allMarketsForAssets, onlyTheseMarkets []string) map[string]map[string]*num.Uint

func (*MarketActivityTracker) UpdateFeesFromTransfers

func (mat *MarketActivityTracker) UpdateFeesFromTransfers(asset, market string, transfers []*types.Transfer)

UpdateFeesFromTransfers takes a slice of transfers and if they represent fees it updates the market fee tracker. market is guaranteed to exist in the mapping as it is added when proposed.

func (*MarketActivityTracker) UpdateMarkPrice added in v0.78.0

func (mat *MarketActivityTracker) UpdateMarkPrice(asset, market string, markPrice *num.Uint)

UpdateMarkPrice is called for a futures market when the mark price is recalculated.

type MarketLiquidity

type MarketLiquidity struct {
	// contains filtered or unexported fields
}

func NewMarketLiquidity

func NewMarketLiquidity(
	log *logging.Logger,
	liquidityEngine LiquidityEngine,
	collateral Collateral,
	broker Broker,
	orderBook liquidity.OrderBook,
	equityShares EquityLikeShares,
	marketActivityTracker *MarketActivityTracker,
	fee *fee.Engine,
	marketType marketType,
	marketID string,
	asset string,
	priceFactor num.Decimal,
	priceRange num.Decimal,
	amm AMM,
) *MarketLiquidity

func NewMarketLiquidityFromSnapshot added in v0.76.0

func NewMarketLiquidityFromSnapshot(
	log *logging.Logger,
	liquidityEngine LiquidityEngine,
	collateral Collateral,
	broker Broker,
	orderBook liquidity.OrderBook,
	equityShares EquityLikeShares,
	marketActivityTracker *MarketActivityTracker,
	fee *fee.Engine,
	marketType marketType,
	marketID string,
	asset string,
	priceFactor num.Decimal,
	state *snapshot.MarketLiquidity,
	amm AMM,
) (*MarketLiquidity, error)

func (*MarketLiquidity) AllocateFees added in v0.73.0

func (m *MarketLiquidity) AllocateFees(ctx context.Context) error

AllocateFees distributes fee from a market fee account to LP fee accounts.

func (*MarketLiquidity) AmendLiquidityProvision

func (m *MarketLiquidity) AmendLiquidityProvision(
	ctx context.Context,
	lpa *types.LiquidityProvisionAmendment,
	party string,
	deterministicID string,
	marketState types.MarketState,
) error

AmendLiquidityProvision forwards a LiquidityProvisionAmendment to the Liquidity Engine.

func (*MarketLiquidity) CalculateSuppliedStake added in v0.73.0

func (m *MarketLiquidity) CalculateSuppliedStake() *num.Uint

func (*MarketLiquidity) CancelLiquidityProvision added in v0.73.0

func (m *MarketLiquidity) CancelLiquidityProvision(ctx context.Context, party string) error

CancelLiquidityProvision amends liquidity provision to 0.

func (*MarketLiquidity) EndBlock

func (m *MarketLiquidity) EndBlock(markPrice, midPrice *num.Uint, positionFactor num.Decimal)

func (*MarketLiquidity) GetAverageLiquidityScores added in v0.73.0

func (m *MarketLiquidity) GetAverageLiquidityScores() map[string]num.Decimal

func (*MarketLiquidity) GetState added in v0.76.0

func (m *MarketLiquidity) GetState() *snapshot.MarketLiquidity

func (*MarketLiquidity) IsProbabilityOfTradingInitialised added in v0.73.0

func (m *MarketLiquidity) IsProbabilityOfTradingInitialised() bool

func (*MarketLiquidity) NewTransfer

func (m *MarketLiquidity) NewTransfer(partyID string, transferType types.TransferType, amount *num.Uint) *types.Transfer

func (*MarketLiquidity) OnBondPenaltyFactorUpdate added in v0.73.0

func (m *MarketLiquidity) OnBondPenaltyFactorUpdate(bondPenaltyFactor num.Decimal)

func (*MarketLiquidity) OnEarlyExitPenalty

func (m *MarketLiquidity) OnEarlyExitPenalty(earlyExitPenalty num.Decimal)

func (*MarketLiquidity) OnEpochEnd

func (m *MarketLiquidity) OnEpochEnd(ctx context.Context, t time.Time, epoch types.Epoch)

func (*MarketLiquidity) OnEpochStart

func (m *MarketLiquidity) OnEpochStart(
	ctx context.Context, now time.Time,
	markPrice, midPrice, targetStake *num.Uint,
	positionFactor num.Decimal,
)

func (*MarketLiquidity) OnMarketClosed added in v0.73.0

func (m *MarketLiquidity) OnMarketClosed(ctx context.Context, t time.Time)

func (*MarketLiquidity) OnMaximumLiquidityFeeFactorLevelUpdate added in v0.73.0

func (m *MarketLiquidity) OnMaximumLiquidityFeeFactorLevelUpdate(liquidityFeeFactorLevelUpdate num.Decimal)

func (*MarketLiquidity) OnMinLPStakeQuantumMultiple

func (m *MarketLiquidity) OnMinLPStakeQuantumMultiple(minLPStakeQuantumMultiple num.Decimal)

func (*MarketLiquidity) OnMinProbabilityOfTradingLPOrdersUpdate added in v0.73.0

func (m *MarketLiquidity) OnMinProbabilityOfTradingLPOrdersUpdate(v num.Decimal)

func (*MarketLiquidity) OnNonPerformanceBondPenaltyMaxUpdate added in v0.73.0

func (m *MarketLiquidity) OnNonPerformanceBondPenaltyMaxUpdate(nonPerformanceBondPenaltyMax num.Decimal)

func (*MarketLiquidity) OnNonPerformanceBondPenaltySlopeUpdate added in v0.73.0

func (m *MarketLiquidity) OnNonPerformanceBondPenaltySlopeUpdate(nonPerformanceBondPenaltySlope num.Decimal)

func (*MarketLiquidity) OnProbabilityOfTradingTauScalingUpdate added in v0.73.0

func (m *MarketLiquidity) OnProbabilityOfTradingTauScalingUpdate(v num.Decimal)

func (*MarketLiquidity) OnProvidersFeeCalculationTimeStep added in v0.73.0

func (m *MarketLiquidity) OnProvidersFeeCalculationTimeStep(d time.Duration)

func (*MarketLiquidity) OnStakeToCcyVolumeUpdate added in v0.73.0

func (m *MarketLiquidity) OnStakeToCcyVolumeUpdate(stakeToCcyVolume num.Decimal)

func (*MarketLiquidity) OnTick

func (m *MarketLiquidity) OnTick(ctx context.Context, t time.Time)

func (*MarketLiquidity) ProvisionsPerParty added in v0.73.0

func (m *MarketLiquidity) ProvisionsPerParty() liquidity.ProvisionsPerParty

func (*MarketLiquidity) SetAMM added in v0.77.0

func (m *MarketLiquidity) SetAMM(a AMM)

func (*MarketLiquidity) SetELSFeeFraction added in v0.77.0

func (m *MarketLiquidity) SetELSFeeFraction(d num.Decimal)

func (*MarketLiquidity) SetState added in v0.77.0

func (m *MarketLiquidity) SetState(ml *snapshot.MarketLiquidity) error

func (*MarketLiquidity) StopAllLiquidityProvision added in v0.73.0

func (m *MarketLiquidity) StopAllLiquidityProvision(ctx context.Context)

func (*MarketLiquidity) SubmitLiquidityProvision

func (m *MarketLiquidity) SubmitLiquidityProvision(
	ctx context.Context,
	sub *types.LiquidityProvisionSubmission,
	party string,
	deterministicID string,
	marketState types.MarketState,
) (err error)

SubmitLiquidityProvision forwards a LiquidityProvisionSubmission to the Liquidity Engine.

func (*MarketLiquidity) UpdateMarketConfig added in v0.73.0

func (m *MarketLiquidity) UpdateMarketConfig(risk liquidity.RiskModel, monitor liquidity.PriceMonitor)

func (*MarketLiquidity) UpdateSLAParameters added in v0.73.0

func (m *MarketLiquidity) UpdateSLAParameters(slaParams *types.LiquiditySLAParams)

func (*MarketLiquidity) ValidOrdersPriceRange added in v0.74.0

func (m *MarketLiquidity) ValidOrdersPriceRange() (*num.Uint, *num.Uint, error)

ValidOrdersPriceRange returns min and max valid prices range for LP orders.

type MarketLiquidityEngine added in v0.73.0

type MarketLiquidityEngine interface {
	OnEpochStart(context.Context, time.Time, *num.Uint, *num.Uint, *num.Uint, num.Decimal)
	OnEpochEnd(context.Context, time.Time, types.Epoch)
	OnTick(context.Context, time.Time)
	EndBlock(*num.Uint, *num.Uint, num.Decimal)
	SubmitLiquidityProvision(context.Context, *types.LiquidityProvisionSubmission, string, string, types.MarketState) error
	AmendLiquidityProvision(context.Context, *types.LiquidityProvisionAmendment, string, string, types.MarketState) error
	CancelLiquidityProvision(context.Context, string) error
	UpdateMarketConfig(liquidity.RiskModel, liquidity.PriceMonitor)
	UpdateSLAParameters(*types.LiquiditySLAParams)
	OnEarlyExitPenalty(num.Decimal)
	OnMinLPStakeQuantumMultiple(num.Decimal)
	OnBondPenaltyFactorUpdate(num.Decimal)
	OnNonPerformanceBondPenaltySlopeUpdate(num.Decimal)
	OnNonPerformanceBondPenaltyMaxUpdate(num.Decimal)
	OnMinProbabilityOfTradingLPOrdersUpdate(num.Decimal)
	OnProbabilityOfTradingTauScalingUpdate(num.Decimal)
	OnMaximumLiquidityFeeFactorLevelUpdate(num.Decimal)
	OnStakeToCcyVolumeUpdate(stakeToCcyVolume num.Decimal)
	OnProvidersFeeCalculationTimeStep(d time.Duration)
	StopAllLiquidityProvision(context.Context)
	IsProbabilityOfTradingInitialised() bool
	GetAverageLiquidityScores() map[string]num.Decimal
	ProvisionsPerParty() liquidity.ProvisionsPerParty
	OnMarketClosed(context.Context, time.Time)
	CalculateSuppliedStake() *num.Uint
	SetELSFeeFraction(d num.Decimal)
}

type OracleEngine

type OracleEngine interface {
	ListensToSigners(dscommon.Data) bool
	Subscribe(context.Context, spec.Spec, spec.OnMatchedData) (spec.SubscriptionID, spec.Unsubscriber, error)
	Unsubscribe(context.Context, spec.SubscriptionID)
}

OracleEngine ...

type OrderReferenceCheck added in v0.73.0

type OrderReferenceCheck types.Order

func (OrderReferenceCheck) HasMoved added in v0.73.0

func (o OrderReferenceCheck) HasMoved(changes uint8) bool

type Parties added in v0.77.0

type Parties interface {
	AssignDeriveKey(ctx context.Context, party types.PartyID, derivedKey string)
}

type PeggedOrders

type PeggedOrders struct {
	// contains filtered or unexported fields
}

func NewPeggedOrders

func NewPeggedOrders(log *logging.Logger, ts TimeService) *PeggedOrders

func NewPeggedOrdersFromSnapshot

func NewPeggedOrdersFromSnapshot(
	log *logging.Logger,
	ts TimeService,
	state *types.PeggedOrdersState,
) *PeggedOrders

func (*PeggedOrders) AmendParked

func (p *PeggedOrders) AmendParked(amended *types.Order)

func (*PeggedOrders) Changed

func (p *PeggedOrders) Changed() bool

func (*PeggedOrders) EnterAuction

func (p *PeggedOrders) EnterAuction(ctx context.Context) []events.Event

func (*PeggedOrders) GetAllParkedForParty

func (p *PeggedOrders) GetAllParkedForParty(party string) (orders []*types.Order)

func (*PeggedOrders) GetParkedByID

func (p *PeggedOrders) GetParkedByID(id string) *types.Order

func (*PeggedOrders) GetParkedIDs

func (p *PeggedOrders) GetParkedIDs() []string

func (*PeggedOrders) GetParkedOrdersCount

func (p *PeggedOrders) GetParkedOrdersCount() int

func (*PeggedOrders) GetState

func (p *PeggedOrders) GetState() *types.PeggedOrdersState

func (*PeggedOrders) IsParked

func (p *PeggedOrders) IsParked(id string) bool

func (*PeggedOrders) Park

func (p *PeggedOrders) Park(o *types.Order)

func (*PeggedOrders) Parked

func (p *PeggedOrders) Parked() []*types.Order

func (*PeggedOrders) RemoveAllForParty

func (p *PeggedOrders) RemoveAllForParty(
	ctx context.Context, party string, status types.OrderStatus,
) (orders []*types.Order, evts []events.Event)

func (*PeggedOrders) Settled

func (p *PeggedOrders) Settled() []*types.Order

func (*PeggedOrders) Unpark

func (p *PeggedOrders) Unpark(oid string)

type PriceMonitor

type PriceMonitor interface {
	OnTimeUpdate(now time.Time)
	CheckPrice(ctx context.Context, as price.AuctionState, price *num.Uint, persistent bool, recordInHistory bool) bool
	ResetPriceHistory(price *num.Uint)
	GetCurrentBounds() []*types.PriceMonitoringBounds
	GetBounds() []*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, price.AuctionState)
}

PriceMonitor interface to handle price monitoring/auction triggers @TODO the interface shouldn't be imported here.

type QuantumGetter added in v0.77.8

type QuantumGetter interface {
	GetAssetQuantum(asset string) (num.Decimal, error)
	GetAllParties() []string
}

type StateVarEngine

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 Teams added in v0.73.0

type Teams interface {
	GetTeamMembers(team string, minEpochsInTeam uint64) []string
	GetAllPartiesInTeams(minEpochsInTeam uint64) []string
	GetAllTeamsWithParties(minEpochsInTeam uint64) map[string][]string
}

type TimeService

type TimeService interface {
	GetTimeNow() time.Time
}

TimeService ...

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package mocks_amm is a generated GoMock package.
Package mocks_amm is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL