perps

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2025 License: Apache-2.0, MIT Imports: 24 Imported by: 0

README

Perps

Perps is a package that tries to abstract the interfaces of Perp DEXes, rn only in Cosmos.

Useful Info && Queries

dYdX
curl -s -X GET https://indexer.dydx.trade/v4/addresses/dydx1ha2hjlce7sqp59g8xhxz2jds97x8fdw9mrf4j3/subaccountNumber/0 | jq .
curl -s -X GET "https://indexer.dydx.trade/v4/fills?address=dydx1ha2hjlce7sqp59g8xhxz2jds97x8fdw9mrf4j3&subaccountNumber=0" | jq .
curl -s -X GET https://indexer.dydx.trade/v4/orderbooks/perpetualMarket/ATOM-USD | jq .
curl -s -X GET https://indexer.dydx.trade/v4/candles/perpetualMarkets/ATOM-USD?resolution=1MIN | jq .

Documentation

Index

Constants

View Source
const (
	DydxChainID        = "dydx-mainnet-1"
	DefaultOrderExpiry = 60   // seconds
	DefaultSlippage    = 0.01 // 1% - eventually we should use the best bid/ask or make market orders idk

)
View Source
const (
	MarsMaintenanceMarginRatio = 0.105 // 9.5x leverage equivalent
)

Variables

This section is empty.

Functions

func ProcessCandlesResponse

func ProcessCandlesResponse(
	response *IndexerCandleResponse,
) (*sdkmath.LegacyDec, error)

ProcessCandlesResponse converts indexer response data into a Position

func ProcessMarsPerpEvent

func ProcessMarsPerpEvent(events []abcitypes.Event) (currentPrice string, entryPrice string, err error)

Types

type DydxConfig

type DydxConfig struct {
	Market           string
	MarketID         uint32
	SubticksPerTick  uint64
	StepBaseQuantums uint64
	MinEquity        sdkmath.Int

	SignerAccount string
	Executor      string
	SubaccountID  uint32
	Denom         string

	BaseChainID string

	SubaccountClient subaccounts.QueryClient
	ClientRegistry   *connection.ClientRegistry
	MsgHandler       ibc.MessageHandler
	IndexerURL       string

	QuantumConversionExp int64
	AtomicResolution     int64
	Decimals             int64
}

type DydxProvider

type DydxProvider struct {
	BaseChainID string
	// contains filtered or unexported fields
}

DydxProvider implements the Provider interface for Dydx Protocol

func NewDydxProvider

func NewDydxProvider(

	logger *zap.Logger,

	marketID uint32,
	market string,
	subticksPerTick uint64,
	stepBaseQuantums uint64,
	quantumConversionExponent int64,
	atomicResolution int64,
	decimals int64,
	minEquity sdkmath.Int,

	signerAccount string,
	executor string,
	subaccountID uint32,
	denom string,

	baseChainID string,

	subaccountClient subaccounts.QueryClient,
	clientRegistry *connection.ClientRegistry,
	msgHandler ibc.MessageHandler,
	indexerURL string,
) *DydxProvider

NewDydxProvider creates a new Dydx provider

func (*DydxProvider) AdjustMargin

func (m *DydxProvider) AdjustMargin(_ context.Context, _ sdkmath.Int, _ bool) (*ExecutionResult, error)

func (*DydxProvider) CheckSubaccount

func (m *DydxProvider) CheckSubaccount(_ string) (bool, error)

CheckSubaccount implements Provider

func (*DydxProvider) ClosePosition

func (m *DydxProvider) ClosePosition(_ context.Context, _ bool) (*ExecutionResult, error)

func (*DydxProvider) CreateLimitOrder

func (m *DydxProvider) CreateLimitOrder(_ context.Context, price, _, size sdkmath.Int, isBuy, reduceOnly bool) ([]sdk.Msg, error)

CreateLimitOrder implements Provider

func (*DydxProvider) CreateMarketOrder

func (m *DydxProvider) CreateMarketOrder(ctx context.Context, price, _, size sdkmath.Int, isBuy, reduceOnly bool) ([]sdk.Msg, error)

