derivatives

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

derivative is a package to interact with the Kraken Futures API on REST and WebSocket V1.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRequest

func NewRequest(opts RequestOptions) (*kraken.Request, error)

NewRequest creates a kraken.Request struct for submission to the Derivatives API.

Authentication algorithm: https://docs.kraken.com/api/docs/guides/futures-rest

func Sign

func Sign(privateKey string, data io.Reader, nonce string, endpointPath string) (string, error)

Sign hashes path, nonce, and body using the given private key. Returns the base64-encoded result.

Types

type AccountsResult

type AccountsResult struct {
	Accounts map[string]any `json:"accounts,omitempty"`
	DerivativesResponse
}

type BatchOrderInstruction

type BatchOrderInstruction struct {
	Order                     string `json:"order,omitempty"`
	OrderTag                  string `json:"order_tag,omitempty"`
	OrderID                   string `json:"order_id,omitempty"`
	OrderType                 string `json:"orderType,omitempty"`
	Symbol                    string `json:"symbol,omitempty"`
	Side                      string `json:"side,omitempty"`
	Size                      string `json:"size,omitempty"`
	LimitPrice                string `json:"limitPrice,omitempty"`
	StopPrice                 string `json:"stopPrice,omitempty"`
	ClientOrderID             string `json:"cliOrdId,omitempty"`
	TriggerSignal             string `json:"triggerSignal,omitempty"`
	ReduceOnly                bool   `json:"reduceOnly,omitempty"`
	TrailingStopMaxDeviation  string `json:"trailingStopMaxDeviation,omitempty"`
	TrailingStopDeviationUnit string `json:"trailingStopDeviationUnit,omitempty"`
}

type BatchOrderJson

type BatchOrderJson struct {
	BatchOrder []*BatchOrderInstruction `json:"batchOrder,omitempty"`
}

type BatchOrderRequest

type BatchOrderRequest struct {
	ProcessBefore time.Time       `json:"processBefore,omitempty"`
	JSON          *BatchOrderJson `json:"json,omitempty" map:"stringify"`
}

type BatchOrderResult

type BatchOrderResult struct {
	BatchStatus []BatchStatusInfo `json:"batchStatus,omitempty"`
	DerivativesResponse
}

type BatchStatusInfo

type BatchStatusInfo struct {
	ClientOrderID    string           `json:"cliOrdId,omitempty"`
	DateTimeReceived time.Time        `json:"dateTimeReceived,omitempty"`
	OrderEvents      []map[string]any `json:"orderEvents,omitempty"`
	OrderID          string           `json:"order_id,omitempty"`
	OrderTag         string           `json:"order_tag,omitempty"`
	Status           string           `json:"status,omitempty"`
}

type BookManager

type BookManager struct {
	OnCreateBook *callback.Manager[*book.Book]
	// contains filtered or unexported fields
}

BookManager manages the lifecycle of a collection of [Book] structs.

func NewBookManager

func NewBookManager() *BookManager

NewBookManager constructs a new BookManager struct.

func (*BookManager) CreateBook

func (b *BookManager) CreateBook(name string) *book.Book

CreateBook constructs a managed [Book] struct.

func (*BookManager) GetBook

func (bm *BookManager) GetBook(name string) *book.Book

GetBook returns the [Book] struct associated with the given symbol.

func (*BookManager) GetBooks

func (bm *BookManager) GetBooks() []string

GetBooks returns a list of all managed [Book] structs.

func (*BookManager) Update

Update accepts a kraken.WebSocketMessage and processes an update.

func (*BookManager) UpdateDelta

func (bm *BookManager) UpdateDelta(b *book.Book, m map[string]any) error

UpdateDelta processes a delta response into the book.

func (*BookManager) UpdateSnapshot

func (bm *BookManager) UpdateSnapshot(b *book.Book, m map[string]any) error

UpdateSnapshot processes a snapshot response into the book.

type CancelAllRequest

type CancelAllRequest struct {
	Symbol string `json:"symbol,omitempty"`
}

type CancelAllResult

type CancelAllResult struct {
	CancelStatus CancelStatus `json:"cancelStatus,omitempty"`
	DerivativesResponse
}

