execution

package
v0.0.0-...-f6bc33c Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2023 License: MIT Imports: 37 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 InitialOrderVersion = 1

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

Variables

View Source
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")
)
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")
)
View Source
var ErrBondSlashing = errors.New("bond slashing")

ErrBondSlashing - just indicates that we had to penalize the party due to insufficient funds, and as such, we have to cancel their LP.

View Source
var ErrCommitmentAmountTooLow = errors.New("commitment amount is too low")
View Source
var (
	ErrSnapshotKeyDoesNotExist = errors.New("unknown key for market activity tracker snapshot")
)

Functions

This section is empty.

Types

type Assets

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

type AuctionState

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
}

AuctionState ...

type Broker

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

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

type Collateral

type Collateral interface {
	MarketCollateral
	AssetExists(string) bool
	CreateMarketAccounts(context.Context, string, string) (string, string, error)
}

type Config

type Config struct {
	Level encoding.LogLevel `long:"log-level"`

	Matching   matching.Config   `group:"Matching" namespace:"matching"`
	Risk       risk.Config       `group:"Risk" namespace:"risk"`
	Position   positions.Config  `group:"Position" namespace:"position"`
	Settlement settlement.Config `group:"Settlement" namespace:"settlement"`
	Fee        fee.Config        `group:"Fee" namespace:"fee"`
	Liquidity  liquidity.Config  `group:"Liquidity" namespace:"liquidity"`
}

Config is the configuration of the execution package.

func NewDefaultConfig

func NewDefaultConfig() Config

NewDefaultConfig creates an instance of the package specific configuration, given a pointer to a logger instance to be used for logging within the package.

type EligibilityChecker

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

type Engine

type Engine struct {
	Config
	// contains filtered or unexported fields
}

Engine is the execution engine.

func NewEngine

func NewEngine(
	log *logging.Logger,
	executionConfig Config,
	ts TimeService,
	collateral Collateral,
	oracle OracleEngine,
	broker Broker,
	stateVarEngine StateVarEngine,
	marketActivityTracker *MarketActivityTracker,
	assets Assets,
) *Engine

NewEngine takes stores and engines and returns a new execution engine to process new orders, etc.

func (*Engine) AmendLiquidityProvision

func (e *Engine) AmendLiquidityProvision(ctx context.Context, lpa *types.LiquidityProvisionAmendment, party string,
	deterministicID string,
) (returnedErr error)

func (*Engine) AmendOrder

func (e *Engine) AmendOrder(
	ctx context.Context,
	amendment *types.OrderAmendment,
	party string,
	idgen IDGenerator,
) (confirmation *types.OrderConfirmation, returnedErr error)

AmendOrder takes order amendment details and attempts to amend the order if it exists and is in a editable state.

func (*Engine) BlockEnd

func (e *Engine) BlockEnd(ctx context.Context)

func (*Engine) CancelLiquidityProvision

func (e *Engine) CancelLiquidityProvision(ctx context.Context, cancel *types.LiquidityProvisionCancellation, party string) (returnedErr error)

func (*Engine) CancelOrder

func (e *Engine) CancelOrder(
	ctx context.Context,
	cancel *types.OrderCancellation,
	party string,
	idgen IDGenerator,
) (_ []*types.OrderCancellationConfirmation, returnedErr error)

CancelOrder takes order details and attempts to cancel if it exists in matching engine, stores etc.

func (*Engine) GetAsset

func (e *Engine) GetAsset(assetID string) (types.Asset, bool)

func (*Engine) GetEquityLikeShareForMarketAndParty

func (e *Engine) GetEquityLikeShareForMarketAndParty(market, party string) (num.Decimal, bool)

GetEquityLikeShareForMarketAndParty return the equity-like shares of the given party in the given market. If the market doesn't exist, it returns false.

func (*Engine) GetMarket

func (e *Engine) GetMarket(market string) (types.Market, bool)

func (*Engine) GetMarketCounters

func (e *Engine) GetMarketCounters() map[string]*types.MarketCounters

GetMarketCounters returns the per-market counts used for gas estimation.

func (*Engine) GetMarketData

func (e *Engine) GetMarketData(mktID string) (types.MarketData, error)

func (*Engine) GetMarketState

func (e *Engine) GetMarketState(mktID string) (types.MarketState, error)

func (*Engine) GetState

func (e *Engine) GetState(_ string) ([]byte, []types.StateProvider, error)

