kraken

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

kraken is a utility package with common functions shared across other packagges.

Index

Constants

View Source
const (
	Bid = "bid"
	Ask = "ask"
)
View Source
const DefaultDecimals = 12

Default decimal places set for integer constructors.

Variables

This section is empty.

Functions

func AddFormField

func AddFormField(writer *multipart.Writer, parent string, child string, v any) error

AddFormField fills a form field with a key defined by parent[child] or child if parent is empty and writes them into multipart.Writer. Accepted values: string, []byte, func() (MultipartFile, error), and map[string]any

func CreateReadCloser

func CreateReadCloser(b []byte) io.ReadCloser

CreateReadCloser constructs an io.ReadCloser from the a slice of byte characters.

func Maps

func Maps(p map[string]any, s ...map[string]any) map[string]any

Maps recursively merges multiple maps of type map[string]any.

func Sign

func Sign(key string, message []byte) (string, error)

Sign encodes a message into HMAC-SHA-512 hashed with a base64-encoded key.

func StructToMap

func StructToMap(s any) (map[string]any, error)

StructToMap converts a struct into a map[string]any object.

func ToJSON

func ToJSON(v any) string

ToJSON returns the JSON string of v or panics.

func ToJSONIndent

func ToJSONIndent(v any) string

ToJSONIndent returns the JSON string of v with indents or panics.

func Traverse

func Traverse[V any](m any, keys ...any) (*V, error)

Traverse returns the value in a nested structure based on a sequence of keys. Iteration-based map indexes are supported. However, they are non deterministic as Go maps are unordered.

func UUID

func UUID() string

UUID creates a new random UUID and returns it as a string or panics

Types

type Action

type Action[T any] func(*Event[T])

type Book

type Book struct {

	// Number of price levels for checksum.
	MaxDepth int `json:"maxDepth,omitempty"`

	// Whether to eliminate book crossings for each update.
	NoBookCrossing bool

	// Whether to trim price levels outside of the max depth.
	// Must be disable for whole books.
	EnableMaxDepth bool

	Bids *Side
	Asks *Side

	OnUpdated          *CallbackManager[*BookUpdateOptions]
	OnBookCrossed      *CallbackManager[*BookCrossedResult]
	OnMaxDepthExceeded *CallbackManager[*MaxDepthExceededResult]
	OnChecksummed      *CallbackManager[*ChecksumResult]
}

Order book structure for L2 and L3.

func NewBook

func NewBook() *Book

NewBook constructs a new Book struct with default values.

func (*Book) BestAsk

func (b *Book) BestAsk() *Level

BestAsk returns the lowest ask price level.

func (*Book) BestBid

func (b *Book) BestBid() *Level

BestBid returns the highest bid price level.

func (*Book) EnforceDepth

func (b *Book) EnforceDepth()

EnforceDepth checks whether the length of each side of the book exceeds the max depth and attempts to removes the worst out-of-depth price levels.

func (*Book) EnforceOrder

func (b *Book) EnforceOrder()

EnforceOrder check whether the bid is greater or equal to the ask and attempts to remove older conflicting price levels.

func (*Book) L2Checksum

func (b *Book) L2Checksum(checksum string) *ChecksumResult

L2Checksum verifies that the L2 book is synchronized with the exchange.

https://docs.kraken.com/api/docs/guides/spot-ws-book-v2

func (*Book) L3Checksum

func (b *Book) L3Checksum(checksum string) *ChecksumResult

L3Checksum verifies that the L3 book is synchronized with the exchange.

https://docs.kraken.com/api/docs/guides/spot-ws-l3-v2

func (*Book) Midpoint

func (b *Book) Midpoint() *Money

Midpoint returns the midpoint of the order book.

func (*Book) Spread

func (b *Book) Spread() *Money

Spread returns the relative difference between the bid-ask price.

func (*Book) Update

func (b *Book) Update(opts *BookUpdateOptions)

Update routes the BookUpdateOptions to the correct side of the book and enforces checks to preserve book integrity.

func (*Book) WorstAsk

func (b *Book) WorstAsk() *Level

WorstAsk returns the highest ask price level.

func (*Book) WorstBid

func (b *Book) WorstBid() *Level

WorstBid returns the lowest bid price level.

type BookCrossedResult

