amm

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: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	V1 = "AMMv1"
)

Variables

View Source
var (
	ErrNoPoolMatchingParty  = errors.New("no pool matching party")
	ErrPartyAlreadyOwnAPool = func(market string) error {
		return fmt.Errorf("party already own a pool for market %v", market)
	}
	ErrCommitmentTooLow          = errors.New("commitment amount too low")
	ErrRebaseOrderDidNotTrade    = errors.New("rebase-order did not trade")
	ErrRebaseTargetOutsideBounds = errors.New("rebase target outside bounds")
)

Functions

func AverageEntryPrice

func AverageEntryPrice(sqrter *Sqrter, lu num.Decimal, pu *num.Uint) num.Decimal

Pa = Lu * sqrt(pu) * (1 - (Lu / (Lu + sqrt(pu)))).

func DeriveAMMParty

func DeriveAMMParty(
	party, market, version string,
	index uint64,
) string

func LiquidationPrice

func LiquidationPrice(b, lc, pB, pb, fl, mr num.Decimal) num.Decimal

Pliq = (b - lc - Pb * pb) / (|Pb| * (fl + mr) - Pb).

func LiquidityUnit

func LiquidityUnit(sqrter *Sqrter, pu, pl *num.Uint) num.Decimal

Lu = (sqrt(pu) * sqrt(pl)) / (sqrt(pu) - sqrt(pl)).

func LossOnCommitment

func LossOnCommitment(pa, pb, pB num.Decimal) num.Decimal

lc = |(pa - pb) * pB|.

func NewCurveFromProto

func NewCurveFromProto(c *snapshotpb.PoolMapEntry_Curve) (*curve, error)

func NewPoolCache added in v0.79.0

func NewPoolCache() *poolCache

func PositionAtLowerBound

func PositionAtLowerBound(rf, b, pl, pa, positionFactor num.Decimal) num.Decimal

Pvl = rf * b / (pl * (1 - rf) + rf * pa).

func PositionAtUpperBound

func PositionAtUpperBound(rf, b, pl, pa, positionFactor num.Decimal) num.Decimal

Pvl = -rf * b / (pl * (1 + rf) - rf * pa).

func RiskFactor

func RiskFactor(lb, fs, fl, fi num.Decimal) num.Decimal

Rf = min(Lb, 1 / (Fs + Fl) * Fi).

Types

type Broker

type Broker interface {
	Send(events.Event)
}

type Collateral