func (*Engine) Hash

func (e *Engine) Hash() []byte

func (*Engine) IsEligibleForProposerBonus

func (e *Engine) IsEligibleForProposerBonus(marketID string, value *num.Uint) bool

IsEligibleForProposerBonus checks if the given value is greater than that market quantum * quantum_multiplier.

func (*Engine) Keys

func (e *Engine) Keys() []string

func (*Engine) LoadState

func (e *Engine) LoadState(ctx context.Context, payload *types.Payload) ([]types.StateProvider, error)

func (*Engine) MarketExists

func (e *Engine) MarketExists(market string) bool

func (*Engine) Namespace

func (e *Engine) Namespace() types.SnapshotNamespace

func (*Engine) OnMarkPriceUpdateMaximumFrequency

func (e *Engine) OnMarkPriceUpdateMaximumFrequency(ctx context.Context, d time.Duration) error

func (*Engine) OnMarketAuctionMinimumDurationUpdate

func (e *Engine) OnMarketAuctionMinimumDurationUpdate(ctx context.Context, d time.Duration) error

func (*Engine) OnMarketCreationQuantumMultipleUpdate

func (e *Engine) OnMarketCreationQuantumMultipleUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketFeeFactorsInfrastructureFeeUpdate

func (e *Engine) OnMarketFeeFactorsInfrastructureFeeUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketFeeFactorsMakerFeeUpdate

func (e *Engine) OnMarketFeeFactorsMakerFeeUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketLiquidityBondPenaltyUpdate

func (e *Engine) OnMarketLiquidityBondPenaltyUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate

func (e *Engine) OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate(
	_ context.Context, d num.Decimal,
) error

func (*Engine) OnMarketLiquidityProvidersFeeDistributionTimeStep

func (e *Engine) OnMarketLiquidityProvidersFeeDistributionTimeStep(_ context.Context, d time.Duration) error

func (*Engine) OnMarketLiquidityProvisionShapesMaxSizeUpdate

func (e *Engine) OnMarketLiquidityProvisionShapesMaxSizeUpdate(
	_ context.Context, v int64,
) error

func (*Engine) OnMarketMarginScalingFactorsUpdate

func (e *Engine) OnMarketMarginScalingFactorsUpdate(ctx context.Context, v interface{}) error

func (*Engine) OnMarketMinProbabilityOfTradingForLPOrdersUpdate

func (e *Engine) OnMarketMinProbabilityOfTradingForLPOrdersUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketProbabilityOfTradingTauScalingUpdate

func (e *Engine) OnMarketProbabilityOfTradingTauScalingUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnMarketValueWindowLengthUpdate

func (e *Engine) OnMarketValueWindowLengthUpdate(_ context.Context, d time.Duration) error

func (*Engine) OnMaxPeggedOrderUpdate

func (e *Engine) OnMaxPeggedOrderUpdate(ctx context.Context, max *num.Uint) error

func (*Engine) OnMinLpStakeQuantumMultipleUpdate

func (e *Engine) OnMinLpStakeQuantumMultipleUpdate(ctx context.Context, d num.Decimal) error

func (*Engine) OnStateLoaded

func (e *Engine) OnStateLoaded(ctx context.Context) error

func (*Engine) OnSuppliedStakeToObligationFactorUpdate

func (e *Engine) OnSuppliedStakeToObligationFactorUpdate(_ context.Context, d num.Decimal) error

func (*Engine) OnTick

func (e *Engine) OnTick(ctx context.Context, t time.Time)

func (*Engine) RejectMarket

func (e *Engine) RejectMarket(ctx context.Context, marketID string) error

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 (*Engine) ReloadConf

func (e *Engine) ReloadConf(cfg Config)

ReloadConf updates the internal configuration of the execution engine and its dependencies.

func (*Engine) RestoreMarket

func (e *Engine) RestoreMarket(ctx context.Context, marketConfig *types.Market) error

RestoreMarket restores a new market from proposal checkpoint.

func (*Engine) StartOpeningAuction

func (e *Engine) StartOpeningAuction(ctx context.Context, marketID string) error

StartOpeningAuction will start the opening auction of the given market. This will work only if the market is currently in a PROPOSED state.

func (*Engine) Stopped

func (e *Engine) Stopped() bool

func (*Engine) SubmitLiquidityProvision

