model

package
v0.0.0-...-a287f25 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2021 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MatchOK                         = "match.ok"
	MatchInternalErrorID            = "match.error.InternalError"
	MatchGasNotEnoughErrorID        = "match.error.GasNotEnough"
	MatchCloseOnlyErrorID           = "match.error.CloseOnly"
	MatchInsufficientBalanceErrorID = "match.error.InsufficientBalance"
	MatchMaxOrderNumReachID         = "match.error.MaxOrderNumReach"
)
View Source
const (
	MASK_CLOSE_ONLY                    = 0x80000000
	MASK_MARKET_ORDER                  = 0x40000000
	MASK_STOP_LOSS_ORDER               = 0x20000000
	MASK_TAKE_PROFIT_ORDER             = 0x10000000
	MASK_USE_TARGET_LEVERAGE           = 0x08000000
	LimitOrder               OrderType = 1
	StopLimitOrder           OrderType = 2
	TakeProfitOrder          OrderType = 3
)
View Source
const PerpetualNormal = 2
View Source
const QueryParamSeperator = ","

Variables

This section is empty.

Functions

func CancelOrder

func CancelOrder(order *Order, reason CancelReasonType, amount decimal.Decimal) error

func MustString

func MustString(s *string) string

func MustUint64

func MustUint64(n *uint64) uint64

func String

func String(s string) *string

func Uint64

func Uint64(n uint64) *uint64

Types

type AMMTradingContext

type AMMTradingContext struct {
	// current trading perpetual
	Index                 decimal.Decimal
	Position1             decimal.Decimal
	HalfSpread            decimal.Decimal
	OpenSlippageFactor    decimal.Decimal
	CloseSlippageFactor   decimal.Decimal
	FundingRateLimit      decimal.Decimal
	MaxClosePriceDiscount decimal.Decimal // δ_m
	MaxLeverage           decimal.Decimal

	// other perpetuals
	OtherIndex              []decimal.Decimal
	OtherPosition           []decimal.Decimal
	OtherOpenSlippageFactor []decimal.Decimal
	OtherMaxLeverage        []decimal.Decimal

	// total
	Cash       decimal.Decimal
	PoolMargin decimal.Decimal

	// trading result
	DeltaMargin     decimal.Decimal
	DeltaPosition   decimal.Decimal
	BestAskBidPrice decimal.Decimal

	// eager evaluation
	ValueWithoutCurrent          decimal.Decimal
	SquareValueWithoutCurrent    decimal.Decimal
	PositionMarginWithoutCurrent decimal.Decimal
}

type AccountComputed

type AccountComputed struct {
	PositionValue        decimal.Decimal
	PositionMargin       decimal.Decimal
	MaintenanceMargin    decimal.Decimal
	AvailableCashBalance decimal.Decimal
	MarginBalance        decimal.Decimal
	AvailableMargin      decimal.Decimal
	WithdrawableBalance  decimal.Decimal
	IsMMSafe             bool // use this if check liquidation
	IsIMSafe             bool // use this if open positions
	IsMarginSafe         bool // use this if close positions. also known as bankrupt
	Leverage             decimal.Decimal
}

type AccountStorage

type AccountStorage struct {
	TargetLeverage decimal.Decimal
	WalletBalance  decimal.Decimal
	CashBalance    decimal.Decimal
	PositionAmount decimal.Decimal
}

type BlockHeader

type BlockHeader struct {
	BlockNumber int64
	BlockHash   string
	ParentHash  string
	BlockTime   time.Time
}

type CancelReasonType

type CancelReasonType string
const (
	CancelReasonExpired           CancelReasonType = "EXPIRED"
	CancelReasonCloseOnly         CancelReasonType = "CANCELED_BY_CLOSE_ONLY"
	CancelReasonUserCancel        CancelReasonType = "CANCELED_BY_USER"
	CancelReasonTransactionFail   CancelReasonType = "TRANSACTION_FAIL"
	CancelReasonRemainTooSmall    CancelReasonType = "REMAIN_TOO_SMALL"
	CancelReasonInsufficientFunds CancelReasonType = "INSUFFICIENT_FUNDS"
	CancelReasonGasNotEnough      CancelReasonType = "GAS_NOT_ENOUGH"
	CancelReasonContractSettled   CancelReasonType = "CONTRACT_SETTLED"
)

type KVStore

type KVStore struct {
	Key        string `gorm:"primary_key"`
	Category   string `gorm:"primary_key"`
	Value      []byte
	UpdateTime time.Time
}

type LaunchTransaction

type LaunchTransaction struct {
	ID              uint64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT;NOT NULL"`
	TxID            string `gorm:"index"`
	FromAddress     string
	ToAddress       string
	Type            TransactionType
	Inputs          []byte
	BlockNumber     *uint64
	BlockHash       *string
	BlockTime       *uint64
	TransactionHash *string
	Nonce           *uint64
	GasPrice        *uint64
	GasLimit        *uint64
	GasUsed         *uint64
	Status          LaunchTransactionStatus
	Value           decimal.Decimal
	CommitTime      time.Time
	UpdateTime      time.Time
}