CreateMarketOrder implements Provider

func (*DydxProvider) CreateSubaccount

func (m *DydxProvider) CreateSubaccount(_ string) (sdk.Msg, error)

CreateSubaccount implements Provider

func (*DydxProvider) DepositSubaccount

func (m *DydxProvider) DepositSubaccount(_ context.Context, amount sdkmath.Int) ([]sdk.Msg, error)

DepositSubaccount implements Provider

func (*DydxProvider) GetAccountBalance

func (m *DydxProvider) GetAccountBalance() (sdk.Coins, error)

GetAccountBalance implements Provider

func (*DydxProvider) GetLiquidationPrice

func (m *DydxProvider) GetLiquidationPrice(equity, size, entryPrice, maintenanceMargin sdkmath.LegacyDec) sdkmath.LegacyDec

GetLiquidationPrice implements Provider

func (*DydxProvider) GetPosition

func (m *DydxProvider) GetPosition(ctx context.Context) (*Position, error)

GetPosition implements Provider

func (*DydxProvider) GetProviderChainID

func (m *DydxProvider) GetProviderChainID() string

GetProviderDenom implements Provider

func (*DydxProvider) GetProviderDenom

func (m *DydxProvider) GetProviderDenom() string

GetProviderDenom implements Provider

func (*DydxProvider) GetProviderExecutor

func (m *DydxProvider) GetProviderExecutor() string

GetProviderExecutor implements Provider

func (*DydxProvider) GetProviderName

func (m *DydxProvider) GetProviderName() string

GetProviderName implements Provider

func (*DydxProvider) GetSubaccount

func (m *DydxProvider) GetSubaccount() string

GetSubaccount implements Provider

func (*DydxProvider) GetSubaccountBalance

func (m *DydxProvider) GetSubaccountBalance() (sdk.Coins, error)

GetSubaccountBalance implements Provider

func (*DydxProvider) IncreasePosition

func (m *DydxProvider) IncreasePosition(ctx context.Context, price float64, amount, margin sdkmath.Int, isLong bool) (*ExecutionResult, error)

Helper functions

func (*DydxProvider) Initialize

func (m *DydxProvider) Initialize(_ context.Context) error

Initialize implements Provider

func (*DydxProvider) ProcessPerpEvent

func (m *DydxProvider) ProcessPerpEvent(_ []abcitypes.Event) (currentPrice string, entryPrice string, err error)

ProcessPerpEvent implements Provider

func (*DydxProvider) QueryCandlePrices

func (m *DydxProvider) QueryCandlePrices(ctx context.Context, market string) (*IndexerCandleResponse, error)

Helper method for subaccount queries

func (*DydxProvider) QueryFillsIndexer

func (m *DydxProvider) QueryFillsIndexer(ctx context.Context, address string, subaccountNumber uint32) (*IndexerFillResponse, error)

Helper method for subaccount queries

func (*DydxProvider) QueryIndexer

func (m *DydxProvider) QueryIndexer(ctx context.Context, path string) (map[string]interface{}, error)

Add these new methods

func (*DydxProvider) QuerySubaccountIndexer

func (m *DydxProvider) QuerySubaccountIndexer(ctx context.Context, address string, subaccountNumber uint32) (*IndexerSubaccountResponse, error)

Helper method for subaccount queries

func (*DydxProvider) ReducePosition

func (m *DydxProvider) ReducePosition(ctx context.Context, price float64, amount, margin sdkmath.Int, isLong bool) (*ExecutionResult, error)

func (*DydxProvider) WithdrawSubaccount

func (m *DydxProvider) WithdrawSubaccount(_ context.Context, amount sdkmath.Int) ([]sdk.Msg, error)

WithdrawSubaccount implements Provider

type ExecutionResult

type ExecutionResult struct {
	TxHash   string
	Events   []abcitypes.Event
	Position *Position
	Executed bool
	Messages []sdk.Msg // The messages that were or would be sent
	Notes    string    // Additional information about the execution
}