type CancelOrderRequest

type CancelOrderRequest struct {
	ProcessBefore time.Time `json:"processBefore,omitempty"`
	OrderID       string    `json:"order_id,omitempty"`
	ClientOrderID string    `json:"cliOrdId,omitempty"`
}

type CancelOrderResult

type CancelOrderResult struct {
	CancelStatus OrderStatus `json:"cancelStatus,omitempty"`
	DerivativesResponse
}

type CancelStatus

type CancelStatus struct {
	CancelOnly      string           `json:"cancelOnly,omitempty"`
	CancelledOrders []CancelledOrder `json:"cancelledOrders,omitempty"`
	OrderEvents     []map[string]any `json:"orderEvents,omitempty"`
	ReceivedTime    time.Time        `json:"receivedTime,omitempty"`
	Status          string           `json:"status,omitempty"`
}

type CancelledOrder

type CancelledOrder struct {
	ClientOrderID string `json:"cliOrdId,omitempty"`
	OrderID       string `json:"order_id,omitempty"`
}

type DerivativesResponse

type DerivativesResponse struct {
	Result     string    `json:"result,omitempty"`
	ServerTime time.Time `json:"serverTime,omitempty"`
}

type EditOrderResult

type EditOrderResult struct {
	EditStatus OrderStatus
	DerivativesResponse
}

type Greeks

type Greeks struct {
	IV *decimal.Decimal `json:"iv,omitempty"`
}

type Instrument

type Instrument struct {
	Category                    string                    `json:"category,omitempty"`
	ContractSize                *decimal.Decimal          `json:"contractSize,omitempty"`
	ContractValueTradePrecision *decimal.Decimal          `json:"contractValueTradePrecision,omitempty"`
	FundingRateCoefficient      *decimal.Decimal          `json:"fundingRateCoefficient,omitempty"`
	ImpactMidSize               *decimal.Decimal          `json:"impactMidSize,omitempty"`
	ISIN                        string                    `json:"isin,omitempty"`
	LastTradingTime             time.Time                 `json:"lastTradingTime,omitempty"`
	MarginSchedules             map[string]MarginSchedule `json:"marginSchedules,omitempty"`
	RetailMarginLevels          []MarginSchedule          `json:"retailMarginLevels,omitempty"`
	MarginLevels                []MarginSchedule          `json:"marginLevels,omitempty"`
	MaxPositionSize             *decimal.Decimal          `json:"maxPositionSize,omitempty"`
	MaxRelativeFundingRate      *decimal.Decimal          `json:"maxRelativeFundingRate,omitempty"`
	OpeningDate                 time.Time                 `json:"openingDate,omitempty"`
	PostOnly                    bool                      `json:"postOnly,omitempty"`
	FeeScheduleUid              string                    `json:"feeScheduleUid,omitempty"`
	Symbol                      string                    `json:"symbol,omitempty"`
	Pair                        string                    `json:"pair,omitempty"`
	Base                        string                    `json:"base,omitempty"`
	Quote                       string                    `json:"quote,omitempty"`
	Tags                        []string                  `json:"tags,omitempty"`
	TickSize                    *decimal.Decimal          `json:"tickSize,omitempty"`
	Tradeable                   bool                      `json:"tradeable,omitempty"`
	Type                        string                    `json:"type,omitempty"`
	Underlying                  string                    `json:"underlying,omitempty"`
	UnderlyingFuture            string                    `json:"underlyingFuture,omitempty"`
	TradFi                      bool                      `json:"tradfi,omitempty"`
	Mtf                         bool                      `json:"mtf,omitempty"`
}

type InstrumentResult

type InstrumentResult struct {
	Instruments []Instrument `json:"instruments,omitempty"`
	DerivativesResponse
}

type JSONOrderBook

type JSONOrderBook struct {
	Asks [][]*decimal.Decimal `json:"asks,omitempty"`
	Bids [][]*decimal.Decimal `json:"bids,omitempty"`
}

func (JSONOrderBook) OrderBook

func (job JSONOrderBook) OrderBook() (book OrderBook)

type MarginSchedule

