risk

package
v0.77.6 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2024 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const RiskFactorStateVarName = "risk-factors"

Variables

View Source
var (
	ErrInsufficientFundsForInitialMargin          = errors.New("insufficient funds for initial margin")
	ErrInsufficientFundsForMaintenanceMargin      = errors.New("insufficient funds for maintenance margin")
	ErrInsufficientFundsForOrderMargin            = errors.New("insufficient funds for order margin")
	ErrInsufficientFundsForMarginInGeneralAccount = errors.New("insufficient funds to cover margin in general margin")
	ErrRiskFactorsNotAvailableForAsset            = errors.New("risk factors not available for the specified asset")
	ErrInsufficientFundsToCoverTradeFees          = errors.New("insufficient funds to cover fees")
)
View Source
var (
	// ErrNilRiskModel ...
	ErrNilRiskModel = errors.New("nil risk model")
	// ErrUnimplementedRiskModel ...
	ErrUnimplementedRiskModel = errors.New("unimplemented risk model")
)

Functions

func CalcOrderMarginIsolatedMode added in v0.74.0

func CalcOrderMarginIsolatedMode(positionSize int64, buyOrders, sellOrders []*OrderInfo, positionFactor, marginFactor, auctionPrice num.Decimal) num.Decimal

CalcOrderMarginIsolatedMode calculates the the order margin required for the party in isolated margin mode given their current orders and margin factor.

func CalcOrderMargins added in v0.75.7

func CalcOrderMargins(positionSize int64, orders []*types.Order, positionFactor, marginFactor num.Decimal, auctionPrice *num.Uint) *num.Uint

CalcOrderMargins calculates the the order margin required for the party given their current orders and margin factor.

func CalculateLiquidationPriceWithSlippageFactors added in v0.71.0

func CalculateLiquidationPriceWithSlippageFactors(sizePosition int64, buyOrders, sellOrders []*OrderInfo, currentPrice, collateralAvailable num.Decimal, positionFactor, linearSlippageFactor, quadraticSlippageFactor, riskFactorLong, riskFactorShort, fundingPaymentPerUnitPosition num.Decimal, isolatedMarginMode bool, marginFactor num.Decimal) (liquidationPriceForOpenVolume, liquidationPriceWithBuyOrders, liquidationPriceWithSellOrders num.Decimal, err error)

func CalculateMaintenanceMarginWithSlippageFactors added in v0.71.0

func CalculateMaintenanceMarginWithSlippageFactors(sizePosition int64, buyOrders, sellOrders []*OrderInfo, marketObservable, positionFactor, linearSlippageFactor, quadraticSlippageFactor, riskFactorLong, riskFactorShort, fundingPaymntPerUnitPosition num.Decimal, auction bool, auctionPrice num.Decimal) num.Decimal

func CalculateRequiredMarginInIsolatedMode added in v0.74.0

func CalculateRequiredMarginInIsolatedMode(sizePosition int64, averageEntryPrice, marketObservable num.Decimal, buyOrders, sellOrders []*OrderInfo, positionFactor, marginFactor num.Decimal, auctionPrice *num.Uint) (num.Decimal, num.Decimal)

Types

type AuctionState

type AuctionState interface {
	InAuction() bool
	CanLeave() bool
}

AuctionState represents the current auction state of the market, previously we got this information from the matching engine, but really... that's not its job.

type Broker

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

Broker the event bus broker.

type Config

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

	StreamMarginLevelsVerbose encoding.Bool `long:"log-margin-update"`
}

Config represent the configuration of the Risk engine.

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 Engine

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

Engine is the risk engine.

func NewEngine

func NewEngine(log *logging.Logger,
	config Config,
	marginCalculator *types.MarginCalculator,
	model Model,
	ob Orderbook,
	as AuctionState,
	timeSvc TimeService,
	broker Broker,
	mktID string,
	asset string,
	stateVarEngine StateVarEngine,
	positionFactor num.Decimal,
	riskFactorsInitialised bool,
	initialisedRiskFactors *types.RiskFactor,
	linearSlippageFactor num.Decimal,
	quadraticSlippageFactor num.Decimal,
) *Engine

NewEngine instantiate a new risk engine.

func (*Engine) CalcOrderMarginsForClosedOutParty added in v0.74.0

func (e *Engine) CalcOrderMarginsForClosedOutParty(orders []*types.Order, marginFactor num.Decimal) *num.Uint

func (*Engine) CalculateRiskFactorsForTest

func (e *Engine) CalculateRiskFactorsForTest()

