dydx

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package dydx implements godex.VenueExecutor for dYdX v4.

It places short-term orders: gas-free, matched synchronously in CheckTx (so a crossing post-only is rejected in the broadcast response rather than asynchronously), and valid for at most a handful of blocks. That last part is the venue's defining characteristic — a resting order here expires on its own after roughly fifteen blocks, which the adapter reports as an OrderRejectedEvent so a strategy never believes a quote is still live.

Transactions are built, signed (SIGN_MODE_DIRECT secp256k1), and broadcast from a minimal vendored protobuf set rather than the dYdX chain module; see internal/pb. Market and account state come from the Indexer, while block height, account lookups, and broadcast go to a validator's CometBFT RPC.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func KeyFromMnemonic added in v0.4.0

func KeyFromMnemonic(mnemonic string) (privateKeyHex, address string, err error)

KeyFromMnemonic derives the account signing key at m/44'/118'/0'/0/0 from a BIP-39 mnemonic and returns it as Credentials-ready values: the private key hex and its bech32 address ("dydx1...").

The mnemonic's checksum is validated (fail fast): deriving from a mistyped mnemonic would produce a syntactically valid but wrong key that only fails much later, as an on-chain authorization error.

func LoadExecutionMetadata added in v0.4.0

func LoadExecutionMetadata(ctx context.Context, cfg MarketDataConfig) (godex.ExecutionMetadata, error)

LoadExecutionMetadata resolves the market's execution metadata (size step, maintenance margin fraction) over public REST, without credentials. It serves consumers that pair real market data with a simulated executor (dry runs): the simulation quantizes exactly like the live executor would.

Types

type Config

type Config struct {
	Credentials Credentials
	// Symbol is the normalized label stamped on events (e.g. "ETH-PERP").
	Symbol godex.Symbol
	// Ticker is the venue market ticker (e.g. "ETH-USD"). dYdX identifies
	// markets by ticker; the numeric clob pair id is resolved at Connect.
	Ticker  string
	Network Network
	// Reconnect tunes the account WS; the zero value means
	// godex.DefaultReconnectConfig().
	Reconnect godex.ReconnectConfig
	// Logger receives operational logs; nil means slog.Default().
	Logger *slog.Logger

	// Test/ops overrides. Zero values resolve from Network and the package
	// constants.
	IndexerRESTBaseURL   string
	IndexerWSURL         string
	RPCBaseURL           string
	ChainID              string
	HTTPClient           *http.Client
	Now                  func() time.Time
	TxRequestTimeout     time.Duration
	TxFaultRecoveryDelay time.Duration
	HeightPollInterval   time.Duration
	HeightStaleAfter     time.Duration
	// contains filtered or unexported fields
}

Config parameterizes a dydx Executor.

type Credentials

type Credentials struct {
	// PrivateKeyHex is the hex-encoded secp256k1 signing key ("0x" prefix
	// optional).
	PrivateKeyHex string
	// Address is the bech32 account the orders belong to ("dydx1..."). Orders
	// are always attributed to this account; it is the message signer whether
	// or not a scoped key signs the transaction.
	//
	// Without an authenticator the signing key must control this address, and
	// Connect verifies that. With an authenticator the signing key is expected
	// to be a different, scoped key, so no such check applies.
	Address string
	// SubaccountNumber selects the subaccount to trade (0 is the default one).
	SubaccountNumber uint32
	// AuthenticatorID names the on-chain authenticator that authorizes this key
	// to act for Address. Nil means the key signs as the account owner itself.
	//
	// The chain expects exactly one authenticator id per message in a
	// transaction, and every transaction godex sends carries one message —
	// hence a single id rather than a list. Compose restrictions (message type,
	// market, subaccount) into one AllOf authenticator on chain and name that.
	AuthenticatorID *uint64
}

Credentials is the venue-scoped trading key material. The library never reads environment variables or files — pass values in from your own secret storage.

dYdX has no separate API key: transactions are signed with an account key. Use a dedicated key registered on chain as a scoped authenticator (accountplus) and name it in AuthenticatorID, so the in-process key cannot withdraw or transfer. A key that controls the account outright must never reach a trading process.

type Executor

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

Executor is the dYdX v4 implementation of godex.VenueExecutor.

func New