type BookCrossedResult struct {
	Bid *Level `json:"bid,omitempty"`
	Ask *Level `json:"ask,omitempty"`
}

type BookDirection

type BookDirection string

Whether a bid or an ask.

type BookUpdateOptions

type BookUpdateOptions struct {
	Direction BookDirection `json:"direction,omitempty"`
	ID        string        `json:"orderid,omitempty"`
	Price     *Money        `json:"price,omitempty"`
	Quantity  *Money        `json:"quantity,omitempty"`
	Timestamp time.Time     `json:"timestamp,omitempty"`
}

BookUpdateOptions is used to communicate an update to the Book.

type Callback

type Callback[T any] struct {
	Action  Action[T]
	Enabled bool
}

Callback contains the function reference and parameters.

func (*Callback[T]) Call

func (c *Callback[T]) Call(v T)

Call constructs an Event object and passes them to the internal Action function.

type CallbackManager

type CallbackManager[T any] struct {
	// contains filtered or unexported fields
}

CallbackManager manages the lifecycle of a collection of generic Callback structs.

func NewCallbackManager

func NewCallbackManager[T any]() *CallbackManager[T]

NewCallbackManager constructs a new CallbackManager structs.

func (*CallbackManager[T]) Call

func (cg *CallbackManager[T]) Call(v T)

Call fans out Event objects across all callbacks in the map.

func (*CallbackManager[T]) Deregister

func (cg *CallbackManager[T]) Deregister(c *Callback[T]) *Callback[T]

Reregister removes a Callback struct from the map.

func (*CallbackManager[T]) Map

func (cg *CallbackManager[T]) Map() map[*Callback[T]]bool

Map returns a clone of the internal Callback map.

func (*CallbackManager[T]) Once

func (cg *CallbackManager[T]) Once(action Action[T]) *Callback[T]

Once adds a Callback to the map that is deregistered after first execution.

func (*CallbackManager[T]) Recurring

func (cg *CallbackManager[T]) Recurring(action Action[T]) *Callback[T]

Recurring adds a recurring Callback struct to the map.

func (*CallbackManager[T]) Register

func (cg *CallbackManager[T]) Register(c *Callback[T]) *Callback[T]

Register adds a Callback struct to the map.

func (*CallbackManager[T]) Reset

func (cg *CallbackManager[T]) Reset()

Reset clears all Callback struct from the map.

func (*CallbackManager[T]) SleepUntilDisabled

func (cg *CallbackManager[T]) SleepUntilDisabled(action Action[T]) *Callback[T]

SleepUntilDisabled adds a Callback struct to the map and pauses the current goroutine until the callback is disabled.

type ChecksumPart

type ChecksumPart struct {
	Level        *Level `json:"-"`
	Order        *Order `json:"order,omitempty"`
	Price        string `json:"price,omitempty"`
	Quantity     string `json:"quantity,omitempty"`
	Concatenated string `json:"concatenated,omitempty"`
}

ChecksumPart contains information regarding a price level or order.

type ChecksumResult

type ChecksumResult struct {
	Level          int             `json:"level,omitempty"`
	ServerChecksum string          `json:"serverChecksum,omitempty"`
	LocalChecksum  string          `json:"localChecksum,omitempty"`
	Match          bool            `json:"match,omitempty"`
	AskParts       []*ChecksumPart `json:"askParts,omitempty"`
	BidParts       []*ChecksumPart `json:"bidParts,omitempty"`
	Asks           string          `json:"asks,omitempty"`
	Bids           string          `json:"bids,omitempty"`
}

ChecksumResult contains the result of the book checksum validation.

type EpochCounter

type EpochCounter struct {
	Granularity time.Duration
	// contains filtered or unexported fields
}

EpochCounter is the default counter for the module, used for nonce generation.

func NewEpochCounter

func NewEpochCounter() *EpochCounter

NewEpochCounter constructs a NonceGenerator.

func (*EpochCounter) Get

func (c *EpochCounter) Get() string

Get concatenates the unix epoch value and 3 leading zero counter values.

type Event

type Event[T any] struct {
	Data     T
	Callback *Callback[T]
}

Event contains the content and reference to the Callback struct.

type Level