ExecutionResult represents the result of a position operation

type IndexerAssetPosition

type IndexerAssetPosition struct {
	Size             string `json:"size"`
	Symbol           string `json:"symbol"`
	Side             string `json:"side"`
	AssetID          string `json:"assetId"`
	SubaccountNumber int    `json:"subaccountNumber"`
}

IndexerAssetPosition represents an asset position

type IndexerCandle

type IndexerCandle struct {
	StartedAt              string `json:"startedAt"`
	Ticker                 string `json:"ticker"`
	Resolution             string `json:"resolution"`
	Low                    string `json:"low"`
	High                   string `json:"high"`
	Open                   string `json:"open"`
	Close                  string `json:"close"`
	BaseTokenVolume        string `json:"baseTokenVolume"`
	UsdVolume              string `json:"usdVolume"`
	Trades                 int    `json:"trades"`
	StartingOpenInterest   string `json:"startingOpenInterest"`
	OrderbookMidPriceOpen  string `json:"orderbookMidPriceOpen"`
	OrderbookMidPriceClose string `json:"orderbookMidPriceClose"`
}

IndexerCandle represents a candle

type IndexerCandleResponse

type IndexerCandleResponse struct {
	Candles []IndexerCandle `json:"candles"`
}

IndexerCandleResponse represents the top-level response from the indexer

type IndexerFill

type IndexerFill struct {
	ID                string `json:"id"`
	Side              string `json:"side"`
	Liquidity         string `json:"liquidity"`
	Type              string `json:"type"`
	Market            string `json:"market"`
	MarketType        string `json:"marketType"`
	Price             string `json:"price"`
	Size              string `json:"size"`
	Fee               string `json:"fee"`
	AffiliateRevShare string `json:"affiliateRevShare"`
	CreatedAt         string `json:"createdAt"`
	CreatedAtHeight   string `json:"createdAtHeight"`
	OrderID           string `json:"orderId"`
	ClientMetadata    string `json:"clientMetadata"`
	SubaccountNumber  uint32 `json:"subaccountNumber"`
}

IndexerFill represents a single fill from the dYdX indexer

type IndexerFillResponse

type IndexerFillResponse struct {
	Fills []IndexerFill `json:"fills"`
}

IndexerFillResponse represents a response containing fills from the dYdX indexer

type IndexerPerpPosition

type IndexerPerpPosition struct {
	Market           string  `json:"market"`
	Status           string  `json:"status"`
	Side             string  `json:"side"`
	Size             string  `json:"size"`
	MaxSize          string  `json:"maxSize"`
	EntryPrice       string  `json:"entryPrice"`
	ExitPrice        *string `json:"exitPrice"`
	RealizedPnl      string  `json:"realizedPnl"`
	UnrealizedPnl    string  `json:"unrealizedPnl"`
	CreatedAt        string  `json:"createdAt"`
	CreatedAtHeight  string  `json:"createdAtHeight"`
	ClosedAt         *string `json:"closedAt"`
	SumOpen          string  `json:"sumOpen"`
	SumClose         string  `json:"sumClose"`
	NetFunding       string  `json:"netFunding"`
	SubaccountNumber int     `json:"subaccountNumber"`
}

IndexerPerpPosition represents a perpetual position

type IndexerSubaccount

type IndexerSubaccount struct {
	Address                    string                          `json:"address"`
	SubaccountNumber           int                             `json:"subaccountNumber"`
	Equity                     string                          `json:"equity"`
	FreeCollateral             string                          `json:"freeCollateral"`
	OpenPerpetualPositions     map[string]IndexerPerpPosition  `json:"openPerpetualPositions"`
	AssetPositions             map[string]IndexerAssetPosition `json:"assetPositions"`
	MarginEnabled              bool                            `json:"marginEnabled"`
	UpdatedAtHeight            string                          `json:"updatedAtHeight"`
	LatestProcessedBlockHeight string                          `json:"latestProcessedBlockHeight"`
}

IndexerSubaccount represents a subaccount's details