func (LaunchTransaction) TableName

func (LaunchTransaction) TableName() string

type LaunchTransactionStatus

type LaunchTransactionStatus int
const (
	TxInitial  LaunchTransactionStatus = 0
	TxPending  LaunchTransactionStatus = 1
	TxSuccess  LaunchTransactionStatus = 2
	TxFailed   LaunchTransactionStatus = 3
	TxCanceled LaunchTransactionStatus = 4
)

func (LaunchTransactionStatus) String

func (ts LaunchTransactionStatus) String() string

func (LaunchTransactionStatus) TransactionStatus

func (ts LaunchTransactionStatus) TransactionStatus() TransactionStatus

type LiquidityPoolStorage

type LiquidityPoolStorage struct {
	VaultFeeRate    decimal.Decimal
	PoolCashBalance decimal.Decimal

	Perpetuals map[int64]*PerpetualStorage
}

type MatchItem

type MatchItem struct {
	OrderHash string          `json:"orderHash"`
	Order     *Order          `json:"-"`
	Amount    decimal.Decimal `json:"amount"`
}

type MatchResult

type MatchResult struct {
	MatchItems  []*MatchItem `json:"matchItems"`
	SuccItems   []*MatchItem `json:"succItems"`
	FailedItems []*MatchItem `json:"failedItems"`
}

type MatchTransaction

type MatchTransaction struct {
	ID                   string            `json:"id" db:"id" primaryKey:"true" gorm:"primary_key"`
	LiquidityPoolAddress string            `json:"liquidityPoolAddress" db:"liquidity_pool_address"`
	PerpetualIndex       int64             `json:"perpetualIndex" db:"perpetual_index"`
	BrokerAddress        string            `json:"brokerAddress" db:"broker_address"`
	MatchJson            string            `json:"-" db:"match_json"`
	Status               TransactionStatus `json:"status" db:"status"`
	BlockConfirmed       bool              `json:"blockConfirmed" db:"block_confirmed"`
	BlockNumber          null.Int          `json:"blockNumber" db:"block_number"`
	BlockHash            null.String       `json:"blockHash" db:"block_hash"`
	TransactionHash      null.String       `json:"transactionHash" db:"transaction_hash"`
	CreatedAt            time.Time         `json:"createdAt" db:"created_at"`
	ExecutedAt           null.Time         `json:"executedAt" db:"executed_at"`
	MatchResult          MatchResult       `json:"matchResult" sql:"-"`
}

func (MatchTransaction) TableName

func (MatchTransaction) TableName() string

type Order

type Order struct {
	OrderParam
	ID                int64                `json:"-" db:"id" primaryKey:"true" gorm:"primary_key"`
	OrderHash         string               `json:"orderHash" db:"order_hash"`
	OldStatus         OrderStatus          `json:"oldStatus" sql:"-"`
	Status            OrderStatus          `json:"status" db:"status"`
	CollateralAddress string               `json:"collateralAddress" db:"collateral_address"`
	AvailableAmount   decimal.Decimal      `json:"availableAmount" db:"available_amount"`
	ConfirmedAmount   decimal.Decimal      `json:"confirmedAmount" db:"confirmed_amount"`
	CanceledAmount    decimal.Decimal      `json:"canceledAmount" db:"canceled_amount"`
	PendingAmount     decimal.Decimal      `json:"pendingAmount" db:"pending_amount"`
	GasFeeLimit       int64                `json:"gasFeeLimit" db:"gas_fee_limit"`
	CreatedAt         time.Time            `json:"createdAt" db:"created_at"`
	UpdatedAt         time.Time            `json:"updatedAt" db:"updated_at"`
	CheckAmount       decimal.Decimal      `json:"-" sql:"-"`
	CancelReasons     []*OrderCancelReason `json:"cancelReasons" sql:"-"`
}

type OrderCancel

type OrderCancel struct {
	OrderHash string
	Status    OrderStatus
	ToCancel  decimal.Decimal
}

type OrderCancelReason

type OrderCancelReason struct {
	Reason          CancelReasonType `json:"reason"`
	Amount          decimal.Decimal  `json:"amount"`
	CanceledAt      time.Time        `json:"canceledAt"`
	TransactionHash string           `json:"transactionHash,omitempty"`
}

OrderCancelReason records of cancel

type OrderParam