type Level struct {
	Price     *Money    `json:"price,omitempty"`
	Quantity  *Money    `json:"quantity,omitempty"`
	Timestamp time.Time `json:"time,omitempty"`
	Lower     *Level    `json:"-"`
	Higher    *Level    `json:"-"`
	// contains filtered or unexported fields
}

Level contains price level information.

func NewLevel

func NewLevel() *Level

NewLevel constructs a new Level struct with default values.

func (*Level) GetPriceString

func (l *Level) GetPriceString() string

GetPriceString returns the level's price.

func (*Level) GetQuantityString

func (l *Level) GetQuantityString() string

GetQuantityString returns the level's total quantity.

func (*Level) Queue

func (l *Level) Queue() []*Order

Queue returns a list of orders arranged by time priority.

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map wraps a map and a mutex for concurrent operations.

func NewMap

func NewMap[K comparable, V any]() *Map[K, V]

NewMap creates a Map.

func (*Map[K, V]) Clone

func (m *Map[K, V]) Clone() *Map[K, V]

Clone returns a copy of m.

func (*Map[K, V]) Delete

func (m *Map[K, V]) Delete(key K)

Delete removes k from m.

func (*Map[K, V]) Get

func (m *Map[K, V]) Get(k K) (*V, error)

Get returns the value of k.

func (*Map[K, V]) Keys

func (m *Map[K, V]) Keys() []K

Keys returns all keys of m.

func (*Map[K, V]) Length

func (m *Map[K, V]) Length() int

Length returns the size of m.

func (*Map[K, V]) Range

func (m *Map[K, V]) Range(f func(K, *V))

Range executes f on all key-value pairs of m.

func (*Map[K, V]) Raw

func (m *Map[K, V]) Raw() map[K]*V

Raw returns a copy of the m hash map.

func (*Map[K, V]) Reset

func (m *Map[K, V]) Reset()

Reset assigns an empty hash map to m.

func (*Map[K, V]) Set

func (m *Map[K, V]) Set(key K, value *V)

Set assigns v to k.

func (*Map[K, V]) SetMap

func (m *Map[K, V]) SetMap(r map[K]*V)

SetMap sets m's hash map to r.

type MaxDepthExceededResult

type MaxDepthExceededResult struct {
	Side         BookDirection `json:"side,omitempty"`
	CurrentDepth int           `json:"currentDepth,omitempty"`
	MaxDepth     int           `json:"maxDepth,omitempty"`
	Worst        *Level        `json:"worst,omitempty"`
}

type Money

type Money struct {
	//  Unscaled integer representation.
	Integer *big.Int
	// Granularity.
	Granularity int64
	// Amount of decimal places.
	Decimals int64
}

Money implements fixed-point arithmetic.

func NewMoneyFromBigFloat

func NewMoneyFromBigFloat(f *big.Float) *Money

NewMoneyFromBigFloat creates a new Money object from a big.Float.

func NewMoneyFromBigInt

func NewMoneyFromBigInt(bi *big.Int) *Money

NewMoneyFromBigInt creates a new Money object from a big.Int.

func NewMoneyFromFloat64

func NewMoneyFromFloat64(f float64) *Money

NewMoneyFromFloat64 creates a new Money object from a float64.

func NewMoneyFromInt64

func NewMoneyFromInt64(i int64) *Money

NewMoneyFromInt64 creates a new Money object from an int64.

func NewMoneyFromString

func NewMoneyFromString(s string) (*Money, error)

NewMoneyFromString creates a new Money object from a string.

func (*Money) Abs

func (m *Money) Abs() *Money

Abs returns the absolute value of m.

func (*Money) Add

func (x *Money) Add(y *Money) *Money

Add returns the result of x + y.

func (*Money) Cmp

func (x *Money) Cmp(y *Money) int

Cmp compares x to y (-1, 0, 1 for <, =, >).

func (*Money) Copy

func (m *Money) Copy() *Money

Copy creates a copy of m.

func (*Money) Div

func (x *Money) Div(y *Money) *Money

Div returns the result of x / y.

func (*Money) Exp

func (x *Money) Exp(y *Money) *Money

func (*Money) Float64

func (m *Money) Float64() float64

Float64 returns the floating point representation of m with potential loss of precision.

func (*Money) Int64

func (m *Money) Int64() int64

Int64 returns the integer part of m with truncated decimals.

func (*Money) MarshalJSON

func (m *Money) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*Money) Mul