type IndexerSubaccountResponse

type IndexerSubaccountResponse struct {
	Subaccount IndexerSubaccount `json:"subaccount"`
}

IndexerSubaccountResponse represents the top-level response from the indexer

type MarsConfig

type MarsConfig struct {
	ChainID         string
	CreditClient    creditmanager.QueryClient
	PerpsClient     marsperps.QueryClient
	MarsConfig      types.MarsConfig
	CollateralDenom string
	OutDecimals     int
	Executor        string
}

MarsConfig holds the configuration for the Mars provider

type MarsProvider

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

MarsProvider implements the Provider interface for Mars Protocol

func NewMarsProvider

func NewMarsProvider(
	logger *zap.Logger,
	chainID string,
	creditClient creditmanager.QueryClient,
	perpsClient marsperps.QueryClient,
	config types.MarsConfig,
	collateralDenom string,
	outDecimals int,
	executor string,
) *MarsProvider

NewMarsProvider creates a new Mars provider

func (*MarsProvider) AdjustMargin

func (m *MarsProvider) AdjustMargin(_ context.Context, _ sdkmath.Int, _ bool) (*ExecutionResult, error)

func (*MarsProvider) CheckSubaccount

func (m *MarsProvider) CheckSubaccount(account string) (bool, error)

CheckSubaccount implements Provider

func (*MarsProvider) ClosePosition

func (m *MarsProvider) ClosePosition(_ context.Context, _ bool) (*ExecutionResult, error)

func (*MarsProvider) CreateLimitOrder

func (m *MarsProvider) CreateLimitOrder(_ context.Context, _, _, _ sdkmath.Int, _, _ bool) ([]sdk.Msg, error)

CreateLimitOrder implements Provider

func (*MarsProvider) CreateMarketOrder

func (m *MarsProvider) CreateMarketOrder(_ context.Context, _, margin, size sdkmath.Int, _, reduceOnly bool) ([]sdk.Msg, error)

CreateMarketOrder implements Provider

func (*MarsProvider) CreateSubaccount

func (m *MarsProvider) CreateSubaccount(account string) (sdk.Msg, error)

CreateSubaccount implements Provider

func (*MarsProvider) DepositSubaccount

func (m *MarsProvider) DepositSubaccount(_ context.Context, amount sdkmath.Int) ([]sdk.Msg, error)

DepositSubaccount implements Provider

func (*MarsProvider) GetAccountBalance

func (m *MarsProvider) GetAccountBalance() (sdk.Coins, error)

GetAccountBalance implements Provider

func (*MarsProvider) GetLiquidationPrice

func (m *MarsProvider) GetLiquidationPrice(_, _, _, _ sdkmath.LegacyDec) sdkmath.LegacyDec

GetLiquidationPrice implements Provider

func (*MarsProvider) GetPosition

func (m *MarsProvider) GetPosition(ctx context.Context) (*Position, error)

GetOpenPosition implements Provider

func (*MarsProvider) GetProviderChainID

func (m *MarsProvider) GetProviderChainID() string

GetProviderDenom implements Provider

func (*MarsProvider) GetProviderDenom

func (m *MarsProvider) GetProviderDenom() string

GetProviderDenom implements Provider

func (*MarsProvider) GetProviderExecutor

func (m *MarsProvider) GetProviderExecutor() string

GetProviderExecutor implements Provider

func (*MarsProvider) GetProviderName

func (m *MarsProvider) GetProviderName() string

GetProviderName implements Provider

func (*MarsProvider) GetSubaccount

func (m *MarsProvider) GetSubaccount() string

GetSubaccount implements Provider

func (*MarsProvider) GetSubaccountBalance

func (m *MarsProvider) GetSubaccountBalance() (sdk.Coins, error)

GetSubaccountBalance implements Provider

func (*MarsProvider) IncreasePosition

func (m *MarsProvider) IncreasePosition(ctx context.Context, _ float64, amount, _ sdkmath.Int, _ bool) (*ExecutionResult, error)