func (e *Engine) SubmitLiquidityProvision(
	ctx context.Context,
	sub *types.LiquidityProvisionSubmission,
	party, deterministicID string,
) (returnedErr error)

func (*Engine) SubmitMarket

func (e *Engine) SubmitMarket(ctx context.Context, marketConfig *types.Market, proposer string) error

SubmitMarket submits a new market configuration to the network.

func (*Engine) SubmitOrder

func (e *Engine) SubmitOrder(
	ctx context.Context,
	submission *types.OrderSubmission,
	party string,
	idgen IDGenerator,
	orderID string,
) (confirmation *types.OrderConfirmation, returnedErr error)

SubmitOrder checks the incoming order and submits it to a Zeta market.

func (*Engine) UpdateMarket

func (e *Engine) UpdateMarket(ctx context.Context, marketConfig *types.Market) error

UpdateMarket will update an existing market configuration.

type EpochEngine

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

type EquityShares

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

EquityShares module controls the Equity sharing algorithm described on the spec: https://github.com/zetaprotocol/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) GetState

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

func (*EquityShares) GetTotalVStake

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

func (*EquityShares) OpeningAuctionEnded

func (es *EquityShares) OpeningAuctionEnded()

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

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(v *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/zetaprotocol/product/blob/master/specs/0042-setting-fees-and-rewarding-lps.md

func (*FeeSplitter) SetCurrentTime

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

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.

type IDGenerator

type IDGenerator interface {
	NextID() string
}

type 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)
}

LiquidityMonitor.

type Market

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

Market represents an instance of a market in zeta and is in charge of calling the engines in order to process all transactions.

func NewMarket

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)

NewMarket creates a new market using the market framework configuration and creates underlying engines.

func NewMarketFromSnapshot

func NewMarketFromSnapshot(
	ctx context.Context,
	log *logging.Logger,
	em *types.ExecMarket,
	riskConfig risk.Config,
	positionConfig positions.Config,
	settlementConfig settlement.Config,
	matchingConfig matching.Config,
	feeConfig fee.Config,
	liquidityConfig liquidity.Config,
	collateralEngine MarketCollateral,
	oracleEngine products.OracleEngine,
	timeService TimeService,
	broker Broker,
	stateVarEngine StateVarEngine,
	assetDetails *assets.Asset,
	marketActivityTracker *MarketActivityTracker,
	peggedOrderNotify func(int64),
) (*Market, error)

func (*Market) AmendLiquidityProvision

func (m *Market) AmendLiquidityProvision(ctx context.Context, lpa *types.LiquidityProvisionAmendment, party string, deterministicID string) (err error)

AmendLiquidityProvision forwards a LiquidityProvisionAmendment to the Liquidity Engine.

func (*Market) AmendOrder

func (m *Market) AmendOrder(
	ctx context.Context,
	orderAmendment *types.OrderAmendment,
	party string,
	deterministicID string,
) (oc *types.OrderConfirmation, _ error,
)

AmendOrder amend an existing order from the order book.

func (*Market) AmendOrderWithIDGenerator

func (m *Market) AmendOrderWithIDGenerator(
	ctx context.Context,
	orderAmendment *types.OrderAmendment,
	party string,
	idgen IDGenerator,
) (oc *types.OrderConfirmation, _ error,
)

func (*Market) BlockEnd

func (m *Market) BlockEnd(ctx context.Context)

BlockEnd notifies the market of the end of the block.

func (*Market) BondPenaltyFactorUpdate

func (m *Market) BondPenaltyFactorUpdate(ctx context.Context, d num.Decimal)

func (*Market) CanLeaveOpeningAuction

func (m *Market) CanLeaveOpeningAuction() bool

CanLeaveOpeningAuction checks if the market can leave the opening auction based on whether floating point consensus has been reached on all 3 vars.

func (*Market) CancelAllOrders

func (m *Market) CancelAllOrders(ctx context.Context, partyID string) ([]*types.OrderCancellationConfirmation, error)

func (*Market) CancelLiquidityProvision

func (m *Market) CancelLiquidityProvision(ctx context.Context, cancel *types.LiquidityProvisionCancellation, party string) (err error)

CancelLiquidityProvision forwards a LiquidityProvisionCancel to the Liquidity Engine.

func (*Market) CancelOrder

func (m *Market) CancelOrder(
	ctx context.Context,
	partyID, orderID string, deterministicID string,
) (oc *types.OrderCancellationConfirmation, _ error)