func (x *Money) Mul(y *Money) *Money

Mul returns the result of x * y

func (*Money) OffsetPercent

func (m *Money) OffsetPercent(o *Money) *Money

OffsetPercent returns the adjustment of m by %o. Formula: m * (1 + o). The multiplicand decimals are set to the max precision of both m and o.

func (*Money) OffsetTicks

func (m *Money) OffsetTicks(o *Money) *Money

OffsetTicks returns the adjustment of m by an increment proportional to o.

func (*Money) Rat

func (m *Money) Rat() *big.Rat

Rat returns the rational number of m.

func (*Money) RoundToGranularity

func (m *Money) RoundToGranularity() *Money

RoundToGranularity returns the rounding of m to the granularity constraint.

func (*Money) ScalingFactor

func (m *Money) ScalingFactor() *big.Int

ScalingFactor returns 10 ^ decimals in big.Int.

func (*Money) SetDecimals

func (m *Money) SetDecimals(d int64) *Money

SetDecimals returns m with adjusted decimal places.

func (*Money) SetGranularity

func (m *Money) SetGranularity(t int64) *Money

SetGranularity configures the raw integer of m to always be a multiple of t.

func (*Money) SetSize

func (m *Money) SetSize(s *Money) *Money

SetSize configures the value of m to always be a multiple of s.

func (*Money) Sign

func (m *Money) Sign() int

Sign returns -1 if m < 0, 0 if m == 0, and +1 if m > 0.

func (*Money) SmallestIncrement

func (m *Money) SmallestIncrement() *Money

SmallestIncrement returns the smallest possible increment of m.

func (*Money) String

func (m *Money) String() string

String returns the literal representation of m.

func (*Money) Sub

func (x *Money) Sub(y *Money) *Money

Sub returns the result of x - y

func (*Money) UnmarshalJSON

func (m *Money) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

type MultipartFile

type MultipartFile interface {
	Name() string
	io.ReadCloser
}

MultipartFile is an interface to attach a file into the multipart form. os.File implements this interface.

type MultipartForm

type MultipartForm struct {
	*bytes.Buffer
	*multipart.Writer
}

MultipartForm is a combined representation of bytes.Buffer and multipart.Writer, both essential for setting the body.

func CreateMultipartForm

func CreateMultipartForm(m map[string]any) (*MultipartForm, error)

CreateMultipartForm constructs a MultipartForm from the given map[string]any. See AddFormField for accepted values.

type NewRequestOptions

type NewRequestOptions struct {
	Method     string
	Path       any
	PathValues map[string]any
	Query      map[string]any
	Headers    map[string]any
	Body       any
}

NewRequestOptions contains the parameters for REST.NewRequest.

type Order

type Order struct {
	ID         string    `json:"id,omitempty"`
	LimitPrice *Money    `json:"limitPrice,omitempty"`
	Quantity   *Money    `json:"quantity,omitempty"`
	Timestamp  time.Time `json:"timestamp,omitempty"`
	Level      *Level    `json:"-"`
}

Order contains information regarding a limit order.

type REST

type REST struct {
	BaseURL            string
	DefaultContentType string
	DefaultUserAgent   string
	*http.Client
}

REST API wrapper for the HTTP client.

func NewREST

func NewREST() *REST

NewREST constructs a new REST struct with default values.

func (*REST) Do

func (r *REST) Do(req *Request) (*Response, error)

Do submits a Request struct and returns a Response.

func (*REST) NewRequest

func (r *REST) NewRequest(opts *NewRequestOptions) (*Request, error)

NewRequest creates a new Request.

func (*REST) Request

func (r *REST) Request(cfg *NewRequestOptions) (*Response, error)

Request helps to call REST.NewRequest and REST.Do in one line.

type Request

type Request struct {
	Body          []byte `json:"body,omitempty"`
	*http.Request `json:"-"`
}

Request is a wrapper around http.Request to assist with internal functions.

func NewRequest

func NewRequest() *Request

NewRequest initializes a Request object with default values.

func (*Request) GetMediaType

func (r *Request) GetMediaType() string

GetMediaType retrieves the Content-Type header without additional parameters.

func (*Request) JoinPath

func (r *Request) JoinPath(p any)

JoinPath adds a path parameter to the request URL.

func (*Request) SetBody

func (r *Request) SetBody(v any) error