type MarginSchedule struct {
	Contracts           int              `json:"contracts,omitempty"`
	NumNonContractUnits *decimal.Decimal `json:"numNonContractUnits,omitempty"`
	InitialMargin       *decimal.Decimal `json:"initialMargin,omitempty"`
	MaintenanceMargin   *decimal.Decimal `json:"maintenanceMargin,omitempty"`
}

type Normalizer

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

Normalizer provides helper methods for a group of Instrument objects.

func NewNormalizer

func NewNormalizer() *Normalizer

NewNormalizer constructs a new Normalizer object. The map will need to be initialized with Normalizer.Use or Normalizer.Update.

func (*Normalizer) FormatPrice

func (m *Normalizer) FormatPrice(symbol string, v *decimal.Decimal) (*decimal.Decimal, error)

FormatPrice sets the decimals to the tick size of the contract.

func (*Normalizer) FormatSize

func (m *Normalizer) FormatSize(symbol string, v *decimal.Decimal) (*decimal.Decimal, error)

FormatSize sets the decimals to the lot size of the contract.

func (*Normalizer) Info

func (m *Normalizer) Info(symbol string) (*Instrument, error)

PairInfo returns the [AssetPair] struct corresponding to the symbol.

func (*Normalizer) Update

func (m *Normalizer) Update(update []Instrument)

Update creates and stores a map of Instrument objects.

func (*Normalizer) Use

func (m *Normalizer) Use(r *REST) error

Use retrieves instrument specifications using the specified REST structure.

type OpenOrder

type OpenOrder struct {
	OrderID        string           `json:"order_id,omitempty"`
	ClientOrderID  string           `json:"cliOrdId,omitempty"`
	Status         string           `json:"status,omitempty"`
	Side           string           `json:"side,omitempty"`
	OrderType      string           `json:"orderType,omitempty"`
	Symbol         string           `json:"symbol,omitempty"`
	LimitPrice     *decimal.Decimal `json:"limitPrice,omitempty"`
	StopPrice      *decimal.Decimal `json:"stopPrice,omitempty"`
	FilledSize     *decimal.Decimal `json:"filledSize,omitempty"`
	UnfilledSize   *decimal.Decimal `json:"unfilledSize,omitempty"`
	ReduceOnly     bool             `json:"reduceOnly,omitempty"`
	TriggerSignal  string           `json:"triggerSignal,omitempty"`
	LastUpdateTime time.Time        `json:"lastUpdateTime,omitempty"`
	ReceivedTime   time.Time        `json:"receivedTime,omitempty"`
}

type OpenOrdersResult

type OpenOrdersResult struct {
	OpenOrders []OpenOrder `json:"openOrders,omitempty"`
	DerivativesResponse
}

type OrderBook

type OrderBook struct {
	Asks []PriceLevel `json:"asks,omitempty"`
	Bids []PriceLevel `json:"bids,omitempty"`
}

func (*OrderBook) UnmarshalJSON

func (ob *OrderBook) UnmarshalJSON(data []byte) error

type OrderBookRequest

type OrderBookRequest struct {
	Symbol string `json:"symbol,omitempty"`
}

type OrderBookResult

type OrderBookResult struct {
	OrderBook OrderBook `json:"orderBook,omitempty"`
	DerivativesResponse
}

type OrderRequest

type OrderRequest struct {
	ProcessBefore             time.Time `json:"processBefore,omitempty"`
	OrderType                 string    `json:"orderType,omitempty"`
	Symbol                    string    `json:"symbol,omitempty"`
	Side                      string    `json:"side,omitempty"`
	Size                      string    `json:"size,omitempty"`
	LimitPrice                string    `json:"limitPrice,omitempty"`
	StopPrice                 string    `json:"stopPrice,omitempty"`
	ClientOrderID             string    `json:"cliOrdId,omitempty"`
	TriggerSignal             string    `json:"triggerSignal,omitempty"`
	ReduceOnly                bool      `json:"reduceOnly,omitempty"`
	TrailingStopMaxDeviation  string    `json:"trailingStopMaxDeviation,omitempty"`
	TrailingStopDeviationUnit string    `json:"trailingStopDeviationUnit,omitempty"`
	LimitPriceOffsetValue     string    `json:"limitPriceOffsetValue,omitempty"`
	LimitPriceOffsetUnit      string    `json:"limitPriceOffsetUnit,omitempty"`
}