CalculateRiskFactorsForTest is a hack for testing for setting directly the risk factors for a market.

func (*Engine) CheckMarginInvariants added in v0.74.0

func (e *Engine) CheckMarginInvariants(ctx context.Context, evt events.Margin, marketObservable *num.Uint, increment num.Decimal, orders []*types.Order, marginFactor num.Decimal) (events.Risk, error)

func (*Engine) ExpectMargins

func (e *Engine) ExpectMargins(evts []events.Margin, markPrice *num.Uint, increment num.Decimal, auctionPrice *num.Uint) (okMargins []events.Margin, distressedPositions []events.Margin)

ExpectMargins is used in the case some parties are in a distressed positions in this situation we will only check if the party margin is > to the maintenance margin.

func (*Engine) FlushMarginLevelsEvents added in v0.68.0

func (e *Engine) FlushMarginLevelsEvents()

func (*Engine) GetRiskFactors

func (e *Engine) GetRiskFactors() *types.RiskFactor

GetRiskFactors returns risk factors per specified asset.

func (*Engine) GetScalingFactors added in v0.77.0

func (e *Engine) GetScalingFactors() *types.ScalingFactors

func (*Engine) GetSlippage added in v0.77.0

func (e *Engine) GetSlippage() num.Decimal

func (*Engine) IsRiskFactorInitialised

func (e *Engine) IsRiskFactorInitialised() bool

func (*Engine) OnMarginScalingFactorsUpdate

func (e *Engine) OnMarginScalingFactorsUpdate(sf *types.ScalingFactors) error

func (*Engine) ReleaseExcessMarginAfterAuctionUncrossing added in v0.74.0

func (e *Engine) ReleaseExcessMarginAfterAuctionUncrossing(ctx context.Context, m events.Margin, marketObservable *num.Uint, increment num.Decimal, marginFactor num.Decimal, orders []*types.Order) events.Risk

ReleaseExcessMarginAfterAuctionUncrossing is called after auction uncrossing to release excess order margin due to orders placed during an auction when the price used for order margin is the auction price rather than the order price.

func (*Engine) ReloadConf

func (e *Engine) ReloadConf(cfg Config)

ReloadConf update the internal configuration of the risk engine.

func (*Engine) SwitchFromIsolatedMargin added in v0.74.0

func (e *Engine) SwitchFromIsolatedMargin(ctx context.Context, evt events.Margin, marketObservable *num.Uint, inc num.Decimal, auctionPrice *num.Uint) events.Risk

SwitchFromIsolatedMargin switches the party from isolated margin mode to cross margin mode. This includes: 1. recalcualtion of the required margin in cross margin mode + margin levels are buffered 2. return a transfer of all the balance from order margin account to margin account NB: cannot fail.

func (*Engine) SwitchToIsolatedMargin added in v0.74.0

func (e *Engine) SwitchToIsolatedMargin(ctx context.Context, evt events.Margin, marketObservable *num.Uint, inc num.Decimal, orders []*types.Order, marginFactor num.Decimal, auctionPrice *num.Uint) ([]events.Risk, error)

SwitchToIsolatedMargin attempts to switch the party from cross margin mode to isolated mode. Error can be returned if it is not possible for the party to switch at this moment. If successful the new margin levels are buffered and the required margin level, margin balances, and transfers (aka events.risk) is returned.

func (*Engine) UpdateIsolatedMarginOnAggressor added in v0.74.0

func (e *Engine) UpdateIsolatedMarginOnAggressor(ctx context.Context, evt events.Margin, marketObservable *num.Uint, increment num.Decimal, orders []*types.Order, trades []*types.Trade, marginFactor num.Decimal, traderSide types.Side, isAmend bool, fees *num.Uint) ([]events.Risk, error)

UpdateIsolatedMarginOnAggressor is called when a new order comes in and is matched immediately. NB: evt has the position after the trades + orders need to include the new order with the updated remaining. returns an error if the new margin is invalid or if the margin account cannot be topped up from general account. if successful it updates the margin level and returns the transfer that is needed for the topup of the margin account or release from the margin account excess.

func (*Engine) UpdateIsolatedMarginOnOrder added in v0.74.0

func (e *Engine) UpdateIsolatedMarginOnOrder(ctx context.Context, evt events.Margin, orders []*types.Order, marketObservable *num.Uint, auctionPrice *num.Uint, increment num.Decimal, marginFactor num.Decimal) (events.Risk, error)