func (*Market) CancelOrderWithIDGenerator

func (m *Market) CancelOrderWithIDGenerator(
	ctx context.Context,
	partyID, orderID string,
	idgen IDGenerator,
) (oc *types.OrderCancellationConfirmation, _ error)

func (*Market) GetID

func (m *Market) GetID() string

GetID returns the id of the given market.

func (*Market) GetMarketData

func (m *Market) GetMarketData() types.MarketData

func (*Market) GetMarketState

func (m *Market) GetMarketState() types.MarketState

func (*Market) GetTotalLPShapeCount

func (m *Market) GetTotalLPShapeCount() uint64

GetTotalLPShapeCount returns the total number of LP shapes.

func (*Market) GetTotalOpenPositionCount

func (m *Market) GetTotalOpenPositionCount() uint64

GetTotalOpenPositionCount returns the total number of open positions.

func (*Market) GetTotalOrderBookLevelCount

func (m *Market) GetTotalOrderBookLevelCount() uint64

GetTotalOrderBookLevelCount returns the total number of levels in the order book.

func (*Market) GetTotalPeggedOrderCount

func (m *Market) GetTotalPeggedOrderCount() uint64

GetTotalPeggedOrderCount returns the total number of pegged orders.

func (*Market) Hash

func (m *Market) Hash() []byte

func (*Market) IntoType

func (m *Market) IntoType() types.Market

func (*Market) OnAuctionEnded

func (m *Market) OnAuctionEnded()

OnAuctionEnded is called whenever an auction is ended and emits an event to the state var engine.

func (*Market) OnFeeFactorsInfrastructureFeeUpdate

func (m *Market) OnFeeFactorsInfrastructureFeeUpdate(ctx context.Context, d num.Decimal) error

func (*Market) OnFeeFactorsMakerFeeUpdate

func (m *Market) OnFeeFactorsMakerFeeUpdate(ctx context.Context, d num.Decimal) error

func (*Market) OnMarginScalingFactorsUpdate

func (m *Market) OnMarginScalingFactorsUpdate(ctx context.Context, sf *types.ScalingFactors) error

func (*Market) OnMarkPriceUpdateMaximumFrequency

func (m *Market) OnMarkPriceUpdateMaximumFrequency(ctx context.Context, d time.Duration)

func (*Market) OnMarketAuctionMinimumDurationUpdate

func (m *Market) OnMarketAuctionMinimumDurationUpdate(ctx context.Context, d time.Duration)

func (*Market) OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate

func (m *Market) OnMarketLiquidityMaximumLiquidityFeeFactorLevelUpdate(d num.Decimal)

func (*Market) OnMarketLiquidityProvidersFeeDistribitionTimeStep

func (m *Market) OnMarketLiquidityProvidersFeeDistribitionTimeStep(d time.Duration)

func (*Market) OnMarketLiquidityProvisionShapesMaxSizeUpdate

func (m *Market) OnMarketLiquidityProvisionShapesMaxSizeUpdate(v int64) error

func (*Market) OnMarketLiquidityTargetStakeTriggeringRatio

func (m *Market) OnMarketLiquidityTargetStakeTriggeringRatio(ctx context.Context, d num.Decimal)

func (*Market) OnMarketMinLpStakeQuantumMultipleUpdate

func (m *Market) OnMarketMinLpStakeQuantumMultipleUpdate(_ context.Context, d num.Decimal)

func (*Market) OnMarketMinProbabilityOfTradingLPOrdersUpdate

func (m *Market) OnMarketMinProbabilityOfTradingLPOrdersUpdate(_ context.Context, d num.Decimal)

func (*Market) OnMarketProbabilityOfTradingTauScalingUpdate

func (m *Market) OnMarketProbabilityOfTradingTauScalingUpdate(_ context.Context, d num.Decimal)

func (*Market) OnMarketTargetStakeScalingFactorUpdate

func (m *Market) OnMarketTargetStakeScalingFactorUpdate(d num.Decimal) error

func (*Market) OnMarketTargetStakeTimeWindowUpdate

func (m *Market) OnMarketTargetStakeTimeWindowUpdate(d time.Duration)

func (*Market) OnMarketValueWindowLengthUpdate

func (m *Market) OnMarketValueWindowLengthUpdate(d time.Duration)

func (*Market) OnOpeningAuctionFirstUncrossingPrice

func (m *Market) OnOpeningAuctionFirstUncrossingPrice()