func New(cfg Config) (*Executor, error)

New builds an Executor. It performs no I/O; Connect does.

func (*Executor) AccountEvents

func (e *Executor) AccountEvents() <-chan godex.AccountEvent

AccountEvents implements godex.VenueExecutor.

func (*Executor) CancelOrder

func (e *Executor) CancelOrder(ctx context.Context, id godex.OrderID) error

CancelOrder implements godex.VenueExecutor.

func (*Executor) Close

func (e *Executor) Close() error

Close implements godex.VenueExecutor. It is terminal and idempotent.

func (*Executor) Connect

func (e *Executor) Connect(ctx context.Context) (godex.ExecutionMetadata, error)

Connect implements godex.VenueExecutor: it loads market metadata, verifies the signing key controls the configured address, reads the account number and sequence, establishes the block height, starts the account stream, and completes only after a verified snapshot has been emitted.

func (*Executor) ForceReconnect

func (e *Executor) ForceReconnect() error

ForceReconnect force-closes the account stream so the automatic reconnect path (resubscription, snapshot re-convergence, fill backfill) runs. Used by the smoke-test reconnect gate.

func (*Executor) PlaceOrder

func (e *Executor) PlaceOrder(ctx context.Context, order godex.NewOrder) (godex.OrderAck, error)

PlaceOrder implements godex.VenueExecutor.

func (*Executor) VenueID

func (e *Executor) VenueID() godex.VenueID

VenueID implements godex.VenueExecutor.

type FundingPayment added in v0.4.0

type FundingPayment struct {
	CreatedAt time.Time
	Ticker    string
	// Side is the position side the payment applied to ("LONG"/"SHORT"); the
	// payment's sign lives in Payment.
	Side string
	// Size is the position size the payment applied to, in base-asset units.
	Size decimal.Decimal
	// Rate is the funding rate applied.
	Rate decimal.Decimal
	// Payment is the settled USD amount: positive received, negative paid.
	Payment decimal.Decimal
}

FundingPayment is one settled funding payment from the Indexer's per-account history (GET /v4/fundingPayments). Unlike the account snapshot's netFunding — a per-position running total that resets when the position closes — payments arrive one per funding interval, so any window can be aggregated from them.

func FetchFundingPayments added in v0.4.0

func FetchFundingPayments(ctx context.Context, cfg FundingPaymentsConfig) ([]FundingPayment, error)

FetchFundingPayments loads an account's settled funding payments, newest first.

type FundingPaymentsConfig added in v0.4.0

type FundingPaymentsConfig struct {
	// Address is the bech32 account ("dydx1...").
	Address string
	// SubaccountNumber selects the subaccount (0 is the default one).
	SubaccountNumber uint32
	// Limit caps the number of newest-first records returned (one per funding
	// interval per open position).
	Limit   int
	Network Network

	// Test/ops overrides. Zero values resolve from Network.
	IndexerRESTBaseURL string
	HTTPClient         *http.Client
}

FundingPaymentsConfig parameterizes FetchFundingPayments. This is public Indexer data — no credentials involved.

type MarketData added in v0.4.0

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

MarketData polls the Indexer REST API for funding and market statistics of one market. Safe for concurrent use.

func NewMarketData added in v0.4.0

func NewMarketData(cfg MarketDataConfig) (*MarketData, error)

NewMarketData builds a MarketData client. It does not touch the network until the first query.

func (*MarketData) FundingRate added in v0.4.0

func (m *MarketData) FundingRate(ctx context.Context) (godex.FundingRate, error)

FundingRate implements godex.MarketDataClient. nextFundingRate is the venue's native 1-hour rate at unpredictable precision, rounded explicitly to godex.FundingRateScale. The Indexer does not report the next funding time, so NextFundingTime is nil.

func (*MarketData) MarketStats added in v0.4.0

func (m *MarketData) MarketStats(ctx context.Context) (godex.MarketStats, error)

MarketStats implements godex.MarketDataClient. openInterest is in base-asset units and is converted with the venue's oracle price, rounding once at the product; volume24H is already USD-denominated.

func (*MarketData) VenueID added in v0.4.0

func (m *MarketData) VenueID() godex.VenueID

VenueID implements godex.MarketDataClient.

type MarketDataConfig added in v0.4.0

