amm

package
v0.77.4 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2024 License: AGPL-3.0 Imports: 17 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 PositionAtLowerBound

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

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

func PositionAtUpperBound

func PositionAtUpperBound(rf, b, pl, pa 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)
	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,
) *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,
) (*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) 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.Order, []*types.Order)

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

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

type EstimatedBounds

type EstimatedBounds struct {
	PositionSizeAtUpper     num.Decimal
	PositionSizeAtLower     num.Decimal
	LossOnCommitmentAtUpper num.Decimal
	LossOnCommitmentAtLower num.Decimal
	LiquidationPriceAtUpper num.Decimal
	LiquidationPriceAtLower num.Decimal
}

func EstimateBounds

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

type Pool

type Pool struct {
	ID          string
	AMMParty    string
	Commitment  *num.Uint
	ProposedFee num.Decimal
	Parameters  *types.ConcentratedLiquidityParameters
	// 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,
) (*Pool, error)

func NewPoolFromProto

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

func (*Pool) BestPrice

func (p *Pool) BestPrice(order *types.Order) *num.Uint

BestPrice returns the price that the pool is willing to trade for the given order side.

func (*Pool) CommitmentAmount

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

func (*Pool) IntoProto

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

func (*Pool) LiquidityFee

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

func (*Pool) OrderbookShape

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

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) 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,
) (*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