OnOpeningAuctionFirstUncrossingPrice is triggered when the opening auction sees an uncrossing price for the first time and emits an event to the state variable engine.

func (*Market) OnSuppliedStakeToObligationFactorUpdate

func (m *Market) OnSuppliedStakeToObligationFactorUpdate(d num.Decimal)

func (*Market) OnTick

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

OnTick notifies the market of a new time event/update. todo: make this a more generic function name e.g. OnTimeUpdateEvent

func (*Market) PostRestore

func (m *Market) PostRestore(ctx context.Context) error

func (*Market) Reject

func (m *Market) Reject(ctx context.Context) error

func (*Market) ReloadConf

func (m *Market) ReloadConf(
	matchingConfig matching.Config,
	riskConfig risk.Config,
	positionConfig positions.Config,
	settlementConfig settlement.Config,
	feeConfig fee.Config,
)

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 (*Market) StartOpeningAuction

func (m *Market) StartOpeningAuction(ctx context.Context) error

func (*Market) SubmitLiquidityProvision

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

SubmitLiquidityProvision forwards a LiquidityProvisionSubmission to the Liquidity Engine.

func (*Market) SubmitOrder

func (m *Market) SubmitOrder(
	ctx context.Context,
	orderSubmission *types.OrderSubmission,
	party string,
	deterministicID string,
) (oc *types.OrderConfirmation, _ error)

SubmitOrder submits the given order.

func (*Market) SubmitOrderWithIDGeneratorAndOrderID

func (m *Market) SubmitOrderWithIDGeneratorAndOrderID(
	ctx context.Context,
	orderSubmission *types.OrderSubmission,
	party string,
	idgen IDGenerator,
	orderID string,
) (oc *types.OrderConfirmation, _ error)

SubmitOrder submits the given order.

func (*Market) Update

func (m *Market) Update(ctx context.Context, config *types.Market, oracleEngine products.OracleEngine) error

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, epochEngine EpochEngine) *MarketActivityTracker

NewFeesTracker instantiates the fees tracker.

func (*MarketActivityTracker) AddValueTraded

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

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

func (*MarketActivityTracker) Checkpoint

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

func (*MarketActivityTracker) GetAllMarketIDs

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

GetAllMarketIDs returns all the current market IDs.

func (*MarketActivityTracker) GetFeePartyScores

func (mat *MarketActivityTracker) GetFeePartyScores(market string, feeType types.TransferType) []*types.PartyContibutionScore

GetFeePartyScores returns the fraction each of the participants paid/received in the given fee of the market in the relevant period.

func (*MarketActivityTracker) GetMarketScores

func (mat *MarketActivityTracker) GetMarketScores(asset string, markets []string, dispatchMetric zeta.DispatchMetric) []*types.MarketContributionScore

GetMarketScores calculates the aggregate share of the asset/market in contribution to the metric out of either all the markets of the asset or the subset specified.

func (*MarketActivityTracker) GetMarketsWithEligibleProposer

func (mat *MarketActivityTracker) GetMarketsWithEligibleProposer(asset string, markets []string, payoutAsset string, funder 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) 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(market string, 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(ctx context.Context, data []byte) error

func (*MarketActivityTracker) LoadState

func (*MarketActivityTracker) MarkPaidProposer

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

MarkProposerPaid 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) Name

func (*MarketActivityTracker) Namespace

func (*MarketActivityTracker) RemoveMarket

func (mat *MarketActivityTracker) RemoveMarket(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) SetEligibilityChecker

func (mat *MarketActivityTracker) SetEligibilityChecker(eligibilityChecker EligibilityChecker)

func (*MarketActivityTracker) Stopped

func (mat *MarketActivityTracker) Stopped() bool

func (*MarketActivityTracker) UpdateFeesFromTransfers

func (mat *MarketActivityTracker) UpdateFeesFromTransfers(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.

type MarketCollateral

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)
	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) ([]*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)
}

type OracleEngine

OracleEngine ...

type OrderReferenceCheck

type OrderReferenceCheck types.Order

func (OrderReferenceCheck) HasMoved

func (o OrderReferenceCheck) HasMoved(changes uint8) bool

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) 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, 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)
}

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

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 TargetStakeCalculator

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)
}

TargetStakeCalculator interface.

type TimeService

type TimeService interface {
	GetTimeNow() time.Time
}

Directories

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

Jump to

Keyboard shortcuts

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