func (*MarsProvider) Initialize

func (m *MarsProvider) Initialize(_ context.Context) error

Initialize implements Provider

func (*MarsProvider) ProcessPerpEvent

func (m *MarsProvider) ProcessPerpEvent(events []abcitypes.Event) (currentPrice string, entryPrice string, err error)

ProcessPerpEvent implements Provider

func (*MarsProvider) ReducePosition

func (m *MarsProvider) ReducePosition(_ context.Context, _ float64, _, _ sdkmath.Int, _ bool) (*ExecutionResult, error)

func (*MarsProvider) WithdrawSubaccount

func (m *MarsProvider) WithdrawSubaccount(_ context.Context, amount sdkmath.Int) ([]sdk.Msg, error)

WithdrawSubaccount implements Provider

type Position

type Position struct {
	CurrentPrice  sdkmath.LegacyDec
	EntryPrice    sdkmath.LegacyDec
	Margin        sdkmath.Int
	Amount        sdkmath.Int
	UnrealizedPnl sdkmath.Int
	RealizedPnl   sdkmath.Int
}

Position represents a perpetual futures position

func GetPosition

func GetPosition(creditPositions creditmanager.PositionsResponse, perpPosition *marsperps.PerpPosition, denom string) (Position, error)

GetPosition extracts and returns a PerpPosition from a PositionsResponse based on a given denom.

func ProcessIndexerResponse

func ProcessIndexerResponse(
	market string,
	decimals int64,
	response *IndexerSubaccountResponse,
) (*Position, error)

ProcessIndexerResponse converts indexer response data into a Position

type Provider

type Provider interface {
	// Initialization
	Initialize(ctx context.Context) error

	// Account Management
	CreateSubaccount(account string) (sdk.Msg, error)
	CheckSubaccount(account string) (bool, error)
	GetSubaccount() string
	GetAccountBalance() (sdk.Coins, error)
	GetSubaccountBalance() (sdk.Coins, error)

	// Order Management
	CreateMarketOrder(ctx context.Context, price, margin, size sdkmath.Int, isBuy, reduceOnly bool) ([]sdk.Msg, error)
	CreateLimitOrder(ctx context.Context, price, margin, size sdkmath.Int, isBuy, reduceOnly bool) ([]sdk.Msg, error)

	// Position Management
	GetPosition(ctx context.Context) (*Position, error)
	GetLiquidationPrice(equity, size, entryPrice, maintenanceMargin sdkmath.LegacyDec) sdkmath.LegacyDec

	// Fund Management
	DepositSubaccount(ctx context.Context, margin sdkmath.Int) ([]sdk.Msg, error)
	WithdrawSubaccount(ctx context.Context, margin sdkmath.Int) ([]sdk.Msg, error)

	// Provider Information
	GetProviderChainID() string
	GetProviderName() string
	GetProviderDenom() string
	GetProviderExecutor() string

	// Event Handling
	ProcessPerpEvent(events []abcitypes.Event) (currentPrice string, entryPrice string, err error)

	// High-Level Operations
	IncreasePosition(ctx context.Context, price float64, amount, margin sdkmath.Int, isLong bool) (*ExecutionResult, error)
	ReducePosition(ctx context.Context, price float64, amount, margin sdkmath.Int, isLong bool) (*ExecutionResult, error)
	ClosePosition(ctx context.Context, isLong bool) (*ExecutionResult, error)
	AdjustMargin(ctx context.Context, margin sdkmath.Int, isAdd bool) (*ExecutionResult, error)
}

Provider defines the interface that any perps provider must implement

func CreateProvider

func CreateProvider(
	providerType ProviderType,
	logger *zap.Logger,
	config map[string]interface{},
) (Provider, error)

ProviderFactory creates perps providers

type ProviderType

type ProviderType string

ProviderType represents supported perps providers

const (
	ProviderMars ProviderType = "mars"
	ProviderDydx ProviderType = "dydx"
)

func GetProvider

func GetProvider(provider string) ProviderType

Jump to

Keyboard shortcuts

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