type MarketDataConfig struct {
	// Symbol is the normalized label stamped on results (e.g. "SOL-PERP").
	Symbol godex.Symbol
	// Ticker is the venue market ticker (e.g. "SOL-USD").
	Ticker  string
	Network Network

	// Test/ops overrides. Zero values resolve from Network.
	IndexerRESTBaseURL string
	HTTPClient         *http.Client
}

MarketDataConfig parameterizes a dydx MarketData client.

type MarketStream added in v0.4.0

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

MarketStream streams the Indexer's v4_orderbook channel for one market and emits normalized full book snapshots.

Sequence integrity: message_id is numbered per connection without gaps or duplicates, but arrival order can swap across channels. A contiguous watermark tracks delivery; an id gap that stays unfilled beyond messageReorderTolerance early arrivals, or a duplicate id, means the connection as a whole lost integrity — it is aborted and the automatic reconnect rebuilds the book from a fresh snapshot.

Crossed books: the Indexer publishes crossed books in normal operation (event-application order jitter). Delta-driven crossings are uncrossed immediately by treating the later update as the freshest state (the same interpretation as the official client), so only a crossed snapshot reaches the caller side — the market is then resubscribed on the same connection. A within-market message_id regression (stale delta) also resubscribes. After maxConsecutiveResyncs the whole connection is rebuilt instead.

func NewMarketStream added in v0.4.0

func NewMarketStream(cfg MarketStreamConfig) (*MarketStream, error)

NewMarketStream builds a MarketStream. It does not touch the network until Start.

func (*MarketStream) Close added in v0.4.0

func (s *MarketStream) Close() error

Close implements godex.MarketStream.

func (*MarketStream) Events added in v0.4.0

func (s *MarketStream) Events() <-chan godex.MarketEvent

Events implements godex.MarketStream.

func (*MarketStream) Start added in v0.4.0

func (s *MarketStream) Start(ctx context.Context) error

Start implements godex.MarketStream.

func (*MarketStream) VenueID added in v0.4.0

func (s *MarketStream) VenueID() godex.VenueID

VenueID implements godex.MarketStream.

type MarketStreamConfig added in v0.4.0

type MarketStreamConfig struct {
	// Symbol is the normalized label stamped on events (e.g. "SOL-PERP").
	Symbol godex.Symbol
	// Ticker is the venue market ticker (e.g. "SOL-USD").
	Ticker string
	// PriceScale and SizeScale are the decimal scales book levels are
	// normalized to. Native precision beyond them is a configuration error
	// (fail fast), not something to round away.
	PriceScale int
	SizeScale  int
	Network    Network
	// Reconnect tunes the WS; the zero value means
	// godex.DefaultReconnectConfig().
	Reconnect godex.ReconnectConfig
	// Logger receives operational logs; nil means slog.Default().
	Logger *slog.Logger

	// Test/ops overrides. Zero values resolve from Network.
	IndexerWSURL string
}

MarketStreamConfig parameterizes a dydx MarketStream.

type Network

type Network string

Network selects the venue deployment. There is no default: the caller must choose explicitly (fail fast).

const (
	Testnet Network = "testnet"
	Mainnet Network = "mainnet"
)

Networks.

func (Network) ChainID

func (n Network) ChainID() (string, error)

ChainID returns the signing chain id for the network.

func (Network) IndexerRESTBaseURL

func (n Network) IndexerRESTBaseURL() (string, error)

IndexerRESTBaseURL returns the Indexer REST endpoint for the network.

func (Network) IndexerWSURL

func (n Network) IndexerWSURL() (string, error)

IndexerWSURL returns the Indexer account/market WebSocket endpoint.

func (Network) RPCBaseURL

func (n Network) RPCBaseURL() (string, error)

RPCBaseURL returns the validator's CometBFT RPC endpoint, which serves block height, account lookups, and transaction broadcast.

Directories

Path Synopsis
internal
pb
Package pb holds the generated protobuf types the dydx adapter needs to build, sign, and broadcast dYdX v4 (Cosmos SDK) transactions.
Package pb holds the generated protobuf types the dydx adapter needs to build, sign, and broadcast dYdX v4 (Cosmos SDK) transactions.

Jump to

Keyboard shortcuts

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