SetBody sets the request body based on the current Content-Type of the Request.

It automatically encodes the provided value `v` according to the media type:

- "multipart/form-data": expects v to be a map[string]any and sets it as a multipart form.

- "application/x-www-form-urlencoded": expects v to be a map[string]any and encodes it as form values.

- "application/json": marshals v as JSON.

Returns an error if the Content-Type is unsupported or if the input type doesn't match the expected format.

func (*Request) SetHeader

func (r *Request) SetHeader(key string, value any)

SetHeader sets the value of a header field.

func (*Request) SetHeaders

func (r *Request) SetHeaders(h map[string]any)

SetHeaders ranges over the hash map and calls Request.SetHeader.

func (*Request) SetQuery

func (r *Request) SetQuery(q map[string]any)

SetQuery converts a map[string]any into a url.Values object and sets it as the URL query.

func (*Request) SetURL

func (r *Request) SetURL(base string, s ...any) error

SetURL creates a url.URL from the given base and path parameters and sets it as the URL.

type Response

type Response struct {
	Request        *Request       `json:"request,omitempty"`
	Body           []byte         `json:"body,omitempty"`
	BodyMap        map[string]any `json:"-"`
	*http.Response `json:"-"`
}

Response is a wrapper around http.Response with an already read body.

func (*Response) JSON

func (r *Response) JSON(v any) error

JSON decodes the body and stores it into the value pointed by v.

func (*Response) Map

func (r *Response) Map() (map[string]any, error)

Map decodes the body into map[string]any.

type Side

type Side struct {
	Direction BookDirection
	High      *Level
	Low       *Level
	Last      *Level
	Levels    *Map[string, Level]
	// contains filtered or unexported fields
}

Side encompasses the price levels in one side of the book.

func NewSide

func NewSide() *Side

NewSide constructs a new Side with default values.

func (*Side) FindAdjacent

func (s *Side) FindAdjacent(price *Money) *Level

FindAdjacent finds the nearest price level close to the given price.

func (*Side) FindAdjacentAbove

func (s *Side) FindAdjacentAbove(price *Money) *Level

FindAdjacentAbove finds the nearest price level above the given price.

func (*Side) FindAdjacentBelow

func (s *Side) FindAdjacentBelow(price *Money) *Level

FindAdjacentBelow finds the nearest price level from below the given price.

func (*Side) Update

func (s *Side) Update(opts *BookUpdateOptions)

Update interprets a BookUpdateOptions message and decides if it should add, update, or delete the price level.

type WebSocket

type WebSocket struct {
	Reconnect     func()
	ReconnectWait time.Duration
	DoReconnect   bool

	OnConnected    *CallbackManager[any]
	OnDisconnected *CallbackManager[error]
	OnSent         *CallbackManager[*WebSocketMessage]
	OnReceived     *CallbackManager[*WebSocketMessage]

	URL string

	Insecure bool
	// contains filtered or unexported fields
}

WebSocket implements a common structure for the WebSocket APIs.

func NewWebSocket

func NewWebSocket() *WebSocket

NewWebSocket creates a new WebSocket object with default values.

func (*WebSocket) Connect

func (ws *WebSocket) Connect() error

Connect establishes a connection.

func (*WebSocket) Disconnect

func (ws *WebSocket) Disconnect() error

Disconnect stops the connection.

func (*WebSocket) IsActive

func (ws *WebSocket) IsActive() bool

IsActive returns the status of the connection.

func (*WebSocket) WriteJSON

func (ws *WebSocket) WriteJSON(message any) error

WriteJSON submits a message to the connection.

func (*WebSocket) WriteMessage

func (ws *WebSocket) WriteMessage(messageType int, data []byte) error

WriteMessage submits a raw message to the connection.

type WebSocketMessage

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

func NewWebSocketMessage

func NewWebSocketMessage(d []byte) *WebSocketMessage

func (*WebSocketMessage) Bytes

func (m *WebSocketMessage) Bytes() []byte

func (*WebSocketMessage) JSON

func (m *WebSocketMessage) JSON(v any) error

func (*WebSocketMessage) Map

func (m *WebSocketMessage) Map() (map[string]any, error)

func (*WebSocketMessage) String

func (m *WebSocketMessage) String() string

Jump to

Keyboard shortcuts

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