type OrderParam struct {
	TraderAddress        string          `json:"traderAddress" db:"trader_address"`
	LiquidityPoolAddress string          `json:"liquidityPoolAddress" db:"liquidity_pool_address"`
	PerpetualIndex       int64           `json:"perpetualIndex" db:"perpetual_index"`
	RelayerAddress       string          `json:"relayerAddress" db:"relayer_address"`
	BrokerAddress        string          `json:"brokerAddress" db:"broker_address"`
	ReferrerAddress      string          `json:"referrerAddress" db:"referrer_address"`
	Type                 OrderType       `json:"type" db:"type"`
	Price                decimal.Decimal `json:"price" db:"price"`
	Amount               decimal.Decimal `json:"amount" db:"amount"`
	MinTradeAmount       decimal.Decimal `json:"minTradeAmount" db:"min_trade_amount"`
	TriggerPrice         decimal.Decimal `json:"triggerPrice" db:"trigger_price"`
	BrokerFeeLimit       int64           `json:"brokerFeeLimit" db:"broker_fee_limit"`
	ExpiresAt            time.Time       `json:"expiresAt" db:"expires_at"`
	Salt                 int64           `json:"-" db:"salt"`
	IsCloseOnly          bool            `json:"isCloseOnly" db:"is_close_only"`
	ChainID              int64           `json:"-" db:"chain_id"`
	Signature            string          `json:"-" db:"signature"`
}

type OrderSignature

type OrderSignature struct {
	R        string `json:"r"`
	S        string `json:"s"`
	V        string `json:"v"`
	SignType string `json:"signType"`
}

type OrderStatus

type OrderStatus string
const (
	OrderCanceled      OrderStatus = "canceled"
	OrderPending       OrderStatus = "pending"
	OrderPartialFilled OrderStatus = "partial_filled"
	OrderFullFilled    OrderStatus = "full_filled"
)

type OrderType

type OrderType int

type Perpetual

type Perpetual struct {
	LiquidityPoolAddress string `json:"liquidityPoolAddress" db:"liquidity_pool_address"`
	PerpetualIndex       int64  `json:"perpetualIndex"  db:"perpetual_index"`
	Symbol               string `json:"symbol"  db:"symbol"`
	OperatorAddress      string `json:"operatorAddress"  db:"operator_address"`
	CollateralSymbol     string `json:"collateralSymbol" db:"collateral_symbol"`
	CollateralAddress    string `json:"collateralAddress" db:"collateral_address"`
	CollateralDecimals   int32  `json:"collateralDecimals" db:"collateral_decimals"`
	IsPublished          bool   `json:"isPublished"       db:"is_published"`
	BlockNumber          int64  `json:"-" db:"block_number"`
}

type PerpetualStorage

type PerpetualStorage struct {
	IsNormal bool

	MarkPrice               decimal.Decimal
	IndexPrice              decimal.Decimal
	UnitAccumulativeFunding decimal.Decimal

	InitialMarginRate      decimal.Decimal
	MaintenanceMarginRate  decimal.Decimal
	OperatorFeeRate        decimal.Decimal
	LpFeeRate              decimal.Decimal
	ReferrerRebateRate     decimal.Decimal
	LiquidationPenaltyRate decimal.Decimal
	KeeperGasReward        decimal.Decimal
	InsuranceFundRate      decimal.Decimal
	OpenInterest           decimal.Decimal
	MaxOpenInterestRate    decimal.Decimal // openInterest <= poolMargin * maxOpenInterestRate / indexPrice

	HalfSpread            decimal.Decimal // α
	OpenSlippageFactor    decimal.Decimal // β1
	CloseSlippageFactor   decimal.Decimal // β2
	FundingRateFactor     decimal.Decimal // γ
	FundingRateLimit      decimal.Decimal // Γ
	MaxLeverage           decimal.Decimal // λ
	MaxClosePriceDiscount decimal.Decimal // δ

	AmmCashBalance    decimal.Decimal
	AmmPositionAmount decimal.Decimal
}

type Receipt

type Receipt struct {
	BlockNumber uint64
	BlockHash   string
	GasUsed     uint64
	Status      LaunchTransactionStatus
	BlockTime   uint64
	Logs        []*ethtypes.Log
}

type TradeFailedEvent

type TradeFailedEvent struct {
	PerpetualAddress string
	BlockNumber      int64
	TransactionSeq   int
	TransactionHash  string
	TraderAddress    string
	OrderHash        string
	Amount           decimal.Decimal
	Reason           string
}

type TradeSuccessEvent

type TradeSuccessEvent struct {
	PerpetualAddress string
	BlockNumber      int64
	TransactionSeq   int
	TransactionHash  string
	TraderAddress    string
	OrderHash        string
	Amount           decimal.Decimal
	Gas              decimal.Decimal
}

type TransactionStatus

type TransactionStatus string
const (
	//TransactionStatusInit Transaction is initialized
	TransactionStatusInit TransactionStatus = "INIT"

	//TransactionStatusPending Transaction is signed by wallet, the transaction hash is created
	TransactionStatusPending TransactionStatus = "PENDING"

	//TransactionStatusSuccess Transaction succeeded on block chain
	TransactionStatusSuccess TransactionStatus = "SUCCESS"

	//TransactionStatusFail Transaction failed on block chain
	TransactionStatusFail TransactionStatus = "FAIL"

	//TransactionStatusAbort Transaction is abort due to system error
	TransactionStatusAbort TransactionStatus = "ABORT"
)

type TransactionType

type TransactionType int
const (
	TxNormal      TransactionType = 0
	TxCancel      TransactionType = 1
	TxAccelerated TransactionType = 2
)

Jump to

Keyboard shortcuts

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