type Collateral interface {
	GetAssetQuantum(asset string) (num.Decimal, error)
	GetAllParties() []string
	GetPartyMarginAccount(market, party, asset string) (*types.Account, error)
	GetPartyGeneralAccount(party, asset string) (*types.Account, error)
	SubAccountUpdate(
		ctx context.Context,
		party, subAccount, asset, market string,
		transferType types.TransferType,
		amount *num.Uint,
	) (*types.LedgerMovement, error)
	SubAccountClosed(ctx context.Context, party, subAccount, asset, market string) ([]*types.LedgerMovement, error)
	SubAccountRelease(
		ctx context.Context,
		party, subAccount, asset, market string, mevt 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 Engine

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

func New

func New(
	log *logging.Logger,
	broker Broker,
	collateral Collateral,
	marketID string,
	assetID string,
	position Position,
	priceFactor num.Decimal,
	positionFactor num.Decimal,
	marketActivityTracker *common.MarketActivityTracker,
	parties common.Parties,
	allowedEmptyAMMLevels uint64,
) *Engine

func NewFromProto

func NewFromProto(
	log *logging.Logger,
	broker Broker,
	collateral Collateral,
	marketID string,
	assetID string,
	position Position,
	state *v1.AmmState,
	priceFactor num.Decimal,
	positionFactor num.Decimal,
	marketActivityTracker *common.MarketActivityTracker,
	parties common.Parties,
	allowedEmptyAMMLevels uint64,
) (*Engine, error)

func (*Engine) Amend

func (e *Engine) Amend(
	ctx context.Context,
	amend *types.AmendAMM,
	riskFactors *types.RiskFactor,
	scalingFactors *types.ScalingFactors,
	slippage num.Decimal,
) (*Pool, *Pool, error)

Amend takes the details of an amendment to an AMM and returns a copy of that pool with the updated curves along with the current pool. The changes are not taken place in the AMM engine until Confirm is called on the updated pool.

func (*Engine) BestPricesAndVolumes

func (e *Engine) BestPricesAndVolumes() (*num.Uint, uint64, *num.Uint, uint64)

BestPricesAndVolumes returns the best bid/ask and their volumes across all the registered AMM's.

func (*Engine) CancelAMM

func (e *Engine) CancelAMM(
	ctx context.Context,
	cancel *types.CancelAMM,
) (events.Margin, error)

func (*Engine) Confirm

func (e *Engine) Confirm(
	ctx context.Context,
	pool *Pool,
)

Confirm takes an AMM that was created earlier and now commits it to the engine as a functioning pool.

func (*Engine) Create

func (e *Engine) Create(
	ctx context.Context,
	submit *types.SubmitAMM,
	deterministicID string,
	riskFactors *types.RiskFactor,
	scalingFactors *types.ScalingFactors,
	slippage num.Decimal,
) (*Pool, error)

Create takes the definition of an AMM and returns it. It is not considered a participating AMM until Confirm as been called with it.

func (*Engine) GetAMMParty

func (e *Engine) GetAMMParty(party string) (string, error)

GetAMMParty returns the AMM's key given the owners key.

func (*Engine) GetAMMPoolsBySubAccount

func (e *Engine) GetAMMPoolsBySubAccount() map[string]common.AMMPool

func (*Engine) GetAllSubAccounts

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

func (*Engine) GetDataSourcedAMMs added in v0.79.0

func (e *Engine) GetDataSourcedAMMs(dataSourceID string) []*Pool

GetDataSourcedAMMs returns any AMM's whose base price is determined by the given data source ID.

func (*Engine) GetVolumeAtPrice

func (e *Engine) GetVolumeAtPrice(price *num.Uint, side types.Side) uint64

GetVolumeAtPrice returns the volumes across all registered AMM's that will uncross with with an order at the given price. Calling this function with price 1000 and side == sell will return the buy orders that will uncross.

func (*Engine) IntoProto

func (e *Engine) IntoProto() *v1.AmmState

func (*Engine) IsAMMPartyID

func (e *Engine) IsAMMPartyID(key string) bool

IsAMMPartyID returns whether the given key is the key of AMM registered with the engine.

func (*Engine) MarketClosing

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

MarketClosing stops all AMM's and returns subaccount balances back to the owning party.

func (*Engine) NotifyFinished

func (e *Engine) NotifyFinished()

NotifyFinished is called when the matching engine has finished matching an order and is returning it to the market for processing.

func (*Engine) OnMTM

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

OnMTM is called whenever core does an MTM and is a signal that any pool's that are closing and have 0 position can be fully removed.

func (*Engine) OnMaxCalculationLevelsUpdate

func (e *Engine) OnMaxCalculationLevelsUpdate(ctx context.Context, c *num.Uint)

func (*Engine) OnMinCommitmentQuantumUpdate

func (e *Engine) OnMinCommitmentQuantumUpdate(ctx context.Context, c *num.Uint)

func (*Engine) OnTick

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

func (*Engine) OrderbookShape

func (e *Engine) OrderbookShape(st, nd *num.Uint, ammParty *string) []*types.OrderbookShapeResult

OrderbookShape expands all registered AMM's into orders between the given prices. If `ammParty` is supplied then just the pool with that party id is expanded.

func (*Engine) RemoveDistressed

func (e *Engine) RemoveDistressed(ctx context.Context, closed []events.MarketPosition)

RemoveDistressed checks if any of the closed out parties are AMM's and if so the AMM is stopped and removed.

func (*Engine) StopPool

func (e *Engine) StopPool(
	ctx context.Context,
	key string,
) error

func (*Engine) SubmitOrder

func (e *Engine) SubmitOrder(agg *types.Order, inner, outer *num.Uint) []*types.Order

SubmitOrder takes an aggressive order and generates matching orders with the registered AMMs such that volume is only taken in the interval (inner, outer) where inner and outer are price-levels on the orderbook. For example if agg is a buy order inner < outer, and if its a sell outer < inner.

func (*Engine) UpdateAllowedEmptyLevels added in v0.79.0

func (e *Engine) UpdateAllowedEmptyLevels(allowedEmptyLevels uint64)

func (*Engine) UpdateSubAccountBalance

func (e *Engine) UpdateSubAccountBalance(
	ctx context.Context,
	party, subAccount string,
	newCommitment *num.Uint,
) (*num.Uint, error)

type EstimatedBounds

type EstimatedBounds struct {
	PositionSizeAtLower     num.Decimal
	LossOnCommitmentAtLower num.Decimal
	LiquidationPriceAtLower num.Decimal
	TooWideLower            bool

	PositionSizeAtUpper     num.Decimal
	LossOnCommitmentAtUpper num.Decimal
	LiquidationPriceAtUpper num.Decimal
	TooWideUpper            bool
}

func EstimateBounds

func EstimateBounds(
	sqrter *Sqrter,
	lowerPrice, basePrice, upperPrice *num.Uint,
	leverageLower, leverageUpper num.Decimal,
	balance *num.Uint,
	linearSlippageFactor, initialMargin,
	riskFactorShort, riskFactorLong,
	priceFactor, positionFactor num.Decimal,
	allowedMaxEmptyLevels uint64,
) EstimatedBounds

type Pool

type Pool struct {
	ID          string
	AMMParty    string
	Commitment  *num.Uint
	ProposedFee num.Decimal
	Parameters  *types.ConcentratedLiquidityParameters

	SlippageTolerance         num.Decimal
	MinimumPriceChangeTrigger num.Decimal
	// contains filtered or unexported fields
}

func NewPool

func NewPool(
	log *logging.Logger,
	id,
	ammParty,
	asset string,
	submit *types.SubmitAMM,
	sqrt sqrtFn,
	collateral Collateral,
	position Position,
	rf *types.RiskFactor,
	sf *types.ScalingFactors,
	linearSlippage num.Decimal,
	priceFactor num.Decimal,
	positionFactor num.Decimal,
	maxCalculationLevels *num.Uint,
	allowedEmptyAMMLevels uint64,
	slippageTolerance num.Decimal,
	minimumPriceChangeTrigger num.Decimal,
) (*Pool, error)

func NewPoolFromProto

func NewPoolFromProto(
	log *logging.Logger,
	sqrt sqrtFn,
	collateral Collateral,
	position Position,
	state *snapshotpb.PoolMapEntry_Pool,
	party string,
	priceFactor num.Decimal,
	positionFactor num.Decimal,
) (*Pool, error)

func (*Pool) BestPrice

func (p *Pool) BestPrice(side types.Side) (*num.Uint, bool)

BestPrice returns the AMM's quote price on the given side. If the AMM's position is fully at a boundary then there is no quote price on that side and false is returned.

func (*Pool) BestPriceAndVolume added in v0.79.0

func (p *Pool) BestPriceAndVolume(side types.Side) (*num.Uint, uint64)

BestPriceAndVolume returns the AMM's best price on a given side and the volume available to trade.

func (*Pool) CommitmentAmount

func (p *Pool) CommitmentAmount() *num.Uint

func (*Pool) FairPrice added in v0.79.0

func (p *Pool) FairPrice() *num.Uint

sqrt(pf) = sqrt(pu) / (1 + pv * sqrt(pu) * 1/L ) where pv is the virtual-position pv = pos, when the pool is long pv = pos + Pv, when pool is short

this transformation is needed since for each curve its virtual position is 0 at the lower bound which maps to the Vega position when the pool is long, but when the pool is short Vega position == 0 at the upper bounds and -ve at the lower.

func (*Pool) IntoProto

func (p *Pool) IntoProto() *snapshotpb.PoolMapEntry_Pool

func (*Pool) IsPending added in v0.79.0

func (p *Pool) IsPending() bool

func (*Pool) LiquidityFee

func (p *Pool) LiquidityFee() num.Decimal

func (*Pool) OrderbookShape

func (p *Pool) OrderbookShape(from, to *num.Uint, idgen *idgeneration.IDGenerator) *types.OrderbookShapeResult

func (*Pool) Owner

func (p *Pool) Owner() string

func (*Pool) PriceForVolume

func (p *Pool) PriceForVolume(volume uint64, side types.Side) *num.Uint

PriceForVolume returns the price the AMM is willing to trade at to match with the given volume of an incoming order.

func (*Pool) TradableVolumeForPrice added in v0.78.2

func (p *Pool) TradableVolumeForPrice(side types.Side, price *num.Uint) uint64

TrableVolumeForPrice returns the volume available between the AMM's fair-price and the given price and side of an incoming order. It is a special case of TradableVolumeInRange with the benefit of accurately using the AMM's position instead of having to calculate the hop from fair-price -> position.

func (*Pool) TradableVolumeInRange

func (p *Pool) TradableVolumeInRange(side types.Side, price1 *num.Uint, price2 *num.Uint) uint64

TradableVolumeInRange returns the volume the pool is willing to provide between the two given price levels for side of a given order that is trading with the pool. If `nil` is provided for either price then we take the full volume in that direction.

func (*Pool) Update

func (p *Pool) Update(
	amend *types.AmendAMM,
	rf *types.RiskFactor,
	sf *types.ScalingFactors,
	linearSlippage num.Decimal,
	allowedEmptyAMMLevels uint64,
) (*Pool, error)

Update returns a copy of the give pool but with its curves and parameters update as specified by `amend`.

type Position

type Position interface {
	GetPositionsByParty(ids ...string) []events.MarketPosition
}

type Sqrter

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

Sqrter calculates sqrt's of Uints and caches the results. We want this cache to be shared across all pools for a market.

func NewSqrter

func NewSqrter() *Sqrter

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