type OrderStatus

type OrderStatus struct {
	ClientOrderID string           `json:"cliOrdId,omitempty"`
	OrderEvents   []map[string]any `json:"orderEvents,omitempty"`
	OrderID       string           `json:"order_id,omitempty"`
	ReceivedTime  time.Time        `json:"receivedTime,omitempty"`
	Status        string           `json:"status,omitempty"`
}

type PriceLevel

type PriceLevel struct {
	Price  *decimal.Decimal `json:"price,omitempty"`
	Volume *decimal.Decimal `json:"volume,omitempty"`
}

type REST

type REST struct {
	PublicKey  string
	PrivateKey string
	Nonce      func() string
	BaseURL    string
	Executor   kraken.ExecutorFunction
}

REST wraps [RESTBase] with functions to call common endpoints.

func NewREST

func NewREST() *REST

REST constructs a new REST object with default values.

For authentication, store the derivatives API key on the PublicKey and PrivateKey fields.

func (*REST) Accounts

func (r *REST) Accounts() (*Response[AccountsResult], error)

Accounts retrieves balances, margin requirements, margin trigger estimates, and other auxilary information of all futures cash and margin accounts.

https://docs.kraken.com/api/docs/futures-api/trading/get-accounts

func (*REST) BatchOrder

func (r *REST) BatchOrder(opts *BatchOrderRequest) (*Response[BatchOrderResult], error)

BatchOrder allows placing an order, cancelling an open order, or editing an existing order in a single request.

https://docs.kraken.com/api/docs/futures-api/trading/send-batch-order

func (*REST) CancelAll

func (r *REST) CancelAll(opts *CancelAllRequest) (*Response[CancelAllResult], error)

CancelAll cancels all open orders on a specific contract pair.

https://docs.kraken.com/api/docs/futures-api/trading/cancel-all-orders

func (*REST) CancelOrder

func (r *REST) CancelOrder(opts *CancelOrderRequest) (*Response[CancelOrderResult], error)

CancelOrder cancels an open order.

https://docs.kraken.com/api/docs/futures-api/trading/cancel-order

func (*REST) EditOrder

func (r *REST) EditOrder(opts *OrderRequest) (*Response[EditOrderResult], error)

EditOrder edits an existing order.

https://docs.kraken.com/api/docs/futures-api/trading/edit-order-spring

func (*REST) InstrumentSymbol

func (r *REST) InstrumentSymbol(s string) (*Instrument, error)

InstrumentSymbol calls REST.Instruments and returns the first Instrument with matching symbol.

func (*REST) Instruments

func (r *REST) Instruments() (*Response[InstrumentResult], error)

Instruments retrieves the specifications of all available contract pairs.

https://docs.kraken.com/api/docs/futures-api/trading/get-instruments

func (*REST) NewRequest

func (r *REST) NewRequest(opts RequestOptions) (*kraken.Request, error)

func (*REST) OpenOrders

func (r *REST) OpenOrders() (*Response[OpenOrdersResult], error)

OpenOrders retrieves information regarding all open orders on the futures account.

https://docs.kraken.com/api/docs/futures-api/trading/get-open-orders

func (*REST) OrderBook

func (r *REST) OrderBook(opts *OrderBookRequest) (*Response[OrderBookResult], error)

OrderBook retrieves the top bid and ask records of a contract pair.

https://docs.kraken.com/api/docs/futures-api/trading/get-orderbook

func (*REST) SendOrder

func (r *REST) SendOrder(opts *OrderRequest) (*Response[SendOrderResult], error)

SendOrder places a new order.

https://docs.kraken.com/api/docs/futures-api/trading/send-order

func (*REST) TickerSymbol

func (r *REST) TickerSymbol(symbol string) (*Response[TickersSingleResult], error)

TickerSymbol retrieves the ticker information of a specific contract pair or indice.

https://docs.kraken.com/api/docs/futures-api/trading/get-ticker

func (*REST) Tickers