UpdateIsolatedMarginOnOrder checks that the party has sufficient cover for the given orders including the new one. It returns an error if the party doesn't have sufficient cover and the necessary transfers otherwise. NB: auctionPrice should be nil in continuous mode.

func (*Engine) UpdateIsolatedMarginOnOrderCancel added in v0.75.0

func (e *Engine) UpdateIsolatedMarginOnOrderCancel(ctx context.Context, evt events.Margin, orders []*types.Order, marketObservable *num.Uint, auctionPrice *num.Uint, increment num.Decimal, marginFactor num.Decimal) (events.Risk, error)

func (*Engine) UpdateIsolatedMarginsOnPositionChange added in v0.74.0

func (e *Engine) UpdateIsolatedMarginsOnPositionChange(ctx context.Context, evt events.Margin, marketObservable *num.Uint, increment num.Decimal, orders []*types.Order, trades []*types.Trade, traderSide types.Side, marginFactor num.Decimal) ([]events.Risk, error)

UpdateIsolatedMarginOnPositionChanged is called upon changes to the position of a party in isolated margin mode. Depending on the nature of the change it checks if it needs to move funds into our out of the margin account from the order margin account or to the general account. At this point we don't enforce any invariants just calculate transfers.

func (*Engine) UpdateMarginAuction

func (e *Engine) UpdateMarginAuction(ctx context.Context, evts []events.Margin, price *num.Uint, increment num.Decimal, auctionPrice *num.Uint) ([]events.Risk, []events.Margin)

func (*Engine) UpdateMarginOnNewOrder

func (e *Engine) UpdateMarginOnNewOrder(ctx context.Context, evt events.Margin, markPrice *num.Uint, increment num.Decimal, auctionPrice *num.Uint) (events.Risk, events.Margin, error)

UpdateMarginOnNewOrder calculate the new margin requirement for a single order this is intended to be used when a new order is created in order to ensure the party margin account is at least at the InitialMargin level before the order is added to the book.

func (*Engine) UpdateMarginsOnSettlement

func (e *Engine) UpdateMarginsOnSettlement(ctx context.Context, evts []events.Margin, markPrice *num.Uint, increment num.Decimal, auctionPrice *num.Uint) []events.Risk

UpdateMarginsOnSettlement ensure the margin requirement over all positions. margins updates are based on the following requirement

---------------------------------------------------------------------------------------

| 1 | SearchLevel < CurMargin < InitialMargin | nothing to do / no risk for the network | | 2 | CurMargin < SearchLevel | set margin to InitialLevel | | 3 | CurMargin > ReleaseLevel | release up to the InitialLevel |

---------------------------------------------------------------------------------------

In the case where the CurMargin is smaller to the MaintenanceLevel after trying to move monies later, we'll need to close out the party but that cannot be figured out now only in later when we try to move monies from the general account.

func (*Engine) UpdateModel

func (e *Engine) UpdateModel(
	stateVarEngine StateVarEngine,
	calculator *types.MarginCalculator,
	model Model,
	linearSlippageFactor num.Decimal,
	quadraticSlippageFactor num.Decimal,
)

type FactorConverter added in v0.55.0

type FactorConverter struct{}

func (FactorConverter) BundleToInterface added in v0.55.0

func (FactorConverter) InterfaceToBundle added in v0.55.0

type Model

type Model interface {
	CalculateRiskFactors() *types.RiskFactor
	DefaultRiskFactors() *types.RiskFactor
	PriceRange(price, yearFraction, probability num.Decimal) (minPrice, maxPrice num.Decimal)
	ProbabilityOfTrading(currentP, orderP, minP, maxP, yFrac num.Decimal, isBid, applyMinMax bool) num.Decimal
	GetProjectionHorizon() num.Decimal
}

Model represents a risk model interface.

func NewModel

func NewModel(prm interface{}, asset string) (Model, error)

NewModel instantiate a new risk model from a market framework configuration.

type OrderInfo added in v0.71.0

type OrderInfo struct {
	TrueRemaining uint64
	Price         num.Decimal
	IsMarketOrder bool
}

func (*OrderInfo) Clone added in v0.77.0

func (o *OrderInfo) Clone() *OrderInfo

Clone - Not really necessary, just added to avoid future pointers copy if some were added.

type Orderbook

type Orderbook interface {
	GetIndicativePrice() *num.Uint
}

Orderbook represent an abstraction over the orderbook.

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
	NewEvent(asset, market string, eventType statevar.EventType)
}

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.

Jump to

Keyboard shortcuts

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