func (r *REST) Tickers() (*Response[TickersResult], error)

Tickers retrieves the ticker information of all available contract pairs and indices.

https://docs.kraken.com/api/docs/futures-api/trading/get-tickers

func (*REST) TradeHistory

func (r *REST) TradeHistory(opts *TradeHistoryRequest) (*Response[TradeHistoryResult], error)

TradeHistory retrieves the most recent trade events in a futures market.

https://docs.kraken.com/api/docs/futures-api/trading/get-history

type RequestOptions

type RequestOptions struct {
	Auth       bool
	PublicKey  string
	PrivateKey string
	Nonce      func() string
	Method     string
	URL        string
	Path       any
	Query      any
	Headers    map[string]any
	Body       any
	UserAgent  string
	Executor   kraken.ExecutorFunction
}

RequestOptions contains the parameters for NewRequest.

type Requestor

type Requestor interface {
	NewRequest(RequestOptions) (*kraken.Request, error)
}

type Response

type Response[T any] struct {
	Result T                `json:"result,omitempty"`
	Http   *kraken.Response `json:"-"`
}

func Call

func Call[T any](r Requestor, opts RequestOptions) (resp *Response[T], err error)

Call creates a request and returns a generic response.

type SendOrderResult

type SendOrderResult struct {
	SendStatus OrderStatus `json:"sendStatus,omitempty"`
	DerivativesResponse
}

type TickerData

type TickerData struct {
	Symbol                string           `json:"symbol,omitempty"`
	Last                  *decimal.Decimal `json:"last,omitempty"`
	LastTime              time.Time        `json:"lastTime,omitempty"`
	LastSize              *decimal.Decimal `json:"lastSize,omitempty"`
	Tag                   string           `json:"tag,omitempty"`
	Pair                  string           `json:"pair,omitempty"`
	MarkPrice             *decimal.Decimal `json:"markPrice,omitempty"`
	Bid                   *decimal.Decimal `json:"bid,omitempty"`
	BidSize               *decimal.Decimal `json:"bidSize,omitempty"`
	Ask                   *decimal.Decimal `json:"ask,omitempty"`
	AskSize               *decimal.Decimal `json:"askSize,omitempty"`
	Vol24h                *decimal.Decimal `json:"vol24h,omitempty"`
	VolumeQuote           *decimal.Decimal `json:"volumeQuote,omitempty"`
	OpenInterest          *decimal.Decimal `json:"openInterest,omitempty"`
	Open24h               *decimal.Decimal `json:"open24h,omitempty"`
	High24h               *decimal.Decimal `json:"high24h,omitempty"`
	Low24h                *decimal.Decimal `json:"low24h,omitempty"`
	ExtrinsicValue        *decimal.Decimal `json:"extrinsicValue,omitempty"`
	FundingRate           *decimal.Decimal `json:"fundingRate,omitempty"`
	FundingRatePrediction *decimal.Decimal `json:"fundingRatePrediction,omitempty"`
	Suspended             bool             `json:"suspended,omitempty"`
	IndexPrice            *decimal.Decimal `json:"indexPrice,omitempty"`
	PostOnly              bool             `json:"postOnly,omitempty"`
	Change24h             *decimal.Decimal `json:"change24h,omitempty"`
}

type TickersResult

type TickersResult struct {
	Tickers []TickerData `json:"tickers,omitempty"`
	DerivativesResponse
}

type TickersSingleResult

type TickersSingleResult struct {
	Data   TickerData `json:"ticker,omitempty"`
	Errors []any      `json:"errors,omitempty"`
	Error  any        `json:"error,omitempty"`
	DerivativesResponse
}

type Trade

type Trade struct {
	Price                         *decimal.Decimal `json:"price,omitempty"`
	Side                          string           `json:"side,omitempty"`
	Size                          *decimal.Decimal `json:"size,omitempty"`
	Time                          time.Time        `json:"time,omitempty"`
	TradeID                       int              `json:"trade_id,omitempty"`
	Type                          string           `json:"type,omitempty"`
	UID                           string           `json:"uid,omitempty"`
	InstrumentIdentificationType  string           `json:"instrument_identification_type,omitempty"`
	ISIN                          string           `json:"isin,omitempty"`
	ExecutionVenue                string           `json:"execution_venue,omitempty"`
	PriceNotation                 string           `json:"price_notation,omitempty"`
	PriceCurrency                 string           `json:"price_currency,omitempty"`
	NotionalAmount                *decimal.Decimal `json:"notional_amount,omitempty"`
	NotionalCurrency              string           `json:"notional_currency,omitempty"`
	PublicationTime               string           `json:"publication_time,omitempty"`
	PublicationVenue              string           `json:"publication_venue,omitempty"`
	TransactionIdentificationCode string           `json:"transaction_identification_code,omitempty"`
	ToBeCleared                   bool             `json:"to_be_cleared,omitempty"`
}

type TradeHistoryRequest

type TradeHistoryRequest struct {
	Symbol   string `json:"symbol,omitempty"`
	LastTime string `json:"lastTime,omitempty"`
}

type TradeHistoryResult

type TradeHistoryResult struct {
	History []Trade `json:"history,omitempty"`
	DerivativesResponse
}

type WebSocket

type WebSocket struct {
	REST *REST
	*WebSocketBase
}

WebSocket wraps a WebSocketBase struct with order management and subscription request functions.

func NewWebSocket

func NewWebSocket() *WebSocket

NewWebSocket constructs a new WebSocket struct with default values.

For authentication, store the derivatives API key on REST.PublicKey and REST.PrivateKey.

func (*WebSocket) SubBalances

func (s *WebSocket) SubBalances() error

SubBalances sends a subscription request to retrieve information for holding wallets, single collateral wallets and multi-collateral wallets.

https://docs.kraken.com/api/docs/futures-api/websocket/balances

func (*WebSocket) SubBook

func (s *WebSocket) SubBook(productID ...string) error

SubBook sends a subscription request to retrieve information about the order book.

https://docs.kraken.com/api/docs/futures-api/websocket/book

func (*WebSocket) SubExecutions

func (s *WebSocket) SubExecutions() error

SubExecutions sends a subscription request for the user's fill events.

https://docs.kraken.com/api/docs/futures-api/websocket/fills

func (*WebSocket) SubOpenOrders

func (s *WebSocket) SubOpenOrders() error

SubOpenOrders sends a subscription request to retrieve information about user open orders.

https://docs.kraken.com/api/docs/futures-api/websocket/open_orders_verbose

func (*WebSocket) SubPrivate

func (b *WebSocket) SubPrivate(feed string, options ...map[string]any) error

SubPrivate submits a subscription request with the authentication fields included.

func (*WebSocket) SubPublic

func (b *WebSocket) SubPublic(feed string, options ...map[string]any) error

SubPublic submits a subscription request.

func (*WebSocket) SubTicker

func (s *WebSocket) SubTicker(productID ...string) error

SubTicker sends a subscription request for pricing information regarding available futures markets.

https://docs.kraken.com/api/docs/futures-api/websocket/ticker

func (*WebSocket) SubTrade

func (s *WebSocket) SubTrade(productID ...string) error

SubTrade sends a subscription request to retrieve information about executed trades.

https://docs.kraken.com/api/docs/futures-api/websocket/trade

type WebSocketBase

type WebSocketBase struct {
	AuthenticateTimeout time.Duration
	PublicKey           string
	PrivateKey          string
	Challenge           string
	Signature           string
	OnAuthenticated     *callback.Manager[string]
	*kraken.WebSocket
}

WebSocketBase is the underlying of the WebSocket client.

func NewWebSocketBase

func NewWebSocketBase() *WebSocketBase

NewWebSocketBase constructs a WebSocketBase struct with default values.

func (*WebSocketBase) Authenticate

func (b *WebSocketBase) Authenticate() error

Authenticate submits a challenge request and retrieves the authentication fields.

If contained within a WebSocketBase callback, this must be wrapped with a goroutine to prevent blocking.

func (*WebSocketBase) SendPrivate

func (b *WebSocketBase) SendPrivate(m map[string]any) error

SendPrivate sends a JSON-encoded map with the authentication fields included.

Jump to

Keyboard shortcuts

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