krakenspot

package
v0.0.0-...-aeb4b38 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2024 License: GPL-3.0 Imports: 26 Imported by: 1

Documentation

Overview

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The batchorder.go file provides the BatchOrder struct and associated methods for handling batch orders in the Kraken Spot Trading API. This file is specifically used for the authenticated AddOrderBatch method from the private-api.go file.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The constants.go file includes variables and constants user for managing connections, subscriptions, and interactions with the Kraken API. They include base URLs, WebSocket URLs, public and private channel names, order channel events, general message events, valid directions, and map sizes for pairs, assets, and tickers.

The API rate limiter constants are used to manage the rate of API calls to the Kraken server, ensuring that the application adheres to Kraken's rate limits. These include decay rates, maximum counters, and trading decay rates for different tiers.

Error definitions are also included to handle specific error scenarios that may occur during the operation of the application.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The data.go file specifically contains the data structure declarations for incoming Kraken WebSocket and REST API JSON messages. It also includes necessary custom json.Unmarshal functions where required. Additionally, it holds data structures for internal package features, playing a crucial role in managing and interpreting data from the Kraken Spot Exchange API.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The krakenclient.go file specifically contains the declaration of data structs for the client, the client constructor function, and a method to set an error logger. It plays a crucial role in establishing and managing interactions with Kraken's WebSocket server, including subscribing to public and private channels and sending orders.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The options.go file in this package implements the "functional options" pattern. It contains functions that provide optional configurations for both WebSocket and REST API methods throughout the package. These functions allow for flexible and clear configuration of various API calls, enhancing the usability and readability of the package. Each contains notes from Kraken's API docs where relevant and necessary cautions on mutual exclusivity between functions.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The private-api.go file contains functions that interact with both public and private endpoints of the Kraken API. These functions require the creation of a KrakenClient and include methods for querying system status, account information, and asset information, trading, etc. This file plays a crucial role in facilitating authenticated interactions with the Kraken API.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

This file, public-api.go, contains the implementation of the public REST API functions. Unlike other files in this package, they do not require the creation of a KrakenClient, making them suitable for quick and independent queries. Each function corresponds to a specific endpoint of Kraken's public API, and returns the data in a structured format for easy consumption.

Package krakenspot is a comprehensive toolkit for interfacing with the Kraken Spot Exchange API. It enables WebSocket and REST API interactions, including subscription to both public and private channels. The package provides a client for initiating these interactions and a state manager for handling them.

The websocket.go file specifically handles all interactions with Kraken's WebSocket server. This includes connecting, subscribing to public and private channels and sending orders among other operations. The code in this file is organized in sections, reflecting the order in which they would typically be called by an end user importing this package.

Index

Constants

This section is empty.

Variables

View Source
var ErrTooManyArgs = errors.New("too many arguments passed to function/method")
View Source
var ErrUnexpectedJSONInput = errors.New("error unmarshalling unexpected JSON input")

Functions

func GetAllAssetInfo

func GetAllAssetInfo() (*map[string]AssetInfo, error)

Calls Kraken API public market data "Assets" endpoint. Gets information about all assets that are available for deposit, withdrawal, trading and staking. Returns them as *map[string]AssetInfo where the string is the asset name.

func GetAllTickerInfo

func GetAllTickerInfo() (*map[string]TickerInfo, error)

Calls Kraken API public market data "Ticker" endpoint. Gets ticker info for all tradeable pairs.

Note: Today's prices start at midnight UTC

func GetTickerInfo

func GetTickerInfo(pair string) (*map[string]TickerInfo, error)

Calls Kraken API public market data "Ticker" endpoint. Accepts one argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

Note: Today's prices start at midnight UTC

func GetTradeablePairsFees

func GetTradeablePairsFees(pair ...string) (*map[string]AssetPairFees, error)

Calls Kraken API public market data "AssetPairs" endpoint with "fees" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func GetTradeablePairsInfo

func GetTradeablePairsInfo(pair ...string) (*map[string]AssetPairInfo, error)

Calls Kraken API public market data "AssetPairs" endpoint with default info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func GetTradeablePairsLeverage

func GetTradeablePairsLeverage(pair ...string) (*map[string]AssetPairLeverage, error)

Calls Kraken API public market data "AssetPairs" endpoint with "leverage" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func GetTradeablePairsMargin

func GetTradeablePairsMargin(pair ...string) (*map[string]AssetPairMargin, error)

Calls Kraken API public market data "AssetPairs" endpoint with "margin" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func ListAltNames

func ListAltNames() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pairs' altnames. Sorted alphabetically.

func ListAssets

func ListAssets() ([]string, error)

Calls Kraken API public market data "Assets" endpoint. Returns a slice of strings of all tradeable asset names sorted alphabetically.

func ListTradeablePairs

func ListTradeablePairs() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pair names. Sorted alphabetically.

func ListWebsocketNames

func ListWebsocketNames() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pairs' websocket names. Sorted alphabetically.

func MapWebsocketNames

func MapWebsocketNames() (map[string]bool, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns map of all tradeable websocket names for fast lookup.

func SystemIsOnline

func SystemIsOnline() (bool, string)

Calls Kraken API public market data "SystemStatus" endpoint and returns true if system is online. Returns false and current status as a string if not online. Returns false and error if error produced from calling API.

Example Usage:

online, status := krakenspot.SystemIsOnline()
if !online {
	log.Println(status)
}

Types

type APIManager

type APIManager struct {
	HandleRateLimit  atomic.Bool
	APICounter       uint8
	MaxAPICounter    uint8
	APICounterDecay  uint8 // seconds per 1 counter decay
	CounterDecayCond *sync.Cond
	Mutex            sync.Mutex
}

REST API

type APREstimate

type APREstimate struct {
	High string `json:"high"`
	Low  string `json:"low"`
}

type AccountTransfer

type AccountTransfer struct {
	TransferID string `json:"transfer_id"`
	Status     string `json:"status"`
}

type AddOrderBatchOption

type AddOrderBatchOption func(payload url.Values)

func AddBatchWithDeadline

func AddBatchWithDeadline(deadline string) AddOrderBatchOption

Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching engine should reject the new order request to arg 'deadline'.

In presence of latency or order queueing: min now() + 2 seconds, max now() + 60 seconds.

func ValidateAddOrderBatch

func ValidateAddOrderBatch() AddOrderBatchOption

Validates inputs only. Do not submit order. Defaults to "false" if not called.

type AddOrderBatchResp

type AddOrderBatchResp struct {
	Orders []BatchResp `json:"orders"`
}

type AddOrderDescription

type AddOrderDescription struct {
	OrderDescription string `json:"order"`
	CloseDescription string `json:"close"`
}

type AddOrderOption

type AddOrderOption func(payload url.Values)

func AddWithDeadline

func AddWithDeadline(deadline string) AddOrderOption

Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching engine should reject the new order request to arg 'deadline'.

In presence of latency or order queueing: min now() + 2 seconds, max now() + 60 seconds.

Example Usage:

AddWithDeadline(time.Now().Add(time.Second*30).Format(time.RFC3339))

func CloseLimit

func CloseLimit(price string) AddOrderOption

Conditional close of "limit" order type where arg 'price' is the level at which the limit order will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseStopLoss

func CloseStopLoss(price string) AddOrderOption

Conditional close of "stop-loss" order type where arg 'price' is the stop loss trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseStopLossLimit

func CloseStopLossLimit(price, price2 string) AddOrderOption

Conditional close of "stop-loss-limit" order type where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseTakeProfit

func CloseTakeProfit(price string) AddOrderOption

Conditional close of "take-profit" order type where arg 'price' is the take profit trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseTakeProfitLimit

func CloseTakeProfitLimit(price, price2 string) AddOrderOption

Conditional close of "take-profit-limit" order type where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseTrailingStop

func CloseTrailingStop(price string) AddOrderOption

Conditional close of "trailing-stop" order type where arg 'price' is the relative stop trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func CloseTrailingStopLimit

func CloseTrailingStopLimit(price, price2 string) AddOrderOption

Conditional close of "trailing-stop-limit" order type where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format Close<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func DisplayVolume

func DisplayVolume(displayVol string) AddOrderOption

Used to create an iceberg order, this is the visible order quantity in terms of the base asset. The rest of the order will be hidden, although the full volume can be filled at any time by any order of that size or larger that matches in the order book. DisplayVolume() can only be used with the Limit() order type. Must be greater than 0, and less than AddOrder() arg 'volume'.

func FCIB

func FCIB() AddOrderOption

Prefer fee in base currency (default if selling)

CAUTION: Mutually exclusive with FCIQ(). Only call one of these two at a time

func FCIQ

func FCIQ() AddOrderOption

Prefer fee in quote currency (default if buying)

CAUTION: Mutually exclusive with FCIB(). Only call one of these two at a time

func GoodTilDate

func GoodTilDate(expireTime string) AddOrderOption

Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "GTD" (Good Til Date). GTD, if called, will cause the order to expire at specified unix time passed to arg 'expireTime'. Expiration time, can be specified as an absolute timestamp or as a number of seconds in the future:

0 no expiration (default)

<n> = unix timestamp of expiration time

+<n> = expire <n> seconds from now, minimum 5 seconds

Note: URL encoding of the + character changes it to a space, so please use %2b followed by the number of seconds instead of +

CAUTION: Mutually exclusive with ImmediateOrCancel(). Only one of these two functions should be called, if any. Order will still pass as valid but one "timeinforce" value will be overridden.

func ImmediateOrCancel

func ImmediateOrCancel() AddOrderOption

Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "IOC" (Immediate Or Cancel). IOC will immediately execute the amount possible and cancel any remaining balance rather than resting in the book. Defaults to "GTC" (Good 'Til Canceled) if function is not called.

CAUTION: Mutually exclusive with GoodTilDate(). Only one of these two functions should be called, if any. Order will still pass as valid but one "timeinforce" value will be overridden.

func IndexTrigger

func IndexTrigger() AddOrderOption

Price signal used to trigger stop-loss, stop-loss-limit, take-profit, take-profit-limit, trailing-stop and trailing-stop-limit orders. Defaults to "last" trigger type if not called. Calling this function overrides default to "index".

Note: This trigger type will also be used for any associated conditional close orders.

Note: To keep triggers serviceable, the last price will be used as fallback reference price during connectivity issues with external index feeds.

func Leverage

func Leverage(leverage string) AddOrderOption

Amount of leverage desired. Defaults to no leverage if function is not called. API accepts string of any number; in practice, must be some integer >= 2

Note: This function should not be used when calling AddOrder() with the SettlePosition() 'orderType'

func NOMPP

func NOMPP() AddOrderOption

Disables market price protection for market orders

func PostOnly

func PostOnly() AddOrderOption

Post-only order (available when ordertype = limit)

func ReduceOnly

func ReduceOnly() AddOrderOption

If true, order will only reduce a currently open position, not increase it or open a new position. Defaults to false if not passed.

Note: ReduceOnly() is only usable with leveraged orders. This includes orders of 'orderType' SettlePosition() and orders with Leverage() passed to 'options'

func STPCancelBoth

func STPCancelBoth() AddOrderOption

Sets self trade behavior to "cancel-both". Overrides default value when called. Default "cancel-newest"

CAUTION: Mutually exclusive with STPCancelOldest(). Only one of these two functions should be called, if any. Order will still pass as valid but one "stptype" value will be overridden.

Self trade prevention behavior definition:

"cancel-newest" - if self trade is triggered, arriving order will be canceled

"cancel-oldest" - if self trade is triggered, resting order will be canceled

"cancel-both" - if self trade is triggered, both arriving and resting orders will be canceled

func STPCancelOldest

func STPCancelOldest() AddOrderOption

Sets self trade behavior to "cancel-oldest". Overrides default value when called. Default "cancel-newest"

CAUTION: Mutually exclusive with STPCancelBoth(). Only one of these two functions should be called, if any. Order will still pass as valid but one "stptype" value will be overridden.

Self trade prevention behavior definition:

"cancel-newest" - if self trade is triggered, arriving order will be canceled

"cancel-oldest" - if self trade is triggered, resting order will be canceled

"cancel-both" - if self trade is triggered, both arriving and resting orders will be canceled

func UserRef

func UserRef(userRef string) AddOrderOption

User reference id 'userref' is an optional user-specified integer id that can be associated with any number of orders. Many clients choose a userref corresponding to a unique integer id generated by their systems (e.g. a timestamp). However, because we don't enforce uniqueness on our side, it can also be used to easily group orders by pair, side, strategy, etc. This allows clients to more readily cancel or query information about orders in a particular group, with fewer API calls by using userref instead of our txid, where supported.

func VIQC

func VIQC() AddOrderOption

Order volume expressed in quote currency. This is supported only for market orders.

func ValidateAddOrder

func ValidateAddOrder() AddOrderOption

Validates inputs only. Does not submit order. Defaults to "false" if not called.

type AddOrderResp

type AddOrderResp struct {
	Description AddOrderDescription `json:"descr"`
	TxID        []string            `json:"txid"`
}

type Allocation

type Allocation struct {
	Converted    string `json:"converted"`
	TimeCreated  string `json:"created_at"`
	TimeExpires  string `json:"expires"`
	NativeAmount string `json:"native"`
}

type AllocationStatus

type AllocationStatus struct {
	Pending bool `json:"pending"`
}

type AmountAllocated

type AmountAllocated struct {
	AllocationCount uint         `json:"allocation_count"`
	Allocations     []Allocation `json:"allocations"`
	ConvertedAmount string       `json:"converted"`
	NativeAmount    string       `json:"native"`
}

type ApiResp

type ApiResp struct {
	Error  []string    `json:"error"`
	Result interface{} `json:"result"`
}

type AssetInfo

type AssetInfo struct {
	Ticker          string
	Aclass          string  `json:"aclass"`
	Altname         string  `json:"altname"`
	Decimals        uint8   `json:"decimals"`
	DisplayDecimals uint8   `json:"display_decimals"`
	CollateralValue float32 `json:"collateral_value"`
	Status          string  `json:"status"`
}

func GetAssetInfo

func GetAssetInfo(asset string) (*AssetInfo, error)

Calls Kraken API public market data "Assets" endpoint. Gets information about specific asset passed to arg.

type AssetPairFees

type AssetPairFees struct {
	Ticker            string
	Fees              [][]float64 `json:"fees"`
	FeesMaker         [][]float64 `json:"fees_maker"`
	FeeVolumeCurrency string      `json:"fee_volume_currency"`
}

type AssetPairInfo

type AssetPairInfo struct {
	Ticker             string
	Altname            string      `json:"altname"`
	Wsname             string      `json:"wsname"`
	AclassBase         string      `json:"aclass_base"`
	Base               string      `json:"base"`
	AclassQuote        string      `json:"aclass_quote"`
	Quote              string      `json:"quote"`
	CostDecimals       uint8       `json:"cost_decimals"`
	PairDecimals       uint8       `json:"pair_decimals"`
	LotDecimals        uint8       `json:"lot_decimals"`
	LotMultiplier      uint8       `json:"lot_multiplier"`
	LeverageBuy        []uint8     `json:"leverage_buy"`
	LeverageSell       []uint8     `json:"leverage_sell"`
	Fees               [][]float64 `json:"fees"`
	FeesMaker          [][]float64 `json:"fees_maker"`
	FeeVolumeCurrency  string      `json:"fee_volume_currency"`
	MarginCall         uint8       `json:"margin_call"`
	MarginStop         uint8       `json:"margin_stop"`
	OrderMin           string      `json:"ordermin"`
	CostMin            string      `json:"costmin"`
	TickSize           string      `json:"tick_size"`
	Status             string      `json:"status"`
	LongPositionLimit  uint32      `json:"long_position_limit"`
	ShortPositionLimit uint32      `json:"short_position_limit"`
}

type AssetPairLeverage

type AssetPairLeverage struct {
	Ticker       string
	LeverageBuy  []uint8 `json:"leverage_buy"`
	LeverageSell []uint8 `json:"leverage_sell"`
}

type AssetPairMargin

type AssetPairMargin struct {
	Ticker      string
	MarginCall  uint8 `json:"margin_call"`
	MarginLevel uint8 `json:"margin_level"`
}

type Authenticator

type Authenticator interface {
	AuthenticateWebSockets() error
	GetSystemStatus() (*SystemStatus, error)
	// contains filtered or unexported methods
}

Authenticator is a field in WebSocketClient to hold a pointer to KrakenClient for access to authenticating token methods without creating circular depencies

type AutoCompound

type AutoCompound struct {
	Default bool   `json:"default"`
	Type    string `json:"type"`
}

type BalanceManager

type BalanceManager struct {
	Balances    map[string]decimal.Decimal
	CurrencyMap map[string]BaseQuoteCurrency
	// contains filtered or unexported fields
}

type BaseQuoteCurrency

type BaseQuoteCurrency struct {
	Base  string
	Quote string
}

type BatchOrder

type BatchOrder struct {
	UserRef       int32  `json:"userref,omitempty"`
	OrderType     string `json:"ordertype"` // Enum: "market", "limit", "stop-loss", "take-profit", "stop-loss-limit", "take-profit-limit", "settle-position"
	Direction     string `json:"type"`      // Enum: "buy", "sell"
	Volume        string `json:"volume"`    // Enum 'volume': >= 0. Note: 'volume' may be 0 for closing margin orders to automatically fill the requisite quantity.
	DisplayVolume string `json:"displayvol,omitempty"`
	Price         string `json:"price,omitempty"`
	Price2        string `json:"price2,omitempty"`
	Trigger       string `json:"trigger,omitempty"`
	Leverage      string `json:"leverage,omitempty"`
	ReduceOnly    bool   `json:"reduce_only,omitempty"`
	STPType       string `json:"stptype,omitempty"`
	OrderFlags    string `json:"oflags,omitempty"`
	TimeInForce   string `json:"timeinforce,omitempty"`
	StartTime     string `json:"starttm,omitempty"`
	ExpireTime    string `json:"expiretm,omitempty"`
}

func NewBatchOrder

func NewBatchOrder(orderType, direction, volume string) *BatchOrder

Constructor function to create new BatchOrder with required fields. Depending on value passed to arg 'orderType', Price and Price2 may also be required. Call with methods SetPrice() and SetPrice2() as necessary

Enum 'orderType': "market", "limit", "stop-loss", "take-profit", "stop-loss-limit", "take-profit-limit", "settle-position"

Enum 'direction': "buy", "sell"

Enum 'volume': >= 0. Note: 'volume' may be 0 for closing margin orders to automatically fill the requisite quantity.

func (*BatchOrder) SetDisplayVolume

func (bo *BatchOrder) SetDisplayVolume(displayVolume string) *BatchOrder

Used to create a iceberg orders, this is the visible order quantity in terms of the base asset. The rest of the order will be hidden, although the full volume can be filled at any time by any order of that size or larger that matches in the order book. displayvol can only be used with the limit order type, must be greater than 0, and less than volume.

func (*BatchOrder) SetExpireTime

func (bo *BatchOrder) SetExpireTime(expireTime string) *BatchOrder

Expiration time:

0 no expiration (default)

+<n> = expire seconds from now, minimum 5 seconds

<n> = unix timestamp of expiration time

func (*BatchOrder) SetLeverage

func (bo *BatchOrder) SetLeverage(leverage string) *BatchOrder

Amount of leverage desired (default: none)

func (*BatchOrder) SetOrderFlags

func (bo *BatchOrder) SetOrderFlags(orderFlags string) *BatchOrder

Comma delimited list of order flags. If multiple flags are desired, method must only be called once and flags put in a single comma delimited string.

Enum: "post", "fcib", "fciq", "nompp", "viqc"

func (*BatchOrder) SetPrice

func (bo *BatchOrder) SetPrice(price string) *BatchOrder

Price:

Limit price for limit orders or trigger price for stop-loss, stop-loss-limit, take-profit, and take-profit-limit orders

Notes:

Relative Prices: Either price or price2 can be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func (*BatchOrder) SetPrice2

func (bo *BatchOrder) SetPrice2(price2 string) *BatchOrder

Limit price for stop-loss-limit and take-profit-limit

Notes:

Relative Prices: Either price or price2 can be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func (*BatchOrder) SetReduceOnly

func (bo *BatchOrder) SetReduceOnly(reduceOnly bool) *BatchOrder

If true, order will only reduce a currently open position, not increase it or open a new position. Can only be used with leveraged positions

func (*BatchOrder) SetSTPType

func (bo *BatchOrder) SetSTPType(stpType string) *BatchOrder

Sets self trade prevention behaviour, defaults to "cancel-newest" if not called/

Enum: "cancel-newest", "cancel-oldest", "cancel-both"

func (*BatchOrder) SetStartTime

func (bo *BatchOrder) SetStartTime(startTime string) *BatchOrder

Scheduled start time, can be specified as an absolute timestamp or as a number of seconds in the future:

0 now (default)

+<n> schedule start time seconds from now

<n> = unix timestamp of start time

func (*BatchOrder) SetTimeInForce

func (bo *BatchOrder) SetTimeInForce(timeInForce string) *BatchOrder

Time-in-force of the order to specify how long it should remain in the order book before being cancelled. GTC (Good-'til-cancelled) is default if the parameter is omitted. IOC (immediate-or-cancel) will immediately execute the amount possible and cancel any remaining balance rather than resting in the book. "GTD" (good-'til-date), if specified, must be called with SetExpireTime() method.

Enum: "GTC", "IOC", "GTD"

func (*BatchOrder) SetTrigger

func (bo *BatchOrder) SetTrigger(trigger string) *BatchOrder

Price signal used to trigger stop-loss, stop-loss-limit, take-profit, and take-profit-limit orders

Note: To keep triggers serviceable, the last price will be used as fallback reference price during connectivity issues with external index feeds.

func (*BatchOrder) SetUserRef

func (bo *BatchOrder) SetUserRef(userRef int32) *BatchOrder

User reference id userref is an optional user-specified integer id that can be associated with any number of orders. Many clients choose a userref corresponding to a unique integer id generated by their systems (e.g. a timestamp). However, because we don't enforce uniqueness on our side, it can also be used to easily group orders by pair, side, strategy, etc. This allows clients to more readily cancel or query information about orders in a particular group, with fewer API calls by using userref instead of our txid, where supported.

type BatchOrderDescription

type BatchOrderDescription struct {
	OrderDescription string `json:"order"`
}

type BatchResp

type BatchResp struct {
	Description BatchOrderDescription `json:"descr"`
	Error       string                `json:"error"`
	TxID        string                `json:"txid"`
}

type BookEntry

type BookEntry struct {
	Price  string
	Volume string
	Time   uint64
}

func (*BookEntry) UnmarshalJSON

func (be *BookEntry) UnmarshalJSON(data []byte) error

type BookState

type BookState struct {
	Asks *[]InternalBookEntry
	Bids *[]InternalBookEntry
}

type CancelAllAfter

type CancelAllAfter struct {
	CurrentTime string `json:"currentTime"`
	TriggerTime string `json:"triggerTime"`
}

type CancelOrderResp

type CancelOrderResp struct {
	Count   int  `json:"count"`
	Pending bool `json:"pending"`
}

type ClosedOrdersResp

type ClosedOrdersResp struct {
	ClosedOrders map[string]Order `json:"closed"`
	Count        int              `json:"count"`
}

type DeleteReportResp

type DeleteReportResp struct {
	Delete bool `json:"delete"`
	Cancel bool `json:"cancel"`
}

type DepositAddress

type DepositAddress struct {
	Address    string      `json:"address"`
	ExpireTime string      `json:"expiretm"`
	New        bool        `json:"new"`
	Memo       string      `json:"memo"`
	Tag        interface{} `json:"tag"`
}

type DepositMethod

type DepositMethod struct {
	Method             string      `json:"method"`
	MinDeposit         string      `json:"minimum"`
	MaxDeposit         interface{} `json:"limit"`
	Fee                string      `json:"fee"`
	AddressSetupFee    string      `json:"address-setup-fee"`
	CanGenerateAddress bool        `json:"gen-address"`
}

type DepositStatus

type DepositStatus struct {
	Method         string      `json:"method"`
	AssetClass     string      `json:"aclass"`
	Asset          string      `json:"asset"`
	RefID          string      `json:"refid"`
	TxID           string      `json:"txid"`
	Info           string      `json:"info"`
	Amount         string      `json:"amount"`
	Fee            interface{} `json:"fee"`
	TimeRequested  int32       `json:"time"`
	Status         interface{} `json:"status"`
	StatusProperty string      `json:"status-prop"`
	Originators    []string    `json:"originators"`
}

type DepositStatusPaginated

type DepositStatusPaginated struct {
	Deposits   []DepositStatus `json:"deposits"`
	NextCursor string          `json:"next_cursor"`
}

type EarnAlloAmount

type EarnAlloAmount struct {
	Bonding   AmountAllocated `json:"bonding"`
	ExitQueue AmountAllocated `json:"exit_queue"`
	Pending   AmountAllocated `json:"pending"`
	Total     AmountAllocated `json:"total"`
	Unbonding AmountAllocated `json:"unbonding"`
}

type EarnAlloPayout

type EarnAlloPayout struct {
	AccumulatedReward EarnAlloReward `json:"accumulated_reward"`
	EstimatedReward   EarnAlloReward `json:"estimated_reward"`
	PeriodEnd         string         `json:"period_end"`
	PeriodStart       string         `json:"period_start"`
}

type EarnAlloReward

type EarnAlloReward struct {
	ConvertedAmount string `json:"converted"`
	NativeAmount    string `json:"native"`
}

type EarnAllocation

type EarnAllocation struct {
	AmountAllocated EarnAlloAmount `json:"amount_allocated"`
	NativeAsset     string         `json:"native_asset"`
	Payout          EarnAlloPayout `json:"payout"`
	StrategyID      string         `json:"strategy_id"`
	TotalReward     EarnAlloReward `json:"total_rewarded"`
}

type EarnAllocationsResp

type EarnAllocationsResp struct {
	ConvertedAsset string           `json:"converted_asset"`
	Allocations    []EarnAllocation `json:"items"`
	TotalAllocated string           `json:"total_allocated"`
	TotalRewarded  string           `json:"total_rewarded"`
}

type EarnStrategiesResp

type EarnStrategiesResp struct {
	Strategies []EarnStrategy `json:"items"`
	NextCursor string         `json:"next_cursor"`
}

type EarnStrategy

type EarnStrategy struct {
	Asset             string       `json:"asset"`
	AllocationFee     interface{}  `json:"allocation_fee"`
	RestrictionInfo   []string     `json:"allocation_restriction_info"`
	APREstimate       APREstimate  `json:"apr_estimate"`
	AutoCompound      AutoCompound `json:"auto_compound"`
	CanAllocate       bool         `json:"can_allocate"`
	CanDeallocate     bool         `json:"can_deallocate"`
	DeallocationFee   interface{}  `json:"deallocation_fee"`
	ID                string       `json:"id"`
	LockType          LockType     `json:"lock_type"`
	UserCap           string       `json:"user_cap"`
	UserMinAllocation string       `json:"user_min_allocation"`
	YieldSource       YieldSource  `json:"yield_source"`
}

type EditOrderDescription

type EditOrderDescription struct {
	OrderDescription string `json:"order"`
}

type EditOrderOption

type EditOrderOption func(payload url.Values)

func NewCancelResponse

func NewCancelResponse() EditOrderOption

Used to interpret if client wants to receive pending replace, before the order is completely replaced. Defaults to "false" if not called.

func NewDeadline

func NewDeadline(deadline string) EditOrderOption

RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching engine should reject the new order request, in presence of latency or order queueing. min now() + 2 seconds, max now() + 60 seconds.

func NewDisplayVolume

func NewDisplayVolume(displayVol string) EditOrderOption

Used to edit an iceberg order, this is the visible order quantity in terms of the base asset. The rest of the order will be hidden, although the full volume can be filled at any time by any order of that size or larger that matches in the order book. displayvol can only be used with the limit order type, must be greater than 0, and less than volume.

func NewPostOnly

func NewPostOnly() EditOrderOption

Post-only order (available when ordertype = limit). All the flags from the parent order are retained except post-only. Post-only needs to be explicitly mentioned on every edit request.

func NewPrice

func NewPrice(price string) EditOrderOption

Updates limit price for "limit" orders. Updates trigger price for "stop-loss", "stop-loss-limit", "take-profit", "take-profit-limit", "trailing-stop" and "trailing-stop-limit" orders

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

Trailing Stops: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

func NewPrice2

func NewPrice2(price2 string) EditOrderOption

Updates limit price for "stop-loss-limit", "take-profit-limit" and "trailing-stop-limit" orders

Trailing Stops Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

func NewUserRef

func NewUserRef(userRef string) EditOrderOption

Field "userref" is an optional user-specified integer id associated with edit request.

Note: userref from parent order will not be retained on the new order after edit.

func NewVolume

func NewVolume(volume string) EditOrderOption

Updates order quantity in terms of the base asset.

func ValidateEditOrder

func ValidateEditOrder() EditOrderOption

Validate inputs only. Do not submit order. Defaults to false if not called.

type EditOrderResp

type EditOrderResp struct {
	Description        EditOrderDescription `json:"descr"`
	NewTxID            string               `json:"txid"`
	Volume             string               `json:"volume"`
	Price              string               `json:"price"`
	Price2             string               `json:"price2"`
	NewUserRef         int                  `json:"newuserref"`
	OldUserRef         int                  `json:"olduserref"`
	NumOrdersCancelled uint8                `json:"orders_cancelled"`
	OldTxID            string               `json:"originaltxid"`
	Status             string               `json:"status"`
	ErrorMessage       string               `json:"error_message"`
}

type ExportReportStatus

type ExportReportStatus struct {
	ID            string `json:"id"`
	Description   string `json:"descr"`
	Format        string `json:"format"`
	Report        string `json:"report"`
	SubType       string `json:"subtype"`
	Status        string `json:"status"`
	Fields        string `json:"fields"`
	CreatedTime   string `json:"createdtm"`
	StartTime     string `json:"starttm"`
	CompletedTime string `json:"completedtm"`
	DataStartTime string `json:"datastarttm"`
	DataEndTime   string `json:"dataendtm"`
	Asset         string `json:"asset"`
}

type ExtendedBalance

type ExtendedBalance struct {
	Balance    string `json:"balance"`
	Credit     string `json:"credit"`
	CreditUsed string `json:"credit_used"`
	HoldTrade  string `json:"hold_trade"`
}

type Fee

type Fee struct {
	Fee        string `json:"fee"`
	MinFee     string `json:"min_fee"`
	MaxFee     string `json:"max_fee"`
	NextFee    string `json:"next_fee"`
	TierVolume string `json:"tier_volume"`
	NextVolume string `json:"next_volume"`
}

type GenericArrayMessage

type GenericArrayMessage struct {
	ChannelName string
	Content     interface{}
}

func (*GenericArrayMessage) UnmarshalJSON

func (gm *GenericArrayMessage) UnmarshalJSON(data []byte) error

type GenericCallback

type GenericCallback func(data interface{})

type GenericMessage

type GenericMessage struct {
	Event   string `json:"event"`
	Content interface{}
}

func (*GenericMessage) UnmarshalJSON

func (gm *GenericMessage) UnmarshalJSON(data []byte) error

type GetClosedOrdersOption

type GetClosedOrdersOption func(payload url.Values)

For *KrakenClient method GetOpenOrders()

func COWithCloseTime

func COWithCloseTime(closeTime string) GetClosedOrdersOption

Which time to use to search and filter results for COWithStart() and COWithEnd() Defaults to "both" if not called or invalid arg 'closeTime' passed

Enum: "open", "close", "both"

func COWithConsolidateTaker

func COWithConsolidateTaker(consolidateTaker bool) GetClosedOrdersOption

Whether or not to consolidate trades by individual taker trades. Defaults to true if not called

func COWithEnd

func COWithEnd(end int) GetClosedOrdersOption

Ending unix timestamp or order tx ID of results (exclusive). If an order's tx ID is given for start or end time, the order's opening time (opentm) is used Defaults to show most recent orders if not called

func COWithOffset

func COWithOffset(offset int) GetClosedOrdersOption

Result offset for pagination. Defaults to no offset if not called

func COWithStart

func COWithStart(start int) GetClosedOrdersOption

Starting unix timestamp or order tx ID of results (exclusive). If an order's tx ID is given for start or end time, the order's opening time (opentm) is used. Defaults to show most recent orders if not called

func COWithTrades

func COWithTrades(trades bool) GetClosedOrdersOption

Whether or not to include trades related to position in output. Defaults to false if not called

func COWithUserRef

func COWithUserRef(userRef int) GetClosedOrdersOption

Restrict results to given user reference id. Defaults to no restrictions if not called

type GetDepositAddressesOption

type GetDepositAddressesOption func(payload url.Values)

For *KrakenClient method GetDepositAddresses()

func DAWithAmount

func DAWithAmount(amount string) GetDepositAddressesOption

Amount you wish to deposit (only required for method=Bitcoin Lightning)

func DAWithNew

func DAWithNew() GetDepositAddressesOption

Whether or not to generate a new address. Defaults to false if function is not called.

type GetDepositMethodsOption

type GetDepositMethodsOption func(payload url.Values)

For *KrakenClient method GetDepositMethods()

func DMWithAssetClass

func DMWithAssetClass(aclass string) GetDepositMethodsOption

Asset class being deposited (optional). Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

type GetDepositsStatusOption

type GetDepositsStatusOption func(payload url.Values)

For *KrakenClient method GetDepositsStatus()

func DSWithAsset

func DSWithAsset(asset string) GetDepositsStatusOption

Filter for specific asset being deposited

func DSWithAssetClass

func DSWithAssetClass(aclass string) GetDepositsStatusOption

Filter asset class being deposited. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func DSWithEnd

func DSWithEnd(end string) GetDepositsStatusOption

End timestamp, deposits created strictly after will be not be included in the response

func DSWithLimit

func DSWithLimit(limit uint) GetDepositsStatusOption

Number of results to include per page

func DSWithMethod

func DSWithMethod(method string) GetDepositsStatusOption

Filter for specific name of deposit method

func DSWithStart

func DSWithStart(start string) GetDepositsStatusOption

Start timestamp, deposits created strictly before will not be included in the response

type GetDepositsStatusPaginatedOption

type GetDepositsStatusPaginatedOption func(payload url.Values)

For *KrakenClient method GetDepositsStatusPaginated()

func DPWithAsset

func DPWithAsset(asset string) GetDepositsStatusPaginatedOption

Filter for specific asset being deposited

func DPWithAssetClass

func DPWithAssetClass(aclass string) GetDepositsStatusPaginatedOption

Filter asset class being deposited. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func DPWithEnd

End timestamp, deposits created strictly after will be not be included in the response

func DPWithLimit

func DPWithLimit(limit uint) GetDepositsStatusPaginatedOption

Number of results to include per page

func DPWithMethod

func DPWithMethod(method string) GetDepositsStatusPaginatedOption

Filter for specific name of deposit method

func DPWithStart

func DPWithStart(start string) GetDepositsStatusPaginatedOption

Start timestamp, deposits created strictly before will not be included in the response

type GetEarnAllocationsOption

type GetEarnAllocationsOption func(payload url.Values)

func EAWithAscending

func EAWithAscending() GetEarnAllocationsOption

Sorts strategies by ascending. Defaults to false (descending) if function is not called

func EAWithConvertedAsset

func EAWithConvertedAsset(asset string) GetEarnAllocationsOption

A secondary currency to express the value of your allocations. Defaults to express value in USD if function is not called

func EAWithHideZeroAllocations

func EAWithHideZeroAllocations() GetEarnAllocationsOption

Omit entries for strategies that were used in the past but now they don't hold any allocation. Defaults to false (don't omit) if function is not called

type GetEarnStrategiesOption

type GetEarnStrategiesOption func(payload url.Values)

func ESWithAscending

func ESWithAscending() GetEarnStrategiesOption

Sorts strategies by ascending. Defaults to false (descending) if function is not called

func ESWithAsset

func ESWithAsset(asset string) GetEarnStrategiesOption

Filter strategies by asset name. Defaults to no filter if function not called

func ESWithCursor

func ESWithCursor(cursor string) GetEarnStrategiesOption

Sets page ID to display results. Defaults to beginning/end (depending on sorting set by ESWithAscending()) if function not called.

func ESWithLimit

func ESWithLimit(limit uint16) GetEarnStrategiesOption

Sets number of items to return per page. Note that the limit may be cap'd to lower value in the application code.

func ESWithLockType

func ESWithLockType(lockTypes []string) GetEarnStrategiesOption

Filters displayed strategies by lock type. Accepts array of strings for arg 'lockTypes' and ignores invalid values passed. Defaults to no filter if function not called or only invalid values passed.

Enum - 'lockTypes': "flex", "bonded", "timed", "instant"

type GetLedgerOption

type GetLedgerOption func(payload url.Values)

func GLWithTrades

func GLWithTrades(trades bool) GetLedgerOption

Whether or not to include trades related to position in output. Defaults to false if not called.

type GetLedgersInfoOption

type GetLedgersInfoOption func(payload url.Values)

func LIWithAclass

func LIWithAclass(aclass string) GetLedgersInfoOption

Filter output by asset class. Defaults to "currency" if not called

Enum: "currency", ...?

func LIWithAsset

func LIWithAsset(asset string) GetLedgersInfoOption

// Filter output by asset or comma delimited list of assets. Defaults to "all" if not called.

func LIWithEnd

func LIWithEnd(end int) GetLedgersInfoOption

Ending unix timestamp or ledger ID of results (inclusive). Defaults to most recent ledgers if not called.

func LIWithOffset

func LIWithOffset(offset int) GetLedgersInfoOption

Result offset for pagination. Defaults to no offset if not called.

func LIWithStart

func LIWithStart(start int) GetLedgersInfoOption

Starting unix timestamp or ledger ID of results (exclusive). Defaults to most recent ledgers if not called.

func LIWithType

func LIWithType(ledgerType string) GetLedgersInfoOption

Type of ledger to retrieve. Defaults to "all" if not called or invalid 'ledgerType' passed.

Enum: "all", "trade", "deposit", "withdrawal", "transfer", "margin", "adjustment", "rollover", "credit", "settled", "staking", "dividend", "sale", "nft_rebate"

func LIWithoutCount

func LIWithoutCount(withoutCount bool) GetLedgersInfoOption

If true, does not retrieve count of ledger entries. Request can be noticeably faster for users with many ledger entries as this avoids an extra database query. Defaults to false if not called.

type GetOpenOrdersOption

type GetOpenOrdersOption func(payload url.Values)

For *KrakenClient method GetOpenOrders()

func OOWithTrades

func OOWithTrades(trades bool) GetOpenOrdersOption

Whether or not to include trades related to position in output. Defaults to false if not called

func OOWithUserRef

func OOWithUserRef(userRef int) GetOpenOrdersOption

Restrict results to given user reference id. Defaults to no restrictions if not called

type GetOpenPositionsConsolidatedOption

type GetOpenPositionsConsolidatedOption func(payload url.Values)

func OPCWithDoCalcs

func OPCWithDoCalcs(doCalcs bool) GetOpenPositionsConsolidatedOption

Whether to include P&L calculations. Defaults to false if not called

func OPCWithTxID

Comma delimited list of txids to limit output to. Defaults to show all open positions if not called

type GetOpenPositionsOption

type GetOpenPositionsOption func(payload url.Values)

func OPWithDoCalcs

func OPWithDoCalcs(doCalcs bool) GetOpenPositionsOption

Whether to include P&L calculations. Defaults to false if not called

func OPWithTxID

func OPWithTxID(txID string) GetOpenPositionsOption

Comma delimited list of txids to limit output to. Defaults to show all open positions if not called

type GetOrdersInfoOption

type GetOrdersInfoOption func(payload url.Values)

func OIWithConsolidateTaker

func OIWithConsolidateTaker(consolidateTaker bool) GetOrdersInfoOption

Whether or not to consolidate trades by individual taker trades. Defaults to true if not called

func OIWithTrades

func OIWithTrades(trades bool) GetOrdersInfoOption

Whether or not to include trades related to position in output. Defaults to false if not called

func OIWithUserRef

func OIWithUserRef(userRef int) GetOrdersInfoOption

Restrict results to given user reference id. Defaults to no restrictions if not called

type GetTradeInfoOption

type GetTradeInfoOption func(payload url.Values)

func TIWithTrades

func TIWithTrades(trades bool) GetTradeInfoOption

Whether or not to include trades related to position in output. Defaults to false if not called

type GetTradeVolumeOption

type GetTradeVolumeOption func(payload url.Values)

func TVWithPair

func TVWithPair(pair string) GetTradeVolumeOption

Comma delimited list of asset pairs to get fee info on. Defaults to show none if not called.

type GetTradesHistoryOption

type GetTradesHistoryOption func(payload url.Values)

func THWithConsolidateTaker

func THWithConsolidateTaker(consolidateTaker bool) GetTradesHistoryOption

Whether or not to consolidate trades by individual taker trades. Defaults to true if not called

func THWithEnd

func THWithEnd(end int) GetTradesHistoryOption

Ending unix timestamp or order tx ID of results (exclusive). If an order's tx ID is given for start or end time, the order's opening time (opentm) is used Defaults to show most recent orders if not called

func THWithOffset

func THWithOffset(offset int) GetTradesHistoryOption

Result offset for pagination. Defaults to no offset if not called

func THWithStart

func THWithStart(start int) GetTradesHistoryOption

Starting unix timestamp or order tx ID of results (exclusive). If an order's tx ID is given for start or end time, the order's opening time (opentm) is used. Defaults to show most recent orders if not called

func THWithTrades

func THWithTrades(trades bool) GetTradesHistoryOption

Whether or not to include trades related to position in output. Defaults to false if not called

func THWithType

func THWithType(tradeType string) GetTradesHistoryOption

Type of trade. Defaults to "all" if not called or invalid 'tradeType' passed.

Enum: "all", "any position", "closed position", "closing position", "no position"

type GetWithdrawalAddressesOption

type GetWithdrawalAddressesOption func(payload url.Values)

For *KrakenClient method GetWithdrawalAddresses()

func WAWithAsset

func WAWithAsset(asset string) GetWithdrawalAddressesOption

Filter addresses for specific asset

func WAWithAssetClass

func WAWithAssetClass(aclass string) GetWithdrawalAddressesOption

Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func WAWithKey

func WAWithKey(key string) GetWithdrawalAddressesOption

Find address for by withdrawal key name, as set up on your account

func WAWithMethod

func WAWithMethod(method string) GetWithdrawalAddressesOption

Filter addresses for specific method

func WAWithVerified

func WAWithVerified(verified bool) GetWithdrawalAddressesOption

Filter by verification status of the withdrawal address. Withdrawal addresses successfully completing email confirmation will have a verification status of true.

type GetWithdrawalMethodsOption

type GetWithdrawalMethodsOption func(payload url.Values)

For *KrakenClient method GetWithdrawalMethods()

func WMWithAsset

func WMWithAsset(asset string) GetWithdrawalMethodsOption

Filter methods for specific asset. Defaults to no filter if function is not called

func WMWithAssetClass

func WMWithAssetClass(aclass string) GetWithdrawalMethodsOption

Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func WMWithNetwork

func WMWithNetwork(network string) GetWithdrawalMethodsOption

Filter methods for specific network. Defaults to no filter if function is not called

type GetWithdrawalsStatusOption

type GetWithdrawalsStatusOption func(payload url.Values)

For *KrakenClient method GetWithdrawalsStatus()

func WSWithAsset

func WSWithAsset(asset string) GetWithdrawalsStatusOption

Filter for specific asset being withdrawn

func WSWithAssetClass

func WSWithAssetClass(aclass string) GetWithdrawalsStatusOption

Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func WSWithEnd

func WSWithEnd(end string) GetWithdrawalsStatusOption

End timestamp, withdrawals created strictly after will be not be included in the response

func WSWithMethod

func WSWithMethod(method string) GetWithdrawalsStatusOption

Filter for specific name of withdrawal method

func WSWithStart

func WSWithStart(start string) GetWithdrawalsStatusOption

Start timestamp, withdrawals created strictly before will not be included in the response

type GetWithdrawalsStatusPaginatedOption

type GetWithdrawalsStatusPaginatedOption func(payload url.Values)

For *KrakenClient method GetWithdrawalsStatusPaginated()

func WPWithAsset

Filter for specific asset being withdrawn

func WPWithAssetClass

func WPWithAssetClass(aclass string) GetWithdrawalsStatusPaginatedOption

Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"

func WPWithEnd

End timestamp, withdrawals created strictly after will be not be included in the response

func WPWithLimit

func WPWithLimit(limit int) GetWithdrawalsStatusPaginatedOption

Number of results to include per page. Defaults to 500 if function is not called

func WPWithMethod

func WPWithMethod(method string) GetWithdrawalsStatusPaginatedOption

Filter for specific name of withdrawal method

func WPWithStart

Start timestamp, withdrawals created strictly before will not be included in the response

type InternalBookEntry

type InternalBookEntry struct {
	Price  decimal.Decimal
	Volume decimal.Decimal
	Time   decimal.Decimal
}

type InternalOrderBook

type InternalOrderBook struct {
	Asks           []InternalBookEntry
	Bids           []InternalBookEntry
	DataChan       chan WSBookUpdateResp
	DoneChan       chan struct{}
	DataChanClosed int32
	DoneChanClosed int32
	PriceDecimals  int32
	VolumeDecimals int32
	Mutex          sync.RWMutex
}

type KrakenClient

type KrakenClient struct {
	APIKey      string
	APISecret   []byte
	Client      *http.Client
	ErrorLogger *log.Logger

	*APIManager
	*WebSocketManager
	// contains filtered or unexported fields
}

func NewKrakenClient

func NewKrakenClient(apiKey, apiSecret string, verificationTier uint8, autoReconnect ...bool) (*KrakenClient, error)

Creates new authenticated client KrakenClient for Kraken API with keys passed to args 'apiKey' and 'apiSecret'. Constructor requires 'verificationTier', but this value is only used if any self rate-limiting features are activated with either StartRESTRateLimiter() or StartTradingRateLimiter(). Accepts up to one optional boolean arg passed to 'reconnect' which will cause client to attempt reconnect, reauthenticate (if applicable), and resubscribe to all WebSocket channels if connection is lost. Defaults to true if not passed.

Verification Tiers:

1. Starter

2. Intermediate

3. Pro

Enum:

'verificationTier': [1..3]

func (*KrakenClient) AccountTransfer

func (kc *KrakenClient) AccountTransfer(asset string, amount string, fromAccount string, toAccount string) (*AccountTransfer, error)

Calls Kraken API private Subaccounts "AccountTransfer" endpoint. Transfer funds to and from master and subaccounts.

Note: AccountTransfer must be called by the master account.

Note: Subaccounts are currently only available to institutional clients. Please contact your Account Manager for more details.

Required Permissions:

Institutional verification;

Example Usage:

transfer, err := kc.AccountTransfer("XBT", "1.0", "ABCD 1234 EFGH 5678", "IJKL 0987 MNOP 6543")

func (*KrakenClient) AddOrder

func (kc *KrakenClient) AddOrder(orderType OrderType, direction, volume, pair string, options ...AddOrderOption) (*AddOrderResp, error)

Calls Kraken API private Trading "AddOrder" endpoint. Creates a new order of type arg 'orderType' with direction or side passed to arg 'direction' and size/quantity passed to arg 'volume' for the specified market passed to arg 'pair'. Accepts any number of functional options passed to arg 'options' to modify behavior or add additional constraints to orders.

Enums:

'orderType': See list "OrderType functions" below for possible functions to pass to this arg. Must use only one.

'direction': "buy", "sell"

'volume': >= 0

'pair': Call public market data endpoint function ListTradeablePairs() for a current list of possible values to pass to this arg

'options': See list "Functional Options" below for possible functions to pass to this arg. Can pass none or many, though some may conflict with eachother and/or conflict with the 'orderType' passed.

CAUTION: Conflicting 'options' args passed may not always result in an invalid order (resulting in an error from Kraken's API). Sometimes, they will overwrite eachother's values depending on the order passed to AddOrder() method and the order will be sent. See the docs marked with "CAUTION" in options.go for further information on specific conflicts.

Required Permissions:

Orders and trades - Create & modify orders;

OrderType functions:

Note: See options.go for complete docstrings with applicable general notes for each order type function.

// Instantly market orders in at best current prices
func Market() OrderType

// Order type of "limit" where arg 'price' is the level at which the limit order
// will be placed...
func Limit(price string) OrderType

// Order type of "stop-loss" order type where arg 'price' is the stop loss
// trigger price...
func StopLoss(price string) OrderType

// Order type of "take-profit" where arg 'price' is the take profit trigger price...
func TakeProfit(price string) OrderType

// Order type of "stop-loss-limit" where arg 'price' is the stop loss trigger
// price and arg 'price2' is the limit order that will be placed...
func StopLossLimit(price, price2 string) OrderType

// Order type of "take-profit-limit" where arg 'price' is the take profit trigger
// price and arg 'price2' is the limit order that will be placed...
func TakeProfitLimit(price, price2 string) OrderType

// Order type of "trailing-stop" where arg 'price' is the relative stop trigger
// price...
func TrailingStop(price string) OrderType

// Order type of "trailing-stop-limit" where arg 'price' is the relative stop
// trigger price and arg 'price2' is the limit order that will be placed...
func TrailingStopLimit(price, price2 string) OrderType

// Order type of "settle-position". Settles any open margin position of same
// 'direction' and 'pair' by amount 'volume'...
func SettlePosition(leverage string)

Functional Options:

Note: See options.go for complete docstrings with further notes on some functions and applicable general notes for each close order type function.

// User reference id 'userref' is an optional user-specified integer id that
// can be associated with any number of orders. Many clients choose a userref
// corresponding to a unique integer id generated by their systems (e.g. a
// timestamp). However, because we don't enforce uniqueness on our side, it
// can also be used to easily group orders by pair, side, strategy, etc. This
// allows clients to more readily cancel or query information about orders in
// a particular group, with fewer API calls by using userref instead of our
// txid, where supported.
func UserRef(userRef string) AddOrderOption

// Used to create an iceberg order, this is the visible order quantity in terms
// of the base asset. The rest of the order will be hidden, although the full
// volume can be filled at any time by any order of that size or larger that
// matches in the order book. DisplayVolume() can only be used with the Limit()
// order type. Must be greater than 0, and less than AddOrder() arg 'volume'.
func DisplayVolume(displayVol string) AddOrderOption

// Price signal used to trigger stop-loss, stop-loss-limit, take-profit,
// take-profit-limit, trailing-stop and trailing-stop-limit orders. Defaults to
// "last" trigger type if not called. Calling this function overrides default to
// "index".
//
// Note: This trigger type will also be used for any associated conditional
// close orders.
//
// Note: To keep triggers serviceable, the last price will be used as fallback
// reference price during connectivity issues with external index feeds.
func IndexTrigger() AddOrderOption

// Amount of leverage desired. Defaults to no leverage if function is not called.
// API accepts string of any number; in practice, must be some integer >= 2...
func Leverage(leverage string) AddOrderOption

// If true, order will only reduce a currently open position, not increase it
// or open a new position. Defaults to false if not passed.
//
// Note: ReduceOnly() is only usable with leveraged orders. This includes orders
// of 'orderType' SettlePosition() and orders with Leverage() passed to 'options'
func ReduceOnly() AddOrderOption

// Sets self trade behavior to "cancel-oldest". Overrides default value when called.
// Default "cancel-newest"...
//
// CAUTION: Mutually exclusive with STPCancelBoth()
func STPCancelOldest() AddOrderOption

// Sets self trade behavior to "cancel-both". Overrides default value when called.
// Default "cancel-newest"...
//
// CAUTION: Mutually exclusive with STPCancelOldest()
func STPCancelBoth() AddOrderOption

// Post-only order (available when ordertype = limit)
func PostOnly() AddOrderOption

// Prefer fee in base currency (default if selling)
//
// CAUTION: Mutually exclusive with FCIQ().
func FCIB() AddOrderOption

// Prefer fee in quote currency (default if buying)
//
// CAUTION: Mutually exclusive with FCIB().
func FCIQ() AddOrderOption

// Disables market price protection for market orders
func NOMPP() AddOrderOption

// Order volume expressed in quote currency. This is supported only for market orders.
func VIQC() AddOrderOption

// Time-in-force of the order to specify how long it should remain in the order
// book before being cancelled. Overrides default value with "IOC" (Immediate Or
// Cancel). IOC will immediately execute the amount possible and cancel any
// remaining balance rather than resting in the book. Defaults to "GTC" (Good
// 'Til Canceled) if function is not called.
//
// CAUTION: Mutually exclusive with GoodTilDate().
func ImmediateOrCancel() AddOrderOption

// Time-in-force of the order to specify how long it should remain in the order
// book before being cancelled. Overrides default value with "GTD" (Good Til Date).
// GTD, if called, will cause the order to expire at specified unix time passed
// to arg 'expireTime'. Expiration time, can be specified as an absolute timestamp
// or as a number of seconds in the future...
//
// CAUTION: Mutually exclusive with ImmediateOrCancel().
func GoodTilDate(expireTime string) AddOrderOption

// Conditional close of "limit" order type where arg 'price' is the level at which the limit order will be placed...

// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseLimit(price string) AddOrderOption

// Conditional close of "stop-loss" order type where arg 'price' is the stop
// loss trigger price...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseStopLoss(price string) AddOrderOption

// Conditional close of "take-profit" order type where arg 'price' is the take
// profit trigger price...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseTakeProfit(price string) AddOrderOption

// Conditional close of "stop-loss-limit" order type where arg 'price' is the
// stop loss trigger price and arg 'price2' is the limit order that will be placed...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseStopLossLimit(price, price2 string) AddOrderOption

// Conditional close of "take-profit-limit" order type where arg 'price' is the
// take profit trigger price and arg 'price2' is the limit order that will be
// placed...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseTakeProfitLimit(price, price2 string) AddOrderOption

// Conditional close of "trailing-stop" order type where arg 'price' is the relative
// stop trigger price...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseTrailingStop(price string) AddOrderOption

// Conditional close of "trailing-stop-limit" order type where arg 'price' is the
// relative stop trigger price and arg 'price2' is the limit order that will be
// placed...
//
// CAUTION: Mutually exclusive with all conditional close orders with format
// Close<orderType>()
func CloseTrailingStopLimit(price, price2 string) AddOrderOption

// Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching
// engine should reject the new order request to arg 'deadline'...
func AddWithDeadline(deadline string) AddOrderOption

// Validates inputs only. Do not submit order. Defaults to "false" if not called.
func ValidateAddOrder() AddOrderOption

Example Usage:

newOrder, err := kc.AddOrder(krakenspot.Limit("45000"), "buy", "1.0", "XXBTZUSD", krakenspot.PostOnly(), krakenspot.CloseLimit("49000"))

func (*KrakenClient) AddOrderBatch

func (kc *KrakenClient) AddOrderBatch(orders []BatchOrder, pair string, options ...AddOrderBatchOption) (*AddOrderBatchResp, error)

Calls Kraken API private Trading "AddOrderBatch" endpoint. Accepts slice of BatchOrder types passed to arg 'orders'. Send an array of orders (max: 15). Any orders rejected due to order validations, will be dropped and the rest of the batch is processed. All orders in batch should be limited to a single pair passed to arg 'pair. The order of returned txid's in the response array is the same as the order of the order list sent in request. Recommended to use constructor function NewBatchOrder() to build new BatchOrder types with the three required fields passed to its args.

Note: It is up to the user to ensure any other required fields (ie. Price) are set with the *BatchOrder methods depending on orderType and desired order behavior, and ensure that no conflicting methods are passed.

Required Permissions:

Orders and trades - Create & modify orders;

Functional Options:

// Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching
// engine should reject the new order request to arg 'deadline'.
//
// In presence of latency or order queueing: min now() + 2 seconds, max now() +
// 60 seconds.
func AddBatchWithDeadline(deadline string) AddOrderBatchOption

// Validates inputs only. Do not submit order. Defaults to "false" if not called.
func ValidateAddOrderBatch() AddOrderBatchOption

Example Usage:

// Layers 15 bids on Bitcoin/USD every 1% down from startingPrice
startingPrice := 46000
orders := make([]krakenspot.BatchOrder, 15)
for i := 0; i < 15; i++ {
	newOrder := krakenspot.NewBatchOrder("limit", "buy", "0.1").SetPrice(fmt.Sprintf("%.1f", float64(startingPrice)-(math.Pow(1.01, float64(i))-1)*float64(startingPrice)))
	orders[i] = *newOrder
}
batchOrderResp, err := kc.AddOrderBatch(orders, "XXBTZUSD", krakenspot.ValidateAddOrderBatch())
if err != nil {
	log.Println("error sending batch | ", err)
}
log.Println(batchOrderResp)

func (*KrakenClient) AllocateEarnFunds

func (kc *KrakenClient) AllocateEarnFunds(strategyID string, amount string) error

Calls Kraken API private Earn "Allocate" endpoint. Allocate funds to the strategy with specified ID passed to arg 'strategyID'. Pass desired amount of base currency to allocate in string format to arg 'amount'.

Note: This method is asynchronous. A couple of preflight checks are performed synchronously on behalf of the method before it is dispatched further. The client is required to poll the result using the (kc *KrakenClient) AllocationStatus() method.

Note: There can be only one (de)allocation request in progress for given user and strategy.

Required permissions:

Funds permissions - Earn;

Example Usage:

err := kc.AllocateEarnFunds("ESXUM7H-SJHQ6-KOQNNI", "5")

func (*KrakenClient) AllocationStatus

func (kc *KrakenClient) AllocationStatus(strategyID string) (bool, error)

Calls Kraken API private Earn "AllocateStatus" endpoint. Gets the status of the last allocation request for specific strategy ID passed to arg 'strategyID'. Returns true if the request is still pending, false if it is completed, and an api error if there was an issue with the request. API will also return false with no errors for strategies on which the account has never made a request.

Required Permissions:

Funds permissions - Query; OR Funds permissions - Earn;

Example Usage:

pending, err := kc.AllocationStatus("ESSR5EH-CKYSY-NUQNZI")

func (*KrakenClient) AuthenticateWebSockets

func (kc *KrakenClient) AuthenticateWebSockets() error

Adds WebSockets token to *KrakenClient via Kraken API private Account Data "GetWebSocketsToken" endpoint. This method must be called before subscribing to any authenticated WebSockets.

Note: An authentication token must be requested via this REST API endpoint in order to connect to and authenticate with our Websockets API. The token should be used within 15 minutes of creation, but it does not expire once a successful WebSockets connection and private subscription has been made and is maintained.

Required Permissions:

WebSockets interface - On;

Example Usage:

err := kc.GetWebSocketsToken()

func (*KrakenClient) AvailableUSDBalance

func (kc *KrakenClient) AvailableUSDBalance() (float64, error)

Calls Kraken API private Account Data "BalanceEx" endpoint. Returns available USD (ZUSD) account balance as float64. Balance available for trading is calculated as: available balance = balance + credit - credit_used - hold_trade

Required Permissions:

Funding Permissions - Query;

func (*KrakenClient) CancelAllOrders

func (kc *KrakenClient) CancelAllOrders() (*CancelOrderResp, error)

Calls Kraken API private Trading "CancelAll" endpoint. Cancels all open orders.

Required Permissions:

Orders and trades - Create & modify orders; OR

Orders and trades - Cancel & close orders

Example Usage:

cancelResp, err := kc.CancelAllOrders()

func (*KrakenClient) CancelAllOrdersAfter

func (kc *KrakenClient) CancelAllOrdersAfter(timeout string) (*CancelAllAfter, error)

Calls Kraken API private Trading "CancelAllOrdersAfter" endpoint. CancelAllOrdersAfter provides a "Dead Man's Switch" mechanism to protect the client from network malfunction, extreme latency or unexpected matching engine downtime. The client can send a request with a timeout (in seconds), that will start a countdown timer which will cancel all client orders when the timer expires. The client has to keep sending new requests to push back the trigger time, or deactivate the mechanism by specifying a timeout of 0. If the timer expires, all orders are cancelled and then the timer remains disabled until the client provides a new (non-zero) timeout.

The recommended use is to make a call every 15 to 30 seconds, providing a timeout of 60 seconds. This allows the client to keep the orders in place in case of a brief disconnection or transient delay, while keeping them safe in case of a network breakdown. It is also recommended to disable the timer ahead of regularly scheduled trading engine maintenance (if the timer is enabled, all orders will be cancelled when the trading engine comes back from downtime - planned or otherwise).

Required Permissions:

Orders and trades - Create & modify orders; OR

Orders and trades - Cancel & close orders

Example Usage:

cancelAfterResp, err := kc.CancelAllOrdersAfter("60")

func (*KrakenClient) CancelAllOrdersForPair

func (kc *KrakenClient) CancelAllOrdersForPair(pair string) (*CancelOrderResp, error)

Calls Kraken API private Trading "CancelOrderBatch" endpoint and private Account Data "OpenOrders" to find and cancel all open orders for market passed to arg 'pair'.

Required Permissions:

Order and Trades - Query open orders & trades;

Orders and trades - Create & modify orders; OR

Orders and trades - Cancel & close orders

Example Usage:

cancelResp, err := kc.CancelAllOrdersForPair("XXBTZUSD")

func (*KrakenClient) CancelOrder

func (kc *KrakenClient) CancelOrder(txID string) (*CancelOrderResp, error)

Calls Kraken API private Trading "CancelOrder" endpoint. Cancels either a particular open order by transaction ID passed to arg 'txID' or set of open orders with specified user reference ID passed to arg 'txID'.

Required Permissions:

Orders and trades - Create & modify orders; OR

Orders and trades - Cancel & close orders

Example Usage:

cancelResp, err := kc.CancelOrder("1234") // cancels multiple w/ user ref "1234"

func (*KrakenClient) CancelOrderBatch

func (kc *KrakenClient) CancelOrderBatch(txIDs []string) (*CancelOrderResp, error)

Calls Kraken API private Trading "CancelOrderBatch" endpoint. Cancels multiple open orders by txid or userref passed as a slice to arg 'txIDs' (maximum 50 total unique IDs/references)

Required Permissions:

Orders and trades - Create & modify orders; OR

Orders and trades - Cancel & close orders

Example Usage:

ordersToCancel := []string{"OG5V2Y-RYKVL-DT3V3B", "OP5V2Y-RYKVL-ET3V3B"}
cancelOrderResp, err := kc.CancelOrderBatch(ordersToCancel)

func (*KrakenClient) CancelWithdrawal

func (kc *KrakenClient) CancelWithdrawal(asset string, refID string) error

Calls Kraken API private Funding "WithdrawCancel" endpoint. Cancels a recently requested withdrawal of specified arg 'asset' with 'refID', if it has not already been successfully processed.

Required Permissions:

Funds permissions - Withdraw;

Example Usage:

err := kc.CancelWithdrawal("XBT", "FTQcuak-V6Za8qrWnhzTx67yYHz8Tg")

func (*KrakenClient) Connect

func (kc *KrakenClient) Connect(systemStatusCallback func(status string)) error

Creates both authenticated and public connections to Kraken WebSocket server. Use ConnectPublic() or ConnectPrivate() instead if only channel type is needed. Accepts arg 'systemStatusCallback' callback function which an end user can implement their own logic on handling incoming system status change messages.

Note: Creates authenticated token with AuthenticateWebSockets() method which expires within 15 minutes. Strongly recommended to subscribe to at least one private WebSocket channel and leave it open.

Note: systemStatusCallback will be triggered twice when Connect() is used as it connects to both an authenticated and a public server. Methods called here intended for initial startup may be triggered twice, recommended to include logic to prevent this or put subscription and startup methods in main after a call to WaitForConnect() instead.

CAUTION: Passing nil to arg 'systemStatusCallback' without handling system status changes elsewhere in your program may result in program crashes or invalid messages being pushed to Kraken's server on the occasions where their system's status is changed. Ensure you have implemented handling system status changes on your own or reinitialize the client with a valid systemStatusCallback function

Enum (possible incoming status message values):

'status': "online", "maintenance", "cancel_only", "limit_only", "post_only"

Example Usage:

Example 1: Using systemStatusCallback for graceful exits

Prints state of book every 15 seconds until systemStatus message other than "online" is received, then calls UnsubscribeAll() method and shuts down program.

// Note: error handling omitted throughout
// initialize KrakenClient and variables
kc, err := ks.NewKrakenClient(os.Getenv("KRAKEN_API_KEY"), os.Getenv("KRAKEN_API_SECRET"), 2, true)
depth := uint16(10)
pair := "XBT/USD"
// exit program gracefully if system status isnt "online"
systemStatusCallback := func(status string) {
	if status != "online" {
		kc.UnsubscribeAll()
		os.Exit(0)
	}
}
// connect and subscribe
err = kc.Connect(systemStatusCallback)
err = kc.SubscribeBook(pair, depth, nil)
// print asks and bids every 15 seconds
ticker := time.NewTicker(time.Second * 15)
for range ticker.C {
	asks, err := kc.ListAsks(pair, depth)
	bids, err := kc.ListBids(pair, depth)
	log.Println(asks)
	log.Println(bids)
}

Example 2: Using systemStatusCallback for graceful startup

Starts hypothetical goroutine function named placeBidAskSpread() when system is online and stops it when any other systemStatus is received.

// Note: error handling omitted throughout
// initialize KrakenClient and variables
kc, err := ks.NewKrakenClient(os.Getenv("KRAKEN_API_KEY"), os.Getenv("KRAKEN_API_SECRET"), 2, true)
depth := uint16(10)
pair := "XBT/USD"
// define your placeBidAskSpread function places a bid and ask every 15 seconds
placeBidAskSpread := func(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			return
		default:
			// logic to place an order each on best bid and best ask
			time.Sleep(time.Second * 15)
		}
	}
}
// create a context with cancel
ctx, cancel := context.WithCancel(context.Background())
// handle system status changes
online := make(chan struct{})
systemStatusCallback := func(status string) {
	if status == "online" {
		// starts the goroutine and subscribe to the book the first time an online message is received
		_, ok := <-online
		if ok {
			close(online)
			err = kc.SubscribeBook(pair, depth, nil)
			go placeBidAskSpread(ctx)
		}
	} else {
		// if system status is not online, cancel the context to stop the goroutine and unsubscribe from the book
		cancel()
		err = kc.UnsubscribeBook(pair, depth)
		// create a new context for the next time the system status is online
		ctx, cancel = context.WithCancel(context.Background())
	}
}
// connect
err = kc.Connect(systemStatusCallback)
// block program from exiting
select{}

func (*KrakenClient) ConnectPrivate

func (kc *KrakenClient) ConnectPrivate(systemStatusCallback func(status string)) error

Connects to the private WebSocket endpoints of the Kraken API and initializes WebSocketClient. Calls the unexported helper method connectPrivate to establish the connection. If the connection is successful, it sets the SystemStatusCallback function. It returns an error if the connection fails.

Note: Creates authenticated token with AuthenticateWebSockets() method which expires within 15 minutes. Strongly recommended to subscribe to at least one private WebSocket channel and leave it open.

CAUTION: Passing nil to arg 'systemStatusCallback' without handling system status changes elsewhere in your program may result in program crashes or invalid messages being pushed to Kraken's server on the occasions where their system's status is changed. Ensure you have implemented handling system status changes on your own or reinitialize the client with a valid systemStatusCallback function

See docstrings for (kc *KrakenClient) Connect() for example usage

func (*KrakenClient) ConnectPublic

func (kc *KrakenClient) ConnectPublic(systemStatusCallback func(status string)) error

Connects to the public WebSocket endpoints of the Kraken API and initializes WebSocketClient. Calls the unexported helper method connectPrivate to establish the connection. If the connection is successful, it sets the SystemStatusCallback function. It returns an error if the connection fails.

CAUTION: Passing nil to arg 'systemStatusCallback' without handling system status changes elsewhere in your program may result in program crashes or invalid messages being pushed to Kraken's server on the occasions where their system's status is changed. Ensure you have implemented handling system status changes on your own or reinitialize the client with a valid systemStatusCallback function

See docstrings for (kc *KrakenClient) Connect() for example usage

func (*KrakenClient) CreateSubaccount

func (kc *KrakenClient) CreateSubaccount(username string, email string) error

Calls Kraken API private Subaccounts "CreateSubaccount" endpoint. Creates a trading subaccount with details passed to args 'username' and 'email'

Note: Subaccounts are currently only available to institutional clients. Please contact your Account Manager for more details.

Required Permissions:

Institutional verification;

Example Usage:

err := kc.CreateSubaccount("kraken-sub-1", "bryptotrader123@aol.com")

func (*KrakenClient) DeallocateEarnFunds

func (kc *KrakenClient) DeallocateEarnFunds(strategyID string, amount string) error

Calls Kraken API private Earn "Deallocate" endpoint. Deallocate funds to the strategy with specified ID passed to arg 'strategyID'. Pass desired amount of base currency to deallocate in string format to arg 'amount'.

Note: This method is asynchronous. A couple of preflight checks are performed synchronously on behalf of the method before it is dispatched further. The client is required to poll the result using the (kc *KrakenClient) DeallocationStatus() method.

Note: There can be only one (de)allocation request in progress for given user and strategy.

Required permissions:

Funds permissions - Earn;

Example Usage:

err := kc.AllocateEarnFunds("ESXUM7H-SJHQ6-KOQNNI", "5")

func (*KrakenClient) DeallocationStatus

func (kc *KrakenClient) DeallocationStatus(strategyID string) (bool, error)

Calls Kraken API private Earn "DeallocateStatus" endpoint. Gets the status of the last deallocation request for specific strategy ID passed to arg 'strategyID'. Returns true if the request is still pending, false if it is completed, and an api error if there was an issue with the request. API will also return false with no errors for strategies on which the account has never made a request.

Required Permissions:

Funds permissions - Query; OR Funds permissions - Earn;

Example Usage:

pending, err := kc.DeallocationStatus("ESSR5EH-CKYSY-NUQNZI")

func (*KrakenClient) DeleteExportReport

func (kc *KrakenClient) DeleteExportReport(reportID string, requestType string) error

Calls Kraken API private Account Data "RemoveExport" endpoint. Deletes/cancels exported trades/ledgers report with specific ID passed to arg 'reportID'. Passing "delete" to arg 'requestType' can only be used for reports that have already been processed; pass "cancel" for queued or processing reports.

Enum - 'requestType': "delete", "cancel"

Required Permissions:

Data - Export data;

Example Usage:

err := kc.RetrieveDataExport("TCJA", "cancel")

func (*KrakenClient) EditOrder

func (kc *KrakenClient) EditOrder(txID, pair string, options ...EditOrderOption) (*EditOrderResp, error)

Calls Kraken API private Trading "EditOrder" endpoint. Edit volume and price on open orders with transaction ID or user reference ID passed to arg 'refID'. If reference ID is used, it must be unique to only one order. Uneditable orders include triggered stop/profit orders, orders with conditional close terms attached, those already cancelled or filled, and those where the executed volume is greater than the newly supplied volume. Accepts any number of functional options passed to arg 'options'; see list below and/or options.go for further docs notes for options.

Note: Edit orders will be rejected by Kraken's API if at least one of NewVolume() or NewPrice() is not passed to arg 'options'

Note: Field "userref" from parent order will not be retained on the new order after edit. NewUserRef() must be passed to arg 'options' if a reference ID associated with this order is still necessary.

Note: Post-only flag is not retained from original order after successful edit. Post-only needs to be explicitly set with NewPostOnly() passed to arg 'options' on edit request.

Required Permissions:

Orders and trades - Create & modify orders;

Functional Options:

// Field "userref" is an optional user-specified integer id associated with
// edit request.
//
// Note: userref from parent order will not be retained on the new order after
// edit.
func NewUserRef(userRef string) EditOrderOption

// Updates order quantity in terms of the base asset.
func NewVolume(volume string) EditOrderOption

// Used to edit an iceberg order, this is the visible order quantity in terms
// of the base asset. The rest of the order will be hidden, although the full
// volume can be filled at any time by any order of that size or larger that
// matches in the order book. displayvol can only be used with the limit order
// type, must be greater than 0, and less than volume.
func NewDisplayVolume(displayVol string) EditOrderOption

// Updates limit price for "limit" orders. Updates trigger price for "stop-loss",
// "stop-loss-limit", "take-profit", "take-profit-limit", "trailing-stop" and
// "trailing-stop-limit" orders...
func NewPrice(price string) EditOrderOption

// Updates limit price for "stop-loss-limit", "take-profit-limit" and
// "trailing-stop-limit" orders...
func NewPrice2(price2 string) EditOrderOption

// Post-only order (available when ordertype = limit). All the flags from the
// parent order are retained except post-only. Post-only needs to be explicitly
// mentioned on every edit request.
func NewPostOnly() EditOrderOption

// RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching
// engine should reject the new order request, in presence of latency or order
// queueing. min now() + 2 seconds, max now() + 60 seconds.
func NewDeadline(deadline string) EditOrderOption

// Used to interpret if client wants to receive pending replace, before the
// order is completely replaced. Defaults to "false" if not called.
func NewCancelResponse() EditOrderOption

// Validate inputs only. Do not submit order. Defaults to false if not called.
func ValidateEditOrder() EditOrderOption

Example Usage:

editOrder, err := kc.EditOrder("OHYO67-6LP66-HMQ437", "XXBTZUSD", krakenspot.NewVolume("2.1234"), krakenspot.NewPostOnly(), krakenspot.NewPrice("45000.1"), krakenspot.ValidateEditOrder())

func (*KrakenClient) GetAccountBalances

func (kc *KrakenClient) GetAccountBalances() (*map[string]string, error)

Calls Kraken API private Account Data "Balance" endpoint. Returns map of all "cash" (including coins) balances, net of pending withdrawals as strings

Required Permissions:

Funding Permissions - Query;

func (*KrakenClient) GetAllAssetInfo

func (kc *KrakenClient) GetAllAssetInfo() (*map[string]AssetInfo, error)

Calls Kraken API public market data "Assets" endpoint. Gets information about all assets that are available for deposit, withdrawal, trading and staking. Returns them as *map[string]AssetInfo where the string is the asset name.

func (*KrakenClient) GetAllTickerInfo

func (kc *KrakenClient) GetAllTickerInfo() (*map[string]TickerInfo, error)

Calls Kraken API public market data "Ticker" endpoint. Gets ticker info for all tradeable pairs.

Note: Today's prices start at midnight UTC

func (*KrakenClient) GetAssetInfo

func (kc *KrakenClient) GetAssetInfo(asset string) (*AssetInfo, error)

Calls Kraken API public market data "Assets" endpoint. Gets information about specific asset passed to arg.

func (*KrakenClient) GetAvailableBalances

func (kc *KrakenClient) GetAvailableBalances() (*map[string]float64, error)

Calls Kraken API private Account Data "BalanceEx" endpoint. Returns map of all available account balances as float64. Balance available for trading is calculated as: available balance = balance + credit - credit_used - hold_trade

Required Permissions:

Funding Permissions - Query;

func (*KrakenClient) GetClosedOrders

func (kc *KrakenClient) GetClosedOrders(options ...GetClosedOrdersOption) (*ClosedOrdersResp, error)

Calls Kraken API private Account Data "ClosedOrders" endpoint. Retrieves information for most recent closed orders. Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query closed orders & trades;

Functional Options:

// Whether or not to include trades related to position in output. Defaults
// to false if not called
func COWithTrades(trades bool) GetClosedOrdersOption

// Restrict results to given user reference id. Defaults to no restrictions
// if not called
func COWithUserRef(userRef int) GetClosedOrdersOption

// Starting unix timestamp or order tx ID of results (exclusive). If an order's
// tx ID is given for start or end time, the order's opening time (opentm) is used.
// Defaults to show most recent orders if not called
func COWithStart(start int) GetClosedOrdersOption

// Ending unix timestamp or order tx ID of results (exclusive). If an order's
// tx ID is given for start or end time, the order's opening time (opentm) is used
// Defaults to show most recent orders if not called
func COWithEnd(end int) GetClosedOrdersOption

// Result offset for pagination. Defaults to no offset if not called
func COWithOffset(offset int) GetClosedOrdersOption

// Which time to use to search and filter results for COWithStart() and COWithEnd()
// Defaults to "both" if not called or invalid arg 'closeTime' passed
//
// Enum: "open", "close", "both"
func COWithCloseTime(closeTime string) GetClosedOrdersOption

// Whether or not to consolidate trades by individual taker trades. Defaults to
// true if not called
func COWithConsolidateTaker(consolidateTaker bool) GetClosedOrdersOption

Example Usage:

orders, err := kc.GetClosedOrders(krakenspot.COWithConsolidateTaker(true), krakenspot.COWithCloseTime("open"))

func (*KrakenClient) GetDepositAddresses

func (kc *KrakenClient) GetDepositAddresses(asset string, method string, options ...GetDepositAddressesOption) (*[]DepositAddress, error)

Calls Kraken API private Funding "DepositAddresses" endpoint. Retrieve (or generate new with DAWithNew() passed to arg 'options') deposit addresses for a particular asset and method. Accepts functional options args 'options'.

Required Permissions:

Funds permissions - Query;

Functional Options:

// Whether or not to generate a new address. Defaults to false if function is
// not called.
func DAWithNew() GetDepositAddressesOption

// Amount you wish to deposit (only required for method=Bitcoin Lightning)
func DAWithAmount(amount string) GetDepositAddressesOption

Example Usage:

depositAddresses, err := kc.GetDepositAddresses("XBT", "Bitcoin", krakenspot.DAWithNew())

func (*KrakenClient) GetDepositMethods

func (kc *KrakenClient) GetDepositMethods(asset string, options ...GetDepositMethodsOption) (*[]DepositMethod, error)

Calls Kraken API private Funding "DepositMethods" endpoint. Retrieve methods available for depositing a specified asset passed to arg 'asset'. ~Accepts functional options args 'options'.~

Required Permissions:

Funds permissions - Query; Funds permissions - Deposit;

~Functional Options:~

~Asset class being deposited (optional). Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency".~

~func DMWithAssetClass(aclass string) GetDepositMethodsOption~

Example Usage:

depositMethods, err := kc.GetDepositMethods("XBT")

func (*KrakenClient) GetDepositsStatus

func (kc *KrakenClient) GetDepositsStatus(options ...GetDepositsStatusOption) (*[]DepositStatus, error)

Calls Kraken API private Funding "DepositStatus" endpoint. Retrieves information about recent deposits. Results are sorted by recency, call method GetDepositsStatusPaginated() instead to begin an iterated list of deposits. Accepts functional options args 'options'.

Required Permissions:

Funds permissions - Query;

Functional Options:

// Filter for specific asset being deposited
func DSWithAsset(asset string) GetDepositsStatusOption

// Filter for specific name of deposit method
func DSWithMethod(method string) GetDepositsStatusOption

// Start timestamp, deposits created strictly before will not be included in
// the response
func DSWithStart(start string) GetDepositsStatusOption

// End timestamp, deposits created strictly after will be not be included in
// the response
func DSWithEnd(end string) GetDepositsStatusOption

// Number of results to include per page
func DSWithLimit(limit uint) GetDepositsStatusOption

~Filter asset class being deposited. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~

~func DSWithAssetClass(aclass string) GetDepositsStatusOption~

Example Usage:

deposits, err := kc.GetDepositsStatus()

func (*KrakenClient) GetDepositsStatusCursor

func (kc *KrakenClient) GetDepositsStatusCursor(cursor string) (*DepositStatusPaginated, error)

Calls Kraken API private Funding "DepositStatus" endpoint. Requires arg 'cursor' which has been retrieved from a previous call to GetDepositsStatusPaginated() method. Continues paginated list with information about recent deposits. Results are sorted by recency and filtered by 'options' passed to GetDepositsStatusPaginated() previously.

Required Permissions:

Funds permissions - Query;

Example Usage:

depositsResp, err := kc.GetDepositsStatusPaginated(krakenspot.DPWithAsset("XBT"), krakenspot.DPWithLimit(5))
deposits := (*depositsResp).Deposits
// do something with deposits
cursor := (*depositsResp).NextCursor
for cursor != "" {
	depositsResp, err = kc.GetDepositsStatusCursor(cursor)
	// error handling
	deposits = (*depositsResp).Deposits
	// do something with deposits
	cursor = (*depositsResp).NextCursor
}

func (*KrakenClient) GetDepositsStatusPaginated

func (kc *KrakenClient) GetDepositsStatusPaginated(options ...GetDepositsStatusPaginatedOption) (*DepositStatusPaginated, error)

Calls Kraken API private Funding "DepositStatus" endpoint. Begins a paginated list with information about recent deposits. Results are sorted by recency and filtered by functional options args 'options'. After list is initiated via this method, use with (kc *KrakenClient) GetDepositsStatusWithCursor().

Required Permissions:

Funds permissions - Query;

Functional Options:

// Filter for specific asset being deposited
func DPWithAsset(asset string) GetDepositsStatusPaginatedOption

// Filter for specific name of deposit method
func DPWithMethod(method string) GetDepositsStatusPaginatedOption

// Start timestamp, deposits created strictly before will not be included in
// the response
func DPWithStart(start string) GetDepositsStatusPaginatedOption

// End timestamp, deposits created strictly after will be not be included in
// the response
func DPWithEnd(end string) GetDepositsStatusPaginatedOption

// Number of results to include per page
func DPWithLimit(limit uint) GetDepositsStatusPaginatedOption

~Filter asset class being deposited. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~

~func DPWithAssetClass(aclass string) GetDepositsStatusPaginatedOption~

Example Usage:

depositsResp, err := kc.GetDepositsStatusPaginated(krakenspot.DPWithAsset("XBT"), krakenspot.DPWithLimit(5))
deposits := (*depositsResp).Deposits
// do something with deposits
cursor := (*depositsResp).NextCursor
for cursor != "" {
	depositsResp, err = kc.GetDepositsStatusCursor(cursor)
	// error handling
	deposits = (*depositsResp).Deposits
	// do something with deposits
	cursor = (*depositsResp).NextCursor
}

func (*KrakenClient) GetEarnAllocations

func (kc *KrakenClient) GetEarnAllocations(options ...GetEarnAllocationsOption) (*EarnAllocationsResp, error)

Calls Kraken API private Earn "Allocations" endpoint. Gets all earn allocations for the user. By default all allocations are returned, even for strategies that have been used in the past and have zero balance now.

Note: Paging hasn't been implemented for this method

Required Permissions:

Funds permissions - Query;

Functional Options:

// Pass with arg 'ascending' set to true to sort strategies ascending. Defaults
// to false (descending) if function is not called
func EAWithAscending(ascending bool) GetEarnAllocationsOption

// A secondary currency to express the value of your allocations. Defaults
// to express value in USD if function is not called
func EAWithConvertedAsset(asset string) GetEarnAllocationsOption

// Omit entries for strategies that were used in the past but now they don't
// hold any allocation. Defaults to false (don't omit) if function is not called
func EAWithHideZeroAllocations(hide bool) GetEarnAllocationsOption

Example Usage:

allocations, err := kc.GetEarnAllocations(krakenspot.EAWithConvertedAsset("XBT"), krakenspot.EAWithHideZeroAllocations())

func (*KrakenClient) GetEarnStrategies

func (kc *KrakenClient) GetEarnStrategies(options ...GetEarnStrategiesOption) (*EarnStrategiesResp, error)

Calls Kraken API private Earn "Strategies" endpoint. Returns earn strategies along with their parameters. Returns only strategies that are available to the user based on geographic region.

Note: In practice, allocation_restriction_info will always be empty even when can_allocate is false despite Kraken API docs note otherwise.

Kraken API docs note: When the user does not meet the tier restriction, can_allocate will be false and allocation_restriction_info indicates Tier as the restriction reason. Earn products generally require Intermediate tier. Get your account verified to access earn.

Note: Paging isn't yet implemented, so the endpoint always returns all data in the first page. This results in some functional options having no effect on output though the query parameters are still valid.

Required Permissions:

None;

Functional Options:

// Filter strategies by asset name. Defaults to no filter if function not called
func ESWithAsset(asset string) GetEarnStrategiesOption

// Filters displayed strategies by lock type. Accepts array of strings for arg
// 'lockTypes' and ignores invalid values passed. Defaults to no filter if
// function not called or only invalid values passed.
//
// Enum - 'lockTypes': "flex", "bonded", "timed", "instant"
func ESWithLockType(lockTypes []string) GetEarnStrategiesOption

~// Pass with arg 'ascending' set to true to sort strategies ascending. Defaults to false (descending) if function is not called~

~func ESWithAscending(ascending bool) GetEarnStrategiesOption~

~// Sets page ID to display results. Defaults to beginning/end (depending on sorting set by ESWithAscending()) if function not called.~

~func ESWithCursor(cursor string) GetEarnStrategiesOption~

~// Sets number of items to return per page. Note that the limit may be cap'd to lower value in the application code.~

~func ESWithLimit(limit uint16) GetEarnStrategiesOption~

Example Usage:

strategies, err := kc.GetEarnStrategies(krakenspot.ESWithLockType([]string{"flex", "instant"}))

func (*KrakenClient) GetExportReportStatus

func (kc *KrakenClient) GetExportReportStatus(reportType string) (*[]ExportReportStatus, error)

Calls Kraken API private Account Data "ExportStatus" endpoint. Gets status of requested data exports. Requires arg 'reportType' of either "trades" or "ledgers".

Note: Kraken API requires valid 'reportType' to be passed. According to Kraken API docs, this will filter results and only get status for reports of type 'reportType'. As of 1/5/2024, this parameter does nothing and the output is identical, yet a valid value is still required.

Enum - 'reportType': "trades", "ledgers"

Required Permissions:

Data - Export data;

Example Usage:

reportStatus, err := kc.GetExportReportStatus("ledgers")

func (*KrakenClient) GetExtendedBalances

func (kc *KrakenClient) GetExtendedBalances() (*map[string]ExtendedBalance, error)

Calls Kraken API private Account Data "BalanceEx" endpoint. Returns map of all extended account balances, including credits and held amounts.

Required Permissions:

Funding Permissions - Query;

func (*KrakenClient) GetLedger

func (kc *KrakenClient) GetLedger(ledgerID string, options ...GetLedgerOption) (*map[string]Ledger, error)

Calls Kraken API private Account Data "QueryLedgers" endpoint. Retrieves information about specific ledger entries passed to arg 'ledgerID'. Accepts multiple ledgers with ledger IDs passed as a single comma delimited string with no white-space (20 maximum). Accepts functional options args 'options'.

Required Permissions:

Data - Query ledger entries;

Functional Options:

// Whether or not to include trades related to position in output. Defaults to
// false if not called.
func GLWithTrades(trades bool) GetLedgerOption

Example Usage:

ledger, err := kc.GetLedger("LGBRJU-SQZ4L-5HLS3C,L3S26P-BHIOV-TTWYYI", krakenspot.GLWithTrades(true))

func (*KrakenClient) GetLedgersInfo

func (kc *KrakenClient) GetLedgersInfo(options ...GetLedgersInfoOption) (*LedgersInfoResp, error)

Calls Kraken API private Account Data "Ledgers" endpoint. Retrieves information about ledger entries. 50 results are returned at a time, the most recent by default. Accepts functional options args 'options'.

Required Permissions:

Data - Query ledger entries;

Functional Options:

// Filter output by asset or comma delimited list of assets. Defaults to "all"
// if not called.
func LIWithAsset(asset string) GetLedgersInfoOption

// Filter output by asset class. Defaults to "currency" if not called
//
// Enum: "currency", ...?
func LIWithAclass(aclass string) GetLedgersInfoOption

// Type of ledger to retrieve. Defaults to "all" if not called or invalid
// 'ledgerType' passed.
//
// Enum: "all", "trade", "deposit", "withdrawal", "transfer", "margin", "adjustment",
// "rollover", "credit", "settled", "staking", "dividend", "sale", "nft_rebate"
func LIWithType(ledgerType string) GetLedgersInfoOption

// Starting unix timestamp or ledger ID of results (exclusive). Defaults to most
// recent ledgers if not called.
func LIWithStart(start int) GetLedgersInfoOption

// Ending unix timestamp or ledger ID of results (inclusive). Defaults to most
// recent ledgers if not called.
func LIWithEnd(end int) GetLedgersInfoOption

// Result offset for pagination. Defaults to no offset if not called.
func LIWithOffset(offset int) GetLedgersInfoOption

// If true, does not retrieve count of ledger entries. Request can be noticeably
// faster for users with many ledger entries as this avoids an extra database query.
// Defaults to false if not called.
func LIWithoutCount(withoutCount bool) GetLedgersInfoOption

Example Usage:

ledgers, err := kc.GetLedgersInfo(krakenspot.LIWithAsset("ZUSD,XXBT"), krakenspot.LIWithoutCount(true), krakenspot.LIWithOffset(5))

func (*KrakenClient) GetOHLC

func (kc *KrakenClient) GetOHLC(pair string, interval uint16, since ...uint64) (*OHLCResp, error)

Calls Kraken API public market data "OHLC" endpoint. Gets OHLC data for specified pair of the required interval (in minutes).

Accepts optional arg since as a start time in Unix for the However, per the Kraken API docs "Note: the last entry in the OHLC array is for the current, not-yet-committed frame and will always be present, regardless of the value of since.

Enum - 'interval': 1, 5, 15, 30, 60, 240, 1440, 10080, 21600

func (*KrakenClient) GetOpenOrders

func (kc *KrakenClient) GetOpenOrders(options ...GetOpenOrdersOption) (*OpenOrdersResp, error)

Calls Kraken API private Account Data "OpenOrders" endpoint. Retrieves information for all currently open orders. Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query open orders & trades;

Functional Options:

// Whether or not to include trades related to position in output. Defaults
// to false if not called
func OOWithTrades(trades bool) GetOpenOrdersOption

// Restrict results to given user reference id. Defaults to no restrictions
// if not called
func OOWithUserRef(userRef int) GetOpenOrdersOption

Example Usage:

orders, err := kc.GetOpenOrders(krakenspot.OOWithTrades(true), krakenspot.OOWithUserRef(123))

func (*KrakenClient) GetOpenOrdersForPair

func (kc *KrakenClient) GetOpenOrdersForPair(pair string) (*map[string]Order, error)

Calls Kraken API private Account Data "OpenOrders" endpoint with default parameters filtered by orders for arg 'pair'. Returns a map of (key) transaction IDs and (value) its order information of all open orders for the pair.

Required Permissions:

Order and Trades - Query open orders & trades;

Example Usage:

orders, err := kc.GetOpenOrdersForPair("SOLUSD")

func (*KrakenClient) GetOpenPositions

func (kc *KrakenClient) GetOpenPositions(options ...GetOpenPositionsOption) (*map[string]OpenPosition, error)

Calls Kraken API private Account Data "OpenPositions" endpoint. Gets information about open margin positions. Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query open orders & trades;

Functional Options:

// Comma delimited list of txids to limit output to. Defaults to show all open
// positions if not called
func OPWithTxID(txID string) GetOpenPositionsOption

// Whether to include P&L calculations. Defaults to false if not called
func OPWithDoCalcs(doCalcs bool) GetOpenPositionsOption

Example Usage:

positions, err := kc.GetOpenPositions(krakenspot.OPWithDoCalcs(true))

func (*KrakenClient) GetOpenPositionsConsolidated

func (kc *KrakenClient) GetOpenPositionsConsolidated(options ...GetOpenPositionsConsolidatedOption) (*[]OpenPositionConsolidated, error)

Calls Kraken API private Account Data "OpenPositions" endpoint. Gets information about open margin positions consolidated by market/pair. Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query open orders & trades;

Functional Options:

// Comma delimited list of txids to limit output to. Defaults to show all open
// positions if not called
func OPCWithTxID(txID string) GetOpenPositionsOption

// Whether to include P&L calculations. Defaults to false if not called
func OPCWithDoCalcs(doCalcs bool) GetOpenPositionsOption

Example Usage:

positions, err := kc.GetOpenPositionsConsolidated(krakenspot.OPWithDoCalcs(true))

func (*KrakenClient) GetOrderBook

func (kc *KrakenClient) GetOrderBook(pair string, count ...uint16) (*OrderBook, error)

Calls Kraken API public market data "Depth" endpoint. Gets arrays of bids and asks for arg 'pair'. Optional arg 'count' will return count number of each bids and asks. Not passing an arg to 'count' will default to 100.

Enum - 'count': [1..500]

func (*KrakenClient) GetOrdersInfo

func (kc *KrakenClient) GetOrdersInfo(txID string, options ...GetOrdersInfoOption) (*map[string]Order, error)

Calls Kraken API private Account Data "OrdersInfo" endpoint. Retrieves order information for specific orders with transaction id passed to arg 'txID'. Accepts multiple orders with transaction IDs passed as a single comma delimited string with no white-space (50 maximum). Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query closed orders & trades;

Functional Options:

// Whether or not to include trades related to position in output. Defaults
// to false if not called
func OIWithTrades(trades bool) GetOrdersInfoOptions

// Restrict results to given user reference id. Defaults to no restrictions
// if not called
func OIWithUserRef(userRef int) GetOrdersInfoOptions

// Whether or not to consolidate trades by individual taker trades. Defaults to
// true if not called
func OIWithConsolidateTaker(consolidateTaker bool)

Example usage:

orders, err := kc.GetOrdersInfo("OYR15S-VHRBC-VY5NA2,OYBGFG-LQHXB-RJHY4C", krakenspot.OIWithConsolidateTaker(true))

func (*KrakenClient) GetServerTime

func (kc *KrakenClient) GetServerTime() (*ServerTime, error)

Calls Kraken API public market data "Time" endpoint. Gets the server's time. ServerTime struct

func (*KrakenClient) GetSpread

func (kc *KrakenClient) GetSpread(pair string, since ...uint64) (*SpreadResp, error)

Calls Kraken API public market data "Spread" endpoint. Returns the last ~200 top-of-book spreads for given arg 'pair'.

Note: arg 'since' intended for incremental updates within available dataset (does not contain all historical spreads)

func (*KrakenClient) GetSystemStatus

func (kc *KrakenClient) GetSystemStatus() (*SystemStatus, error)

Calls Kraken API public market data "SystemStatus" endpoint. Gets the current system status or trading mode

Example Usage:

status, err := krakenspot.GetSystemStatus()
log.Println(status.Status)
log.Println(status.Timestamp)

func (*KrakenClient) GetTickerInfo

func (kc *KrakenClient) GetTickerInfo(pair string) (*map[string]TickerInfo, error)

Calls Kraken API public market data "Ticker" endpoint. Accepts one argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

Note: Today's prices start at midnight UTC

func (*KrakenClient) GetTradeBalance

func (kc *KrakenClient) GetTradeBalance(asset ...string) (*TradeBalance, error)

Calls Kraken API private Account Data "TradeBalance" endpoint. Returns a summary of collateral balances, margin position valuations, equity and margin level denominated in arg 'asset'. Passing no arg to 'asset' defaults to USD (ZUSD) denomination.

Required Permissions:

Funding Permissions - Query;

Order and Trades - Query open orders & trades

func (*KrakenClient) GetTradeInfo

func (kc *KrakenClient) GetTradeInfo(txID string, options ...GetTradeInfoOption) (*map[string]TradeInfo, error)

Calls Kraken API private Account Data "QueryTrades" endpoint. Retrieves information specific trades/fills with transaction id passed to arg 'txID'. Accepts multiple trades with transaction IDs passed as a single comma delimited string with no white-space (20 maximum). Accepts functional options args 'options'.

Required Permissions:

Order and Trades - Query closed orders & trades;

Functional Options:

// Whether or not to include trades related to position in output. Defaults
// to false if not called
func TIWithTrades(trades bool) GetTradeInfoOption

Example Usage:

trades, err := kc.GetTradeInfo("TRWCIF-3MJWU-5DYJG5,TNGJFU-5CD67-ZV3AEO")

func (*KrakenClient) GetTradeVolume

func (kc *KrakenClient) GetTradeVolume(options ...GetTradeVolumeOption) (*TradeVolume, error)

Calls Kraken API private Account Data "TradeVolume" endpoint. Returns 30 day USD trading volume and resulting fee schedule for any asset pair(s) provided. Note: If an asset pair is on a maker/taker fee schedule, the taker side is given in fees and maker side in fees_maker. For pairs not on maker/taker, they will only be given in fees. Accepts functional options args 'options'.

Required Permissions:

Funds permissions - Query;

Functional Options:

// Comma delimited list of asset pairs to get fee info on. Defaults to show none
// if not called.
func TVWithPair(pair string) GetTradeVolumeOption

Example Usage:

kc.GetTradeVolume(krakenspot.TVWithPair("XXBTZUSD,XETHZUSD"))

func (*KrakenClient) GetTradeablePairsFees

func (kc *KrakenClient) GetTradeablePairsFees(pair ...string) (*map[string]AssetPairFees, error)

Calls Kraken API public market data "AssetPairs" endpoint with "fees" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func (*KrakenClient) GetTradeablePairsInfo

func (kc *KrakenClient) GetTradeablePairsInfo(pair ...string) (*map[string]AssetPairInfo, error)

Calls Kraken API public market data "AssetPairs" endpoint with default info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func (*KrakenClient) GetTradeablePairsLeverage

func (kc *KrakenClient) GetTradeablePairsLeverage(pair ...string) (*map[string]AssetPairLeverage, error)

Calls Kraken API public market data "AssetPairs" endpoint with "leverage" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func (*KrakenClient) GetTradeablePairsMargin

func (kc *KrakenClient) GetTradeablePairsMargin(pair ...string) (*map[string]AssetPairMargin, error)

Calls Kraken API public market data "AssetPairs" endpoint with "margin" info query parameter. Calling function without arguments gets info for all tradable asset pairs. Accepts one optional argument for the "pair" query parameter. If multiple pairs are desired, pass them as one comma delimited string into the pair argument.

func (*KrakenClient) GetTrades

func (kc *KrakenClient) GetTrades(pair string, count ...uint16) (*TradesResp, error)

Calls Kraken API public market data "Trades" endpoint. Gets the most recent trades for arg 'pair'. Accepts optional arg 'count' to get 'count' number of recent trades. Not passing an arg to 'count' will default to 1000

Enum - 'count': [1..1000]

func (*KrakenClient) GetTradesHistory

func (kc *KrakenClient) GetTradesHistory(options ...GetTradesHistoryOption) (*TradesHistoryResp, error)

Calls Kraken API private Account Data "TradesHistory" endpoint. Retrieves information about trades/fills. 50 results are returned at a time, the most recent by default.

Required Permissions:

Order and Trades - Query closed orders & trades;

Functional Options:

// Type of trade. Defaults to "all" if not called or invalid 'tradeType' passed.
//
// Enum: "all", "any position", "closed position", "closing position", "no position"
func THWithType(tradeType string) GetTradesHistoryOptions

// Whether or not to include trades related to position in output. Defaults
// to false if not called
func THWithTrades(trades bool) GetTradesHistoryOptions

// Starting unix timestamp or order tx ID of results (exclusive). If an order's
// tx ID is given for start or end time, the order's opening time (opentm) is used.
// Defaults to show most recent orders if not called
func THWithStart(start int) GetTradesHistoryOptions

// Ending unix timestamp or order tx ID of results (exclusive). If an order's
// tx ID is given for start or end time, the order's opening time (opentm) is used
// Defaults to show most recent orders if not called
func THWithEnd(end int) GetTradesHistoryOptions

// Result offset for pagination. Defaults to no offset if not called
func THWithOffset(offset int) GetTradesHistoryOptions

// Whether or not to consolidate trades by individual taker trades. Defaults to
// true if not called
func THWithConsolidateTaker(consolidateTaker bool) GetTradesHistoryOptions

Example Usage:

trades, err := kc.GetTradesHistory(krakenspot.THWithType("closed position"), krakenspot.THWithOffset(2))

func (*KrakenClient) GetTradesSince

func (kc *KrakenClient) GetTradesSince(pair string, since uint64, count ...uint16) (*TradesResp, error)

Calls Kraken API public market data "Trades" endpoint. Gets the trades after unix time arg 'since' for arg 'pair'. Accepts optional arg 'count' to get 'count' number of trades after 'since'. Not passing an arg to 'count' will default to 1000

Enum - 'count': [1..1000]

func (*KrakenClient) GetWebSocketsToken

func (kc *KrakenClient) GetWebSocketsToken() (*WebSocketsToken, error)

Calls Kraken API private Account Data "GetWebSocketsToken" endpoint. This method only returns the API's response as a struct including the token and the number of seconds until expiration. It does not add the token to *KrakenClient. Use *KrakenClient method AuthenticateWebSockets() instead.

Note: An authentication token must be requested via this REST API endpoint in order to connect to and authenticate with our Websockets API. The token should be used within 15 minutes of creation, but it does not expire once a successful WebSockets connection and private subscription has been made and is maintained.

Required Permissions:

WebSockets interface - On;

Example Usage:

tokenResp, err := kc.GetWebSocketsToken()
token := (*tokenResp).Token

func (*KrakenClient) GetWithdrawalAddresses

func (kc *KrakenClient) GetWithdrawalAddresses(options ...GetWithdrawalAddressesOption) (*[]WithdrawalAddress, error)

Calls Kraken API private Funding "WithdrawAddresses" endpoint. Retrieves a list of withdrawal addresses available for the user. Accepts functional options passed to arg 'options'

Required Permissions:

Funds permissions - Query; Funds permissions - Withdraw;

Functional Options:

// Filter addresses for specific asset
func WAWithAsset(asset string) GetWithdrawalAddressesOption

// Filter addresses for specific method
func WAWithMethod(method string) GetWithdrawalAddressesOption

// Find address for by withdrawal key name, as set up on your account
func WAWithKey(key string) GetWithdrawalAddressesOption

// Filter by verification status of the withdrawal address. Withdrawal addresses
// successfully completing email confirmation will have a verification status of
// true.
func WAWithVerified(verified bool) GetWithdrawalAddressesOption

~// Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~ ~func WAWithAssetClass(aclass string) GetWithdrawalAddressesOption~

Example Usage:

withdrawalAddresses, err := kc.GetWithdrawalAddresses(krakenspot.WAWithAsset("XBT"), krakenspot.WAWithVerified(true))

func (*KrakenClient) GetWithdrawalInfo

func (kc *KrakenClient) GetWithdrawalInfo(asset string, key string, amount string) (*WithdrawalInfo, error)

Calls Kraken API private Funding "WithdrawInfo" endpoint. Retrieves fee information about potential withdrawals for a specified args 'asset', withdrawal key name 'key', and 'amount'.

Required Permissions:

Funds permissions - Query; Funds permissions - Withdraw;

Example Usage:

withdrawalinfo, err := kc.GetWithdrawalInfo("XBT", "btc_testnet_with1", "0.725")

func (*KrakenClient) GetWithdrawalMethods

func (kc *KrakenClient) GetWithdrawalMethods(options ...GetWithdrawalMethodsOption) (*[]WithdrawalMethod, error)

Calls Kraken API private Funding "WithdrawMethods" endpoint. Retrieve a list of withdrawal methods available for the user. Accepts functional options args 'options'.

Required Permissions:

Funds permissions - Query; Funds permissions - Withdraw;

Functional Options:

// Filter methods for specific asset. Defaults to no filter if function is not
// called
func WMWithAsset(asset string) GetWithdrawalMethodsOption

// Filter methods for specific network. Defaults to no filter if function is not
// called
func WMWithNetwork(network string) GetWithdrawalMethodsOption

~// Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~

~func WMWithAssetClass(aclass string) GetWithdrawalMethodsOption~

Example Usage:

withdrawalMethods, err := kc.GetWithdrawalMethods(krakenspot.WMWithNetwork("Ethereum"))

func (*KrakenClient) GetWithdrawalsStatus

func (kc *KrakenClient) GetWithdrawalsStatus(options ...GetWithdrawalsStatusOption) (*[]WithdrawalStatus, error)

Calls Kraken API private Funding "WithdrawStatus" endpoint. Retrieves information about recent withdrawals. Results are sorted by recency, call method GetWithdrawalsStatusPaginated() instead to begin an iterated list of withdrawals. Accepts functional options args 'options'.

Required Permissions:

Funds permissions - Withdraw; OR Data - Query ledger entries;

Functional Options:

// Filter for specific asset being withdrawn
func WSWithAsset(asset string) GetWithdrawalsStatusOption

// Filter for specific name of withdrawal method
func WSWithMethod(method string) GetWithdrawalsStatusOption

// Start timestamp, withdrawals created strictly before will not be included in
// the response
func WSWithStart(start string) GetWithdrawalsStatusOption

// End timestamp, withdrawals created strictly after will be not be included in
// the response
func WSWithEnd(end string) GetWithdrawalsStatusOption

~// Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~

~func WSWithAssetClass(aclass string) GetWithdrawalsStatusOption~

Example Usage:

withdrawalStatus, err := kc.GetWithdrawalsStatus(krakenspot.WSWithMethod("Bank Frick (SWIFT)"))

func (*KrakenClient) GetWithdrawalsStatusPaginated

func (kc *KrakenClient) GetWithdrawalsStatusPaginated(options ...GetWithdrawalsStatusPaginatedOption) (*WithdrawalStatusPaginated, error)

Calls Kraken API private Funding "WithdrawStatus" endpoint. Begins a paginated list with information about recent withdrawals. Results are sorted by recency and filtered by functional options args 'options'. After list is initiated via this method, use with (kc *KrakenClient) GetWithdrawalsStatusWithCursor().

Required Permissions:

Funds permissions - Withdraw; OR Data - Query ledger entries;

Functional Options:

// Filter for specific asset being withdrawn
func WPWithAsset(asset string) GetWithdrawalsStatusPaginatedOption

// Filter for specific name of withdrawal method
func WPWithMethod(method string) GetWithdrawalsStatusPaginatedOption

// Start timestamp, withdrawals created strictly before will not be included in
// the response
func WPWithStart(start string) GetWithdrawalsStatusPaginatedOption

// End timestamp, withdrawals created strictly after will be not be included in
// the response
func WPWithEnd(end string) GetWithdrawalsStatusPaginatedOption

// Number of results to include per page. Defaults to 500 if function is not called
func WPWithLimit(limit int) GetWithdrawalsStatusPaginatedOption

~// Filter asset class being withdrawn. Defaults to "currency" if function is not called. As of 1/7/24, only known valid asset class is "currency"~

~func WPWithAssetClass(aclass string) GetWithdrawalsStatusPaginatedOption~

Example Usage:

withdrawalsResp, err := kc.GetWithdrawalsStatusPaginated(krakenspot.WPWithAsset("XBT"), krakenspot.WPWithLimit(5))
withdrawals := (*withdrawalsResp).Withdrawals
// do something with withdrawals
cursor := (*withdrawalsResp).NextCursor
for cursor != "" {
	withdrawalsResp, err = kc.GetWithdrawalsStatusWithCursor(cursor)
	// error handling
	withdrawals = (*withdrawalsResp).Withdrawals
	// do something withwithdrawals
	cursor = (*withdrawalsResp).NextCursor
}

func (*KrakenClient) GetWithdrawalsStatusWithCursor

func (kc *KrakenClient) GetWithdrawalsStatusWithCursor(cursor string) (*WithdrawalStatusPaginated, error)

Calls Kraken API private Funding "WithdrawStatus" endpoint. Requires arg 'cursor' which has been retrieved from a previous call to GetWithdrawalsStatusPaginated() method. Continues paginated list with information about recent withdrawals. Results are sorted by recency and filtered by 'options' passed to GetWithdrawalsStatusPaginated() previously.

Required Permissions:

Funds permissions - Withdraw; OR Data - Query ledger entries;

Example Usage:

withdrawalsResp, err := kc.GetWithdrawalsStatusPaginated(krakenspot.WPWithAsset("XBT"), krakenspot.WPWithLimit(5))
withdrawals := (*withdrawalsResp).Withdrawals
// do something with withdrawals
cursor := (*withdrawalsResp).NextCursor
for cursor != "" {
	withdrawalsResp, err = kc.GetWithdrawalsStatusWithCursor(cursor)
	// error handling
	withdrawals = (*withdrawalsResp).Withdrawals
	// do something withwithdrawals
	cursor = (*withdrawalsResp).NextCursor
}

func (*KrakenClient) ListAltNames

func (kc *KrakenClient) ListAltNames() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pairs' altnames. Sorted alphabetically.

func (*KrakenClient) ListAssets

func (kc *KrakenClient) ListAssets() ([]string, error)

Calls Kraken API public market data "Assets" endpoint. Returns a slice of strings of all tradeable asset names

func (*KrakenClient) ListOpenTxIDsForPair

func (kc *KrakenClient) ListOpenTxIDsForPair(pair string) ([]string, error)

Calls Kraken API private Account Data "OpenOrders" endpoint with default parameters filtered by orders for arg 'pair'. Returns a slice of transaction IDs of all open orders for the pair.

Required Permissions:

Order and Trades - Query open orders & trades;

Example Usage:

orders, err := kc.ListOpenTxIDsForPair("SOLUSD")

func (*KrakenClient) ListTopNumberTradesLast24Hours

func (kc *KrakenClient) ListTopNumberTradesLast24Hours(num ...uint16) ([]TickerTrades, error)

Calls Kraken API public market data "Ticker" endpoint. Returns a slice of tickers sorted descending by their last 24 hour number of trades. Calling this function without passing a value to arg num will return the entire list of sorted pairs. Passing a value to num will return a slice of the top num sorted pairs.

func (*KrakenClient) ListTopVolumeLast24Hours

func (kc *KrakenClient) ListTopVolumeLast24Hours(num ...uint16) ([]TickerVolume, error)

Calls Kraken API public market data "Ticker" endpoint. Returns a slice of tickers sorted descending by their last 24 hour USD volume. Calling this function without passing a value to arg num will return the entire list of sorted pairs. Passing a value to num will return a slice of the top num sorted pairs.

func (*KrakenClient) ListTradeablePairs

func (kc *KrakenClient) ListTradeablePairs() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pair names. Sorted alphabetically.

func (*KrakenClient) ListWebsocketNames

func (kc *KrakenClient) ListWebsocketNames() ([]string, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns slice of all tradeable pairs' websocket names. Sorted alphabetically.

func (*KrakenClient) MapWebsocketNames

func (kc *KrakenClient) MapWebsocketNames() (map[string]bool, error)

Calls Kraken API public market data "AssetPairs" endpoint and returns map of all tradeable websocket names for fast lookup.

func (*KrakenClient) RequestLedgersExportReport

func (kc *KrakenClient) RequestLedgersExportReport(description string, options ...RequestLedgersExportReportOption) (string, error)

Calls Kraken API private Account Data "AddExport" endpoint. Requests export of ledgers data to file, defaults to CSV file type. Returns string containing report ID or empty string if encountered error. Accepts functional options args 'options'.

Required Permissions:

Data - Query ledger entries; Data - Export data;

Functional Options:

// File format to export. Defaults to "CSV" if not called or invalid value
// passed to arg 'format'
//
// Enum: "CSV", "TSV"
func RLWithFormat(format string) RequestLedgersExportReportOption

// Accepts comma-delimited list of fields passed as a single string to include
// in report. Defaults to "all" if not called. API will return error:
// [EGeneral:Internal error] if invalid value passed to arg 'fields'. Function has
// no validation checks for passed value to 'fields'
//
// Enum: "refid", "time", "type", "aclass", "asset",
// "amount", "fee", "balance"
func RLWithFields(fields string) RequestLedgersExportReportOption

// UNIX timestamp for report start time. Defaults to 1st of the current month
// if not called
func RLWithStart(start int) RequestLedgersExportReportOption

// UNIX timestamp for report end time. Defaults to current time if not called
func RLWithEnd(end int) RequestLedgersExportReportOption

Example Usage:

reportID, err := kc.RequestLedgersExportReport("January 2021 Ledgers", krakenspot.RLWithStart(1609459200), krakenspot.RLWithEnd(1612137600), krakenspot.RLWithFields("time,type,asset,amount,balance"))

func (*KrakenClient) RequestTradesExportReport

func (kc *KrakenClient) RequestTradesExportReport(description string, options ...RequestTradesExportReportOption) (string, error)

Calls Kraken API private Account Data "AddExport" endpoint. Requests export of trades data to file, defaults to CSV file type. Returns string containing report ID or empty string if encountered error. Accepts functional options args 'options'.

Required Permissions:

Orders and trades - Query open orders and trades; Orders and trades - Query closed orders and trades; Data - Export data;

Functional Options:

// File format to export. Defaults to "CSV" if not called or invalid value
// passed to arg 'format'
//
// Enum: "CSV", "TSV"
func RTWithFormat(format string) RequestTradesExportReportOption

// Accepts comma-delimited list of fields passed as a single string to include
// in report. Defaults to "all" if not called. API will return error:
// [EGeneral:Internal error] if invalid value passed to arg 'fields'. Function has
// no validation checks for passed value to 'fields'
//
// Enum: "ordertxid", "time", "ordertype", "price", "cost", "fee", "vol",
// "margin", "misc", "ledgers"
func RTWithFields(fields string) RequestTradesExportReportOption

// UNIX timestamp for report start time. Defaults to 1st of the current month
// if not called
func RTWithStart(start int) RequestTradesExportReportOption

// UNIX timestamp for report end time. Defaults to current time if not called
func RTWithEnd(end int) RequestTradesExportReportOption

Example Usage:

reportID, err := kc.RequestTradesExportReport("January 2021 Trades", krakenspot.RTWithStart(1609459200), krakenspot.RTWithEnd(1612137600), krakenspot.RTWithFields("time,type,asset,amount,balance"))

func (*KrakenClient) RetrieveDataExport

func (kc *KrakenClient) RetrieveDataExport(reportID string, path ...string) error

Calls Kraken API private Account Data "RetrieveExport" endpoint. Retrieves a specified processed data export with the ID passed to arg 'reportID' and creates a file with the output. Accepts optional arg 'path' as the full desired path name. Defaults to creating .zip file in current directory if no path is entered.

Required Permissions:

Data - Export data;

Example Usage:

err := kc.RetrieveDataExport("TCJA", "C:/Users/User/Downloads/Reports/my-report.zip")

func (*KrakenClient) SetErrorLogger

func (kc *KrakenClient) SetErrorLogger(output io.Writer) *log.Logger

SetErrorLogger creates a new custom error logger for KrakenClient and its components. The logger logs to the provided 'output' io.Writer. This method also sets the created logger as the ErrorLogger for the KrakenClient and its WebSocketManager and WebSocketClients. It returns the newly created logger.

Example Usage:

// Open a file for logging
file, err := os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// Create a new KrakenClient
kc := krakenspot.NewKrakenClient()

// Set the KrakenClient logger to write to the file
logger := kc.SetErrorLogger(file)

// Now when you use the KrakenClient, it will log internal errors to the file
// But you still need to call the logger for externally returned errors
err = kc.Connect()
if err != nil {
	logger.Println("error connecting")
}

func (*KrakenClient) StartBalanceManager

func (kc *KrakenClient) StartBalanceManager() error

StartBalanceManager gets current account balances from Kraken's REST API and loads them into memory, then it starts a go routine which listens for completed trades from the "ownTrades" WebSocket channel and updates the balances accordingly. Must be used with an open subscription to "ownTrades" channel. This feature only tracks total balances. It does not track available balances for trading.

Note: Recommended use is to call SubscribeOwnTrades passing WithoutSnapshot to 'options' before StartBalanceManager as the snapshot message from the "ownTrades" channel will cause balances to be inaccurate. If snapshot message is required for some other reason, then call StartBalanceManager after SubscribeOwnTrades and before any trading occurs.

func (*KrakenClient) StartRESTRateLimiter

func (kc *KrakenClient) StartRESTRateLimiter() error

StartRESTRateLimiter starts self rate-limiting for general (everything except "order" type) REST API call methods. For this feature to work correctly, StartRESTRateLimiter must be called before any general REST API calls are made.

Note: This does not rate limit "trading" endpoint calls (such as AddOrder(), EditOrder(), or CancelOrder()).

Note: This feature adds processing and wait overhead so it should not be used if many consecutive general API calls won't be made, or if the application importing this package is performance critical and/or handling rate limiting itself.

func (*KrakenClient) StopRESTRateLimiter

func (kc *KrakenClient) StopRESTRateLimiter() error

StopRESTRateLimiter stops self rate-limiting for general (everything except "order" type) REST API call methods.

func (*KrakenClient) SystemIsOnline

func (kc *KrakenClient) SystemIsOnline() (bool, string, error)

Calls Kraken API public market data "SystemStatus" endpoint and returns true if system is online. Returns false and current status as a string if not online. Returns false and error if error produced from calling API.

Example Usage:

online, status := krakenspot.SystemIsOnline()
if !online {
	log.Println(status)
}

func (*KrakenClient) TotalUSDBalance

func (kc *KrakenClient) TotalUSDBalance() (float64, error)

Calls Kraken API private Account Data "Balance" endpoint. Returns float of total USD balance "ZUSD"

Required Permissions:

Funding Permissions - Query;

func (*KrakenClient) TransferToFutures

func (kc *KrakenClient) TransferToFutures(asset string, amount string) (string, error)

Calls Kraken API private Funding "WalletTransfer" endpoint. Transfers specified arg 'amount' of 'asset' from Kraken spot wallet to Kraken Futures wallet. Note that a transfer in the other direction must be requested via the Kraken Futures API endpoint for withdrawals to Spot wallets

Required Permissions:

Funds permissions - Query;

Example Usage:

refID, err := kc.TransferToFutures("ZUSD", "10000")

func (*KrakenClient) WithdrawFunds

func (kc *KrakenClient) WithdrawFunds(asset string, key string, amount string, options ...WithdrawFundsOption) (string, error)

Calls Kraken API private Funding "Withdraw" endpoint. Makes a withdrawal request for specified args 'asset', withdrawal key name 'key', and 'amount'. If successful, returns resulting reference ID as a string.

Required Permissions:

Funds permissions - Withdraw;

Functional Options:

// Optional, crypto address that can be used to confirm address matches key
// (will return Invalid withdrawal address error if different)
func WFWithAddress(address string) WithdrawFundsOption

// Optional, if the processed withdrawal fee is higher than max_fee, withdrawal
// will fail with EFunding:Max fee exceeded
func WFWithMaxFee(maxFee string) WithdrawFundsOption

Example Usage:

refID, err := kc.WithdrawFunds("XBT", "btc_testnet_with1", "0.725")

type Ledger

type Ledger struct {
	RefID      string  `json:"refid"`
	Time       float64 `json:"time"`
	Type       string  `json:"type"`
	SubType    string  `json:"subtype"`
	AssetClass string  `json:"aclass"`
	Asset      string  `json:"asset"`
	TxAmount   string  `json:"amount"`
	TxFee      string  `json:"fee"`
	EndBalance string  `json:"balance"`
}

type LedgersInfoResp

type LedgersInfoResp struct {
	Ledgers map[string]Ledger `json:"ledger"`
	Count   int               `json:"count"`
}

type LimitChase

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

type LimitChaseFill

type LimitChaseFill struct {
	FilledVol    decimal.Decimal
	RemainingVol decimal.Decimal
}

type LimitChaseManager

type LimitChaseManager struct {
	LimitChaseOrders map[int32]*LimitChase
	Mutex            sync.RWMutex
}

type LockType

type LockType struct {
	Type                    string `json:"type"`
	PayoutFrequency         int    `json:"payout_frequency"`
	BondingPeriod           int    `json:"bonding_period"`
	BondingPeriodVariable   bool   `json:"bonding_period_variable"`
	BondingRewards          bool   `json:"bonding_rewards"`
	ExitQueuePeriod         int    `json:"exit_queue_period"`
	UnbondingPeriod         int    `json:"unbonding_period"`
	UnbondingPeriodVariable bool   `json:"unbonding_period_variable"`
	UnbondingRewards        bool   `json:"unbonding_rewards"`
}

type MessageRouter

type MessageRouter interface {
	// contains filtered or unexported methods
}

type OHLCData

type OHLCData struct {
	Time   uint64
	Open   string
	High   string
	Low    string
	Close  string
	VWAP   string
	Volume string
	Count  uint32
}

type OHLCDataSlice

type OHLCDataSlice []OHLCData

type OHLCResp

type OHLCResp struct {
	Ticker  string
	Data    OHLCDataSlice
	Current OHLCData
	Last    uint64 `json:"last"`
}

func GetOHLC

func GetOHLC(pair string, interval uint16, since ...uint64) (*OHLCResp, error)

Calls Kraken API public market data "OHLC" endpoint. Gets OHLC data for specified pair of the required interval (in minutes).

Accepts optional arg since as a start time in Unix for the However, per the Kraken API docs "Note: the last entry in the OHLC array is for the current, not-yet-committed frame and will always be present, regardless of the value of since.

Enum - 'interval': 1, 5, 15, 30, 60, 240, 1440, 10080, 21600

func (*OHLCResp) UnmarshalJSON

func (ohlc *OHLCResp) UnmarshalJSON(data []byte) error

type OpenOrderManager

type OpenOrderManager struct {
	OpenOrders map[string]WSOpenOrder
	// contains filtered or unexported fields
}

type OpenOrdersResp

type OpenOrdersResp struct {
	OpenOrders map[string]Order `json:"open"`
}

type OpenPosition

type OpenPosition struct {
	OrderTxID      string  `json:"ordertxid"`
	PositionStatus string  `json:"posstatus"`
	Pair           string  `json:"pair"`
	Time           float64 `json:"time"`
	Direction      string  `json:"type"`
	OrderType      string  `json:"ordertype"`
	QuoteCost      string  `json:"cost"`
	QuoteFee       string  `json:"fee"`
	Size           string  `json:"vol"`
	VolumeClosed   string  `json:"vol_closed"`
	InitialMargin  string  `json:"margin"`
	CurrentValue   string  `json:"value"`
	UPnL           string  `json:"net"`
	Terms          string  `json:"terms"`
	RolloverTime   string  `json:"rollovertm"`
	Misc           string  `json:"misc"`
	OrderFlags     string  `json:"oflags"`
}

type OpenPositionConsolidated

type OpenPositionConsolidated struct {
	Pair          string `json:"pair"`
	Direction     string `json:"type"`
	Size          string `json:"vol"`
	VolumeClosed  string `json:"vol_closed"`
	QuoteCost     string `json:"cost"`
	QuoteFee      string `json:"fee"`
	Leverage      string `json:"leverage"`
	InitialMargin string `json:"margin"`
	UPnL          string `json:"net"`
	NumPositions  string `json:"positions"`
	CurrentValue  string `json:"value"`
}

type OptionType

type OptionType int
const (
	SubscriptionOption OptionType = iota
	PrivateReqIDOption
	SnapshotOption
)

type Order

type Order struct {
	RefID          string           `json:"refid"`
	UserRef        int              `json:"userref"`
	Status         string           `json:"status"`
	OpenTime       float64          `json:"opentm"`
	StartTime      float64          `json:"starttm"`
	ExpireTime     float64          `json:"expiretm"`
	Description    OrderDescription `json:"descr"`
	Volume         string           `json:"vol"`
	VolumeExecuted string           `json:"vol_exec"`
	QuoteCost      string           `json:"cost"`
	QuoteFee       string           `json:"fee"`
	AvgPrice       string           `json:"price"`
	StopPrice      string           `json:"stopprice"`
	LimitPrice     string           `json:"limitprice"`
	Trigger        string           `json:"trigger"`
	Misc           string           `json:"misc"`
	OrderFlags     string           `json:"oflags"`
	TradeIDs       []string         `json:"trades"`
	CloseTime      float64          `json:"closetm,omitempty"`
	Reason         string           `json:"reason,omitempty"`
}

type OrderBook

type OrderBook struct {
	Ticker string
	Asks   []BookEntry `json:"asks"`
	Bids   []BookEntry `json:"bids"`
}

func GetOrderBook

func GetOrderBook(pair string, count ...uint16) (*OrderBook, error)

Calls Kraken API public market data "Depth" endpoint. Gets arrays of bids and asks for arg 'pair'. Optional arg 'count' will return count number of each bids and asks. Not passing an arg to 'count' will default to 100.

Enum - 'count': [1..500]

type OrderBookManager

type OrderBookManager struct {
	OrderBooks map[string]map[string]*InternalOrderBook
	// contains filtered or unexported fields
}

Internal order book management

type OrderDescription

type OrderDescription struct {
	Pair             string `json:"pair"`
	Direction        string `json:"type"`
	OrderType        string `json:"ordertype"`
	Price            string `json:"price"`  // Limit price for limit orders. Trigger price for stop-loss, stop-loss-limit, take-profit, take-profit-limit, trailing-stop, and trailing-stop-limit orders
	Price2           string `json:"price2"` // Secondary limit price for stop-loss-limit, take-profit-limit, and trailing-stop-limit orders
	Leverage         string `json:"leverage"`
	Description      string `json:"order"`
	CloseDescription string `json:"close"`
}

type OrderType

type OrderType func(payload url.Values)

func Limit

func Limit(price string) OrderType

Order type of "limit" where arg 'price' is the level at which the limit order will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func Market

func Market() OrderType

Instantly market orders in at best current prices

func SettlePosition

func SettlePosition(leverage string) OrderType

Order type of "settle-position". Settles any open margin position of same 'direction' and 'pair' by amount 'volume'

Note: AddOrder() arg 'volume' can be set to "0" for closing margin orders to automatically fill the requisite quantity

Note: Required arg 'leverage' is a required parameter by the API, but in practice can be any valid value. Value of 'leverage' here has no effect as leverage is already set by the opened position.

func StopLoss

func StopLoss(price string) OrderType

Order type of "stop-loss" order type where arg 'price' is the stop loss trigger price

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func StopLossLimit

func StopLossLimit(price, price2 string) OrderType

Order type of "stop-loss-limit" where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func TakeProfit

func TakeProfit(price string) OrderType

Order type of "take-profit" where arg 'price' is the take profit trigger price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func TakeProfitLimit

func TakeProfitLimit(price, price2 string) OrderType

Order type of "take-profit-limit" where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func TrailingStop

func TrailingStop(price string) OrderType

Order type of "trailing-stop" where arg 'price' is the relative stop trigger price.

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func TrailingStopLimit

func TrailingStopLimit(price, price2 string) OrderType

Order type of "trailing-stop-limit" where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed.

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

type ReconnectManager

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

type ReqIDOption

type ReqIDOption func(buffer *bytes.Buffer)

func ReqID

func ReqID(reqID string) ReqIDOption

type RequestExportReportResp

type RequestExportReportResp struct {
	ID string `json:"id"`
}

type RequestLedgersExportReportOption

type RequestLedgersExportReportOption func(payload url.Values)

func RLWithEnd

UNIX timestamp for report end time. Defaults to current time if not called

func RLWithFields

func RLWithFields(fields string) RequestLedgersExportReportOption

Accepts comma-delimited list of fields passed as a single string to include in report. Defaults to "all" if not called. API will return error: [EGeneral:Internal error] if invalid value passed to arg 'fields'. Function has no validation checks for passed value to 'fields'

Enum: "refid", "time", "type", "aclass", "asset", "amount", "fee", "balance"

func RLWithFormat

func RLWithFormat(format string) RequestLedgersExportReportOption

File format to export. Defaults to "CSV" if not called or invalid value passed to arg 'format'

Enum: "CSV", "TSV"

func RLWithStart

func RLWithStart(start int) RequestLedgersExportReportOption

UNIX timestamp for report start time. Defaults to 1st of the current month if not called

type RequestTradesExportReportOption

type RequestTradesExportReportOption func(payload url.Values)

func RTWithEnd

func RTWithEnd(end int) RequestTradesExportReportOption

UNIX timestamp for report end time. Defaults to current time if not called

func RTWithFields

func RTWithFields(fields string) RequestTradesExportReportOption

Accepts comma-delimited list of fields passed as a single string to include in report. Defaults to "all" if not called. API will return error: [EGeneral:Internal error] if invalid value passed to arg 'fields'. Function has no validation checks for passed value to 'fields'

Enum: "ordertxid", "time", "ordertype", "price", "cost", "fee", "vol", "margin", "misc", "ledgers"

func RTWithFormat

func RTWithFormat(format string) RequestTradesExportReportOption

File format to export. Defaults to "CSV" if not called or invalid value passed to arg 'format'

Enum: "CSV", "TSV"

func RTWithStart

func RTWithStart(start int) RequestTradesExportReportOption

UNIX timestamp for report start time. Defaults to 1st of the current month if not called

type ServerTime

type ServerTime struct {
	UnixTime int    `json:"unixtime"`
	Rfc1123  string `json:"rfc1123"`
}

func GetServerTime

func GetServerTime() (*ServerTime, error)

Calls Kraken API public market data "Time" endpoint. Gets the server's time. ServerTime struct

type Spread

type Spread struct {
	Time uint64
	Bid  string
	Ask  string
}

type SpreadResp

type SpreadResp struct {
	Ticker  string
	Spreads SpreadSlice
	Last    uint64 `json:"last"`
}

func GetSpread

func GetSpread(pair string, since ...uint64) (*SpreadResp, error)

Calls Kraken API public market data "Spread" endpoint. Returns the last ~200 top-of-book spreads for given arg 'pair'.

Note: arg 'since' intended for incremental updates within available dataset (does not contain all historical spreads)

func (*SpreadResp) UnmarshalJSON

func (sr *SpreadResp) UnmarshalJSON(data []byte) error

type SpreadSlice

type SpreadSlice []Spread

type SubscribeOpenOrdersOption

type SubscribeOpenOrdersOption interface {
	Apply(*bytes.Buffer)
	Type() OptionType
}

func SubscribeOpenOrdersReqID

func SubscribeOpenOrdersReqID(reqID string) SubscribeOpenOrdersOption

Attach optional request ID 'reqID' to request

func WithRateCounter

func WithRateCounter() SubscribeOpenOrdersOption

Whether to send rate-limit counter in updates Defaults to false if not called.

type SubscribeOwnTradesOption

type SubscribeOwnTradesOption interface {
	Apply(*bytes.Buffer)
	Type() OptionType
}

func SubscribeOwnTradesReqID

func SubscribeOwnTradesReqID(reqID string) SubscribeOwnTradesOption

Attach optional request ID 'reqID' to request

func WithoutConsolidatedTaker

func WithoutConsolidatedTaker() SubscribeOwnTradesOption

Whether to consolidate order fills by root taker trade(s). If false, all order fills will show separately. Defaults to true if not called.

func WithoutSnapshot

func WithoutSnapshot() SubscribeOwnTradesOption

Whether to send historical feed data snapshot upon subscription. Defaults to true if not called.

type Subscription

type Subscription struct {
	ChannelName         string
	Pair                string
	DataChan            chan interface{}
	DoneChan            chan struct{}
	ConfirmedChan       chan struct{}
	DataChanClosed      int32
	DoneChanClosed      int32
	ConfirmedChanClosed int32
	Callback            GenericCallback
}

type SubscriptionManager

type SubscriptionManager struct {
	PublicSubscriptions  map[string]map[string]*Subscription
	PrivateSubscriptions map[string]*Subscription
	SubscribeWaitGroup   sync.WaitGroup
	// contains filtered or unexported fields
}

Keeps track of all open subscriptions

type SystemStatus

type SystemStatus struct {
	Status    string `json:"status"`
	Timestamp string `json:"timestamp"`
}

func GetSystemStatus

func GetSystemStatus() (*SystemStatus, error)

Calls Kraken API public market data "SystemStatus" endpoint. Gets the current system status or trading mode

Example Usage:

status, err := krakenspot.GetSystemStatus()
log.Println(status.Status)
log.Println(status.Timestamp)

type TickerBookInfo

type TickerBookInfo struct {
	Price          string
	WholeLotVolume string
	LotVolume      string
}

func (*TickerBookInfo) UnmarshalJSON

func (ti *TickerBookInfo) UnmarshalJSON(data []byte) error

type TickerDailyInfo

type TickerDailyInfo struct {
	Today       string
	Last24Hours string
}

func (*TickerDailyInfo) UnmarshalJSON

func (ti *TickerDailyInfo) UnmarshalJSON(data []byte) error

type TickerDailyInfoInt

type TickerDailyInfoInt struct {
	Today       int
	Last24Hours int
}

func (*TickerDailyInfoInt) UnmarshalJSON

func (ti *TickerDailyInfoInt) UnmarshalJSON(data []byte) error

type TickerInfo

type TickerInfo struct {
	Ticker          string
	Ask             TickerBookInfo      `json:"a"`
	Bid             TickerBookInfo      `json:"b"`
	LastTradeClosed TickerLastTradeInfo `json:"c"`
	Volume          TickerDailyInfo     `json:"v"`
	VWAP            TickerDailyInfo     `json:"p"`
	NumberOfTrades  TickerDailyInfoInt  `json:"t"`
	Low             TickerDailyInfo     `json:"l"`
	High            TickerDailyInfo     `json:"h"`
	Open            string              `json:"o"`
}

type TickerLastTradeInfo

type TickerLastTradeInfo struct {
	Price     string
	LotVolume string
}

func (*TickerLastTradeInfo) UnmarshalJSON

func (ti *TickerLastTradeInfo) UnmarshalJSON(data []byte) error

type TickerTrades

type TickerTrades struct {
	Ticker    string
	NumTrades int
}

func ListTopNumberTradesLast24Hours

func ListTopNumberTradesLast24Hours(num ...uint16) ([]TickerTrades, error)

Calls Kraken API public market data "Ticker" endpoint. Returns a slice of tickers sorted descending by their last 24 hour number of trades. Calling this function without passing a value to arg num will return the entire list of sorted pairs. Passing a value to num will return a slice of the top num sorted pairs.

type TickerVolume

type TickerVolume struct {
	Ticker string
	Volume float64
}

func ListTopVolumeLast24Hours

func ListTopVolumeLast24Hours(num ...uint16) ([]TickerVolume, error)

Calls Kraken API public market data "Ticker" endpoint. Returns a slice of tickers sorted descending by their last 24 hour USD volume. Calling this function without passing a value to arg num will return the entire list of sorted pairs. Passing a value to num will return a slice of the top num sorted pairs.

type Trade

type Trade struct {
	Price     string
	Volume    string
	Time      float64
	Direction string
	OrderType string
	Misc      string
	TradeID   float64
}

type TradeBalance

type TradeBalance struct {
	EquivalentBalance string `json:"eb"`
	TradeBalance      string `json:"tb"`
	OpenMargin        string `json:"m"`
	UnrealizedPnL     string `json:"n"`
	CostBasis         string `json:"c"`
	FloatingValuation string `json:"v"`
	Equity            string `json:"e"`
	FreeMargin        string `json:"mf"`
	MarginLevel       string `json:"ml"`
	UnexecutedValue   string `json:"uv"`
}

type TradeInfo

type TradeInfo struct {
	OrderTxID           string   `json:"ordertxid"`
	PositionTxID        string   `json:"postxid"`
	Pair                string   `json:"pair"`
	Time                float64  `json:"time"`
	Direction           string   `json:"type"`
	OrderType           string   `json:"ordertype"`
	AvgPrice            string   `json:"price"`
	QuoteCost           string   `json:"cost"`
	QuoteFee            string   `json:"fee"`
	Volume              string   `json:"vol"`
	InitialMargin       string   `json:"margin"`
	Leverage            string   `json:"leverage"`
	Misc                string   `json:"misc"`
	TradeID             int      `json:"trade_id"`
	PositionStatus      string   `json:"posstatus"`
	PortionClosedPrice  string   `json:"cprice"`
	PortionClosedCost   string   `json:"ccost"`
	PortionClosedFee    string   `json:"cfee"`
	PortionClosedVolume string   `json:"cvol"`
	PortionMarginFreed  string   `json:"cmargin"`
	PortionClosedPnL    string   `json:"net"`
	Trades              []string `json:"trades"`
	Maker               bool     `json:"maker"`
}

type TradeLogger

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

type TradeSlice

type TradeSlice []Trade

type TradeVolume

type TradeVolume struct {
	Currency      string         `json:"currency"`
	CurrentVolume string         `json:"volume"`
	Fees          map[string]Fee `json:"fees"`
	MakerFees     map[string]Fee `json:"fees_maker"`
}

type TradesHistoryResp

type TradesHistoryResp struct {
	Trades map[string]TradeInfo `json:"trades"`
}

type TradesResp

type TradesResp struct {
	Ticker string
	Trades TradeSlice
	Last   float64 `json:"last"`
}

func GetTrades

func GetTrades(pair string, count ...uint16) (*TradesResp, error)

Calls Kraken API public market data "Trades" endpoint. Gets the most recent trades for arg 'pair'. Accepts optional arg 'count' to get 'count' number of recent trades. Not passing an arg to 'count' will default to 1000

Enum - 'count': [1..1000]

func GetTradesSince

func GetTradesSince(pair string, since uint64, count ...uint16) (*TradesResp, error)

Calls Kraken API public market data "Trades" endpoint. Gets the trades after unix time arg 'since' for arg 'pair'. Accepts optional arg 'count' to get 'count' number of trades after 'since'. Not passing an arg to 'count' will default to 1000

Enum - 'count': [1..1000]

func (*TradesResp) UnmarshalJSON

func (tr *TradesResp) UnmarshalJSON(data []byte) error

type TradingRateLimiter

type TradingRateLimiter struct {
	HandleRateLimit      atomic.Bool
	Counters             map[string]*atomic.Int32
	UnbufferedMaxCounter int32
	MaxCounter           int32
	CounterDecay         uint16 // milliseconds per 1 counter decay
	CounterDecayConds    map[string]*sync.Cond
	Mutex                sync.Mutex
}

type UnsubscribeOpenOrdersOption

type UnsubscribeOpenOrdersOption func(*bytes.Buffer)

func UnsubscribeOpenOrdersReqID

func UnsubscribeOpenOrdersReqID(reqID string) UnsubscribeOpenOrdersOption

type UnsubscribeOwnTradesOption

type UnsubscribeOwnTradesOption func(buffer *bytes.Buffer)

func UnsubscribeOwnTradesReqID

func UnsubscribeOwnTradesReqID(reqID string) UnsubscribeOwnTradesOption

Attach optional request ID 'reqID' to request

type WSAddOrderOption

type WSAddOrderOption func(buffer *bytes.Buffer)

func WSAddOrderReqID

func WSAddOrderReqID(reqID string) WSAddOrderOption

Attach optional request ID 'reqID' to request

func WSAddWithDeadline

func WSAddWithDeadline(deadline string) WSAddOrderOption

Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching engine should reject the new order request to arg 'deadline'.

In presence of latency or order queueing: min now() + 2 seconds, max now() + 60 seconds.

Example Usage:

WSAddWithDeadline(time.Now().Add(time.Second*30).Format(time.RFC3339))

func WSCloseLimit

func WSCloseLimit(price string) WSAddOrderOption

Conditional close of "limit" order type where arg 'price' is the level at which the limit order will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseStopLoss

func WSCloseStopLoss(price string) WSAddOrderOption

Conditional close of "stop-loss" order type where arg 'price' is the stop loss trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseStopLossLimit

func WSCloseStopLossLimit(price, price2 string) WSAddOrderOption

Conditional close of "stop-loss-limit" order type where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseTakeProfit

func WSCloseTakeProfit(price string) WSAddOrderOption

Conditional close of "take-profit" order type where arg 'price' is the take profit trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseTakeProfitLimit

func WSCloseTakeProfitLimit(price, price2 string) WSAddOrderOption

Conditional close of "take-profit-limit" order type where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseTrailingStop

func WSCloseTrailingStop(price string) WSAddOrderOption

Conditional close of "trailing-stop" order type where arg 'price' is the relative stop trigger price.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSCloseTrailingStopLimit

func WSCloseTrailingStopLimit(price, price2 string) WSAddOrderOption

Conditional close of "trailing-stop-limit" order type where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed.

CAUTION: Mutually exclusive with other conditional close order functions. Only one conditional close order function with format WSClose<orderType>() should be passed at a time. If more than one are passed, it will override the previous function calls.

Conditional Close Orders: Orders that are triggered by execution of the primary order in the same quantity and opposite direction, but once triggered are independent orders that may reduce or increase net position

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSFCIB

func WSFCIB() WSAddOrderOption

Prefer fee in base currency (default if selling)

CAUTION: Mutually exclusive with FCIQ(). Only call one of these two at a time

func WSFCIQ

func WSFCIQ() WSAddOrderOption

Prefer fee in quote currency (default if buying)

CAUTION: Mutually exclusive with FCIB(). Only call one of these two at a time

func WSGoodTilDate

func WSGoodTilDate(expireTime string) WSAddOrderOption

Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "GTD" (Good Til Date). GTD, if called, will cause the order to expire at specified unix time passed to arg 'expireTime'. Expiration time, can be specified as an absolute timestamp or as a number of seconds in the future:

0 no expiration (default)

<n> = unix timestamp of expiration time

+<n> = expire <n> seconds from now, minimum 5 seconds

Note: URL encoding of the + character changes it to a space, so please use %2b followed by the number of seconds instead of +

CAUTION: Mutually exclusive with ImmediateOrCancel(). Only one of these two functions should be called, if any. Order will still pass as valid but one "timeinforce" value will be overridden.

func WSImmediateOrCancel

func WSImmediateOrCancel() WSAddOrderOption

Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "IOC" (Immediate Or Cancel). IOC will immediately execute the amount possible and cancel any remaining balance rather than resting in the book. Defaults to "GTC" (Good 'Til Canceled) if function is not called.

CAUTION: Mutually exclusive with GoodTilDate(). Only one of these two functions should be called, if any. Order will still pass as valid but one "timeinforce" value will be overridden.

func WSLeverage

func WSLeverage(leverage string) WSAddOrderOption

Amount of leverage desired. Defaults to no leverage if function is not called. API accepts string of any number; in practice, must be some integer >= 2

Note: This function should not be used when calling AddOrder() with the SettlePosition() 'orderType'

func WSNOMPP

func WSNOMPP() WSAddOrderOption

Disables market price protection for market orders

func WSOrderFlags

func WSOrderFlags(flags string) WSAddOrderOption

Add all desired order 'flags' as a single comma-delimited list. Use either this function or call (one or many) the individual flag functions below.

Note: "post" is only available for WSLimit() type orders. "nompp" is only available for WSMarket() type orders

CAUTION: "fciq" and "fcib" are mutually exclusive, only call one or neither at a time

CAUTION: Do not pass this function with any of WSPostOnly(), WSFCIB(), WSFCIQ(), WSNOMPP(), WSVIQC()

Enums:

'flags': "post", "fciq", "fcib", "nompp", ~"viqc"~

Example Usage:

kc.WSAddOrder(WSLimit("42100.2"), "XBT/USD", "1.0", WSOrderFlags("post,fciq"))

func WSPostOnly

func WSPostOnly() WSAddOrderOption

Post-only order (available when ordertype = limit)

func WSReduceOnly

func WSReduceOnly() WSAddOrderOption

If true, order will only reduce a currently open position, not increase it or open a new position. Defaults to false if not passed.

Note: ReduceOnly() is only usable with leveraged orders. This includes orders of 'orderType' SettlePosition() and orders with Leverage() passed to 'options'

func WSUserRef

func WSUserRef(userRef string) WSAddOrderOption

User reference id 'userref' is an optional user-specified integer id that can be associated with any number of orders. Many clients choose a userref corresponding to a unique integer id generated by their systems (e.g. a timestamp). However, because we don't enforce uniqueness on our side, it can also be used to easily group orders by pair, side, strategy, etc. This allows clients to more readily cancel or query information about orders in a particular group, with fewer API calls by using userref instead of our txid, where supported.

func WSVIQC

func WSVIQC() WSAddOrderOption

Order volume expressed in quote currency. This is supported only for market orders.

Note: Not currently available

func WSValidateAddOrder

func WSValidateAddOrder() WSAddOrderOption

Validates inputs only. Does not submit order. Defaults to "false" if not called.

type WSAddOrderResp

type WSAddOrderResp struct {
	Event        string `json:"event"`
	RequestID    int    `json:"reqid"`
	Status       string `json:"status"`
	TxID         string `json:"txid"`
	Description  string `json:"descr"`
	ErrorMessage string `json:"errorMessage"`
}

type WSBookEntry

type WSBookEntry struct {
	Price      string
	Volume     string
	Time       string
	UpdateType string
}

func (*WSBookEntry) UnmarshalJSON

func (s *WSBookEntry) UnmarshalJSON(data []byte) error

type WSBookSnapshotResp

type WSBookSnapshotResp struct {
	ChannelID   int `json:"channelID"`
	OrderBook   WSOrderBookSnapshot
	ChannelName string `json:"channelName"`
	Pair        string `json:"pair"`
}

func (*WSBookSnapshotResp) UnmarshalJSON

func (s *WSBookSnapshotResp) UnmarshalJSON(data []byte) error

type WSBookUpdateResp

type WSBookUpdateResp struct {
	ChannelID   int
	Asks        []WSBookEntry
	Bids        []WSBookEntry
	Checksum    string
	ChannelName string
	Pair        string
}

func (*WSBookUpdateResp) UnmarshalJSON

func (bu *WSBookUpdateResp) UnmarshalJSON(data []byte) error

type WSCancelAllAfterResp

type WSCancelAllAfterResp struct {
	Event        string `json:"event"`
	RequestID    int    `json:"reqid"`
	Status       string `json:"status"`
	CurrentTime  string `json:"currentTime"`
	TriggerTime  string `json:"triggerTime"`
	ErrorMessage string `json:"errorMessage"`
}

type WSCancelAllResp

type WSCancelAllResp struct {
	Event        string `json:"event"`
	RequestID    int    `json:"reqid"`
	Count        int    `json:"count"`
	Status       string `json:"status"`
	ErrorMessage string `json:"errorMessage"`
}

type WSCancelOrderResp

type WSCancelOrderResp struct {
	Event        string `json:"event"`
	RequestID    int    `json:"reqid"`
	Status       string `json:"status"`
	ErrorMessage string `json:"errorMessage"`
}

type WSContingent

type WSContingent struct {
	OrderType  string `json:"ordertype"`
	Price      string `json:"price"`
	Price2     string `json:"price2"`
	OrderFlags string `json:"oflags"`
}

type WSEditOrderOption

type WSEditOrderOption func(buffer *bytes.Buffer)

func WSEditOrderReqID

func WSEditOrderReqID(reqID string) WSEditOrderOption

Attach optional request ID 'reqID' to request

func WSNewPostOnly

func WSNewPostOnly() WSEditOrderOption

Post-only order (available when ordertype = limit). All the flags from the parent order are retained except post-only. Post-only needs to be explicitly mentioned on every edit request.

func WSNewPrice

func WSNewPrice(price string) WSEditOrderOption

Updates limit price for "limit" orders. Updates trigger price for "stop-loss", "stop-loss-limit", "take-profit", "take-profit-limit", "trailing-stop" and "trailing-stop-limit" orders

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

Trailing Stops: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

func WSNewPrice2

func WSNewPrice2(price2 string) WSEditOrderOption

Updates limit price for "stop-loss-limit", "take-profit-limit" and "trailing-stop-limit" orders

Trailing Stops Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

func WSNewUserRef

func WSNewUserRef(userRef string) WSEditOrderOption

Field "userref" is an optional user-specified integer id associated with edit request.

Note: userref from parent order will not be retained on the new order after edit.

func WSNewVolume

func WSNewVolume(volume string) WSEditOrderOption

Updates order quantity in terms of the base asset.

func WSValidateEditOrder

func WSValidateEditOrder() WSEditOrderOption

Validate inputs only. Do not submit order. Defaults to false if not called.

type WSEditOrderResp

type WSEditOrderResp struct {
	Event        string `json:"event"`
	RequestID    int    `json:"reqid"`
	Status       string `json:"status"`
	TxID         string `json:"txid"`
	OriginalTxID string `json:"originaltxid"`
	Description  string `json:"descr"`
	ErrorMessage string `json:"errorMessage"`
}

type WSErrorResp

type WSErrorResp struct {
	Event        string `json:"event"`
	ErrorMessage string `json:"errorMessage"`
	ReqID        int    `json:"reqid"`
}

type WSOHLC

type WSOHLC struct {
	Time    string
	EndTime string
	Open    string
	High    string
	Low     string
	Close   string
	VWAP    string
	Volume  string
	Count   int
}

func (*WSOHLC) UnmarshalJSON

func (w *WSOHLC) UnmarshalJSON(data []byte) error

type WSOHLCResp

type WSOHLCResp struct {
	ChannelID   int `json:"channelID"`
	OHLC        WSOHLC
	ChannelName string `json:"channelName"`
	Pair        string `json:"pair"`
}

func (*WSOHLCResp) UnmarshalJSON

func (w *WSOHLCResp) UnmarshalJSON(data []byte) error

type WSOpenOrder

type WSOpenOrder struct {
	RefID               string             `json:"refid"`
	UserRef             int                `json:"userref"`
	Status              string             `json:"status"`
	OpenTime            string             `json:"opentm"`
	StartTime           string             `json:"starttm"`
	DisplayVolume       string             `json:"display_volume"`
	DisplayVolumeRemain string             `json:"display_volume_remain"`
	ExpireTime          string             `json:"expiretm"`
	ContingentOrder     WSContingent       `json:"contingent"`
	Description         WSOrderDescription `json:"descr"`
	LastUpdateTime      string             `json:"lastupdated"`
	VolumeExecuted      string             `json:"vol_exec"`
	QuoteCost           string             `json:"cost"`
	QuoteFee            string             `json:"fee"`
	AvgPrice            string             `json:"avg_price"`
	TrailingStopPrice   string             `json:"stopprice"`
	TriggeredLimitPrice string             `json:"limitprice"`
	Misc                string             `json:"misc"`
	OrderFlags          string             `json:"oflags"`
	TimeInForce         string             `json:"timeinforce"`
	CancelReason        string             `json:"cancel_reason"`
	RateCount           int                `json:"ratecount"`
}

type WSOpenOrdersResp

type WSOpenOrdersResp struct {
	OpenOrders  []map[string]WSOpenOrder
	ChannelName string
	Sequence    int
}

func (*WSOpenOrdersResp) UnmarshalJSON

func (oo *WSOpenOrdersResp) UnmarshalJSON(data []byte) error

type WSOrderBook

type WSOrderBook struct {
	Asks     []WSBookEntry `json:"a"`
	Bids     []WSBookEntry `json:"b"`
	Checksum string        `json:"c"`
}

type WSOrderBookSnapshot

type WSOrderBookSnapshot struct {
	Asks []WSBookEntry `json:"as"`
	Bids []WSBookEntry `json:"bs"`
}

type WSOrderDescription

type WSOrderDescription struct {
	Pair             string `json:"pair"`
	Direction        string `json:"type"`
	OrderType        string `json:"ordertype"`
	Price            string `json:"price"`  // Limit price for limit orders. Trigger price for stop-loss, stop-loss-limit, take-profit, take-profit-limit, trailing-stop, and trailing-stop-limit orders
	Price2           string `json:"price2"` // Secondary limit price for stop-loss-limit, take-profit-limit, and trailing-stop-limit orders
	Leverage         string `json:"leverage"`
	Description      string `json:"order"`
	CloseDescription string `json:"close"`
}

type WSOrderType

type WSOrderType func(buffer *bytes.Buffer)

func WSLimit

func WSLimit(price string) WSOrderType

Order type of "limit" where arg 'price' is the level at which the limit order will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSMarket

func WSMarket() WSOrderType

Instantly market orders in at best current prices

func WSSettlePosition

func WSSettlePosition(leverage string) WSOrderType

Order type of "settle-position". Settles any open margin position of same 'direction' and 'pair' by amount 'volume'

Note: AddOrder() arg 'volume' can be set to "0" for closing margin orders to automatically fill the requisite quantity

Note: Required arg 'leverage' is a required parameter by the API, but in practice can be any valid value. Value of 'leverage' here has no effect as leverage is already set by the opened position.

func WSStopLoss

func WSStopLoss(price string) WSOrderType

Order type of "stop-loss" order type where arg 'price' is the stop loss trigger price

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSStopLossLimit

func WSStopLossLimit(price, price2 string) WSOrderType

Order type of "stop-loss-limit" where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSTakeProfit

func WSTakeProfit(price string) WSOrderType

Order type of "take-profit" where arg 'price' is the take profit trigger price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSTakeProfitLimit

func WSTakeProfitLimit(price, price2 string) WSOrderType

Order type of "take-profit-limit" where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSTrailingStop

func WSTrailingStop(price string) WSOrderType

Order type of "trailing-stop" where arg 'price' is the relative stop trigger price.

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

func WSTrailingStopLimit

func WSTrailingStopLimit(price, price2 string) WSOrderType

Order type of "trailing-stop-limit" where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed.

Note: Required arg 'price' must use a relative price for this field, namely the + prefix, from which the direction will be automatic based on if the original order is a buy or sell (no need to use - or #). The % suffix also works for these order types to use a relative percentage price.

Note: In practice, the system will accept either relative or specific (without + or -) for arg 'price2' despite what the docs say. The note is included here just in case; Kraken API docs: Must use a relative price for this field, namely one of the + or - prefixes. This will provide the offset from the trigger price to the limit price, i.e. +0 would set the limit price equal to the trigger price. The % suffix also works for this field to use a relative percentage limit price.

Relative Prices: Either price or price2 can (and sometimes must) be preceded by +, -, or # to specify the order price as an offset relative to the last traded price. + adds the amount to, and - subtracts the amount from the last traded price. # will either add or subtract the amount to the last traded price, depending on the direction and order type used. Prices can also be suffixed with a % to signify the relative amount as a percentage, rather than an absolute price difference.

type WSOwnTrade

type WSOwnTrade struct {
	OrderTxID     string `json:"ordertxid"`
	PositionTxID  string `json:"postxid"`
	Pair          string `json:"pair"`
	Time          string `json:"time"`
	Direction     string `json:"type"`
	OrderType     string `json:"ordertype"`
	AvgPrice      string `json:"price"`
	QuoteCost     string `json:"cost"`
	QuoteFee      string `json:"fee"`
	Volume        string `json:"vol"`
	InitialMargin string `json:"margin"`
	UserRef       int32  `json:"userref"`
}

type WSOwnTradesResp

type WSOwnTradesResp struct {
	OwnTrades   []map[string]WSOwnTrade
	ChannelName string
	Sequence    int
}

func (*WSOwnTradesResp) UnmarshalJSON

func (ot *WSOwnTradesResp) UnmarshalJSON(data []byte) error

type WSPong

type WSPong struct {
	Event string `json:"event"`
	ReqID int    `json:"reqid"`
}

type WSSequence

type WSSequence struct {
	Sequence int `json:"sequence"`
}

type WSSpread

type WSSpread struct {
	Bid       string
	Ask       string
	Time      string
	BidVolume string
	AskVolume string
}

func (*WSSpread) UnmarshalJSON

func (s *WSSpread) UnmarshalJSON(data []byte) error

type WSSpreadResp

type WSSpreadResp struct {
	ChannelID   int `json:"channelID"`
	Spread      WSSpread
	ChannelName string `json:"channelName"`
	Pair        string `json:"pair"`
}

func (*WSSpreadResp) UnmarshalJSON

func (s *WSSpreadResp) UnmarshalJSON(data []byte) error

type WSSubscription

type WSSubscription struct {
	Depth        int    `json:"depth"`
	Interval     int    `json:"interval"`
	MaxRateCount int    `json:"maxratecount"`
	Name         string `json:"name"`
	Token        string `json:"token"`
}

type WSSubscriptionStatus

type WSSubscriptionStatus struct {
	ChannelID    int            `json:"channelID"`
	ErrorMessage string         `json:"errorMessage"`
	ChannelName  string         `json:"channelName"`
	Event        string         `json:"event"`
	RequestID    int            `json:"reqid"`
	Pair         string         `json:"pair"`
	Status       string         `json:"status"`
	Subscription WSSubscription `json:"subscription"`
}

type WSSystemStatus

type WSSystemStatus struct {
	ConnectionID uint64 `json:"connectionID"`
	Event        string `json:"event"`
	Status       string `json:"status"`
	Version      string `json:"version"`
}

type WSTickerBook

type WSTickerBook struct {
	Price          string `json:"price"`
	WholeLotVolume uint64 `json:"wholeLotVolume"`
	LotVolume      string `json:"lotVolume"`
}

func (*WSTickerBook) UnmarshalJSON

func (w *WSTickerBook) UnmarshalJSON(data []byte) error

type WSTickerDaily

type WSTickerDaily struct {
	Today       string `json:"today"`
	Last24Hours string `json:"last24Hours"`
}

func (*WSTickerDaily) UnmarshalJSON

func (w *WSTickerDaily) UnmarshalJSON(data []byte) error

type WSTickerDailyTrades

type WSTickerDailyTrades struct {
	Today       uint `json:"today"`
	Last24Hours uint `json:"last24Hours"`
}

func (*WSTickerDailyTrades) UnmarshalJSON

func (w *WSTickerDailyTrades) UnmarshalJSON(data []byte) error

type WSTickerInfo

type WSTickerInfo struct {
	Ticker          string
	Ask             WSTickerBook        `json:"a"`
	Bid             WSTickerBook        `json:"b"`
	LastTradeClosed WSTickerLastTrade   `json:"c"`
	Volume          WSTickerDaily       `json:"v"`
	VWAP            WSTickerDaily       `json:"p"`
	NumberOfTrades  WSTickerDailyTrades `json:"t"`
	Low             WSTickerDaily       `json:"l"`
	High            WSTickerDaily       `json:"h"`
	Open            WSTickerDaily       `json:"o"`
}

type WSTickerLastTrade

type WSTickerLastTrade struct {
	Price     string `json:"price"`
	LotVolume string `json:"lotVolume"`
}

func (*WSTickerLastTrade) UnmarshalJSON

func (w *WSTickerLastTrade) UnmarshalJSON(data []byte) error

type WSTickerResp

type WSTickerResp struct {
	ChannelID   int `json:"channelID"`
	TickerInfo  WSTickerInfo
	ChannelName string `json:"channelName"`
	Pair        string `json:"pair"`
}

func (*WSTickerResp) UnmarshalJSON

func (w *WSTickerResp) UnmarshalJSON(data []byte) error

type WSTrade

type WSTrade struct {
	Price     string
	Volume    string
	Time      string
	Direction string
	OrderType string
	Misc      string
}

func (*WSTrade) UnmarshalJSON

func (t *WSTrade) UnmarshalJSON(data []byte) error

type WSTradeResp

type WSTradeResp struct {
	ChannelID   int `json:"channelID"`
	Trades      []WSTrade
	ChannelName string `json:"channelName"`
	Pair        string `json:"pair"`
}

func (*WSTradeResp) UnmarshalJSON

func (t *WSTradeResp) UnmarshalJSON(data []byte) error

type WalletTransferResponse

type WalletTransferResponse struct {
	RefID string `json:"refid"`
}

type WebSocketClient

type WebSocketClient struct {
	Conn          *websocket.Conn
	Ctx           context.Context
	Cancel        context.CancelFunc
	Router        MessageRouter
	Authenticator Authenticator

	ErrorLogger *log.Logger

	Mutex sync.Mutex
	// contains filtered or unexported fields
}

type WebSocketManager

type WebSocketManager struct {
	WebSocketClient     *WebSocketClient
	AuthWebSocketClient *WebSocketClient

	WebSocketToken     string
	SubscriptionMgr    *SubscriptionManager
	OrderBookMgr       *OrderBookManager
	TradeLogger        *TradeLogger
	OpenOrdersMgr      *OpenOrderManager
	TradingRateLimiter *TradingRateLimiter
	LimitChaseMgr      *LimitChaseManager
	BalanceMgr         *BalanceManager

	ConnectWaitGroup *sync.WaitGroup
	ErrorLogger      *log.Logger
	Mutex            sync.RWMutex
	// contains filtered or unexported fields
}

WebSocket API

func (*WebSocketManager) AssetBalance

func (ws *WebSocketManager) AssetBalance(asset string) (decimal.Decimal, error)

AssetBalance retrieves total decimal balance for arg 'asset' when balance manager is active. Must be called after StartBalanceManager. Returns an error if either balance manager is not active or if 'asset' is not found.

Note: Many assets have different tickers in Kraken's system than those listed in their currency pairs, use GetTradablePairsInfo to verify correct asset ticker's to pass to 'asset'.

func (*WebSocketManager) AssetBalances

func (ws *WebSocketManager) AssetBalances() (map[string]decimal.Decimal, error)

AssetBalances retrieves a map for all total asset balances managed internally when balance manager is active. Must be called after StartBalanceManager. Returns an error if balance manager is not active.

func (*WebSocketManager) CancelLimitChase

func (ws *WebSocketManager) CancelLimitChase(userRef int32) error

CancelLimitChase cancels a LimitChase order with the same user reference ID passed to 'userRef' and removes it from the LimitChaseOrders map. The method ensures thread safety by using a mutex lock when accessing the map. It returns an error if a LimitChase order with the given 'userRef' doesn't exist.

func (*WebSocketManager) Disconnected

func (ws *WebSocketManager) Disconnected() bool

Disconnected returns true if any clients become disconnected after initial startup.

func (*WebSocketManager) GetBookState

func (ws *WebSocketManager) GetBookState(pair string, depth uint16) (BookState, error)

GetBookState returns a BookState struct which holds pointers to both Bids and Asks slices for current state of book for arg 'pair' and specified 'depth'.

Note: This method should only be called when current state of book is being managed by the WebSocketManager within the KrakenClient instance (when StartOrderBookManager() method was called before subscription). This method will throw an error if no subscriptions were made after StartOrderBookManager() was called.

CAUTION: As this method returns pointers to the Asks and Bids fields, any modification done directly to Asks or Bids will likely result in an error and cause the WebSocketManager to unsubscribe from this channel. If modification to these slices is desired, either make a copy from reference or use ListAsks() and ListBids() instead.

func (*WebSocketManager) ListAsks

func (ws *WebSocketManager) ListAsks(pair string, depth uint16) ([]InternalBookEntry, error)

ListAsks returns a copy of the Asks slice which holds the current state of the order book for arg 'pair' and specified 'depth'. May be less performant than GetBookState() for larger lists ('depth').

Note: This method should only be called when current state of book is being managed by the WebSocketManager within the KrakenClient instance (when StartOrderBookManager() method was called before subscription). This method will throw an error if no subscriptions were made after StartOrderBookManager() was called.

func (*WebSocketManager) ListBids

func (ws *WebSocketManager) ListBids(pair string, depth uint16) ([]InternalBookEntry, error)

ListBids returns a copy of the Bids slice which holds the current state of the order book for arg 'pair' and specified 'depth'. May be less performant than GetBookState() for larger lists ('depth').

Note: This method should only be called when current state of book is being managed by the WebSocketManager within the KrakenClient instance (when StartOrderBookManager() method was called before subscription). This method will throw an error if no subscriptions were made after StartOrderBookManager() was called.

func (*WebSocketManager) ListOpenOrdersForPair

func (ws *WebSocketManager) ListOpenOrdersForPair(pair string) ([]map[string]WSOpenOrder, error)

Returns a slice of all currently open orders for arg 'pair' sorted ascending by price.

func (*WebSocketManager) LogOpenOrders

func (ws *WebSocketManager) LogOpenOrders(filename string, overwrite ...bool) error

LogOpenorders creates or opens a file with arg 'filename' and writes the current state of the open orders to the file in json lines format. Accepts one optional boolean arg 'overwrite'. If false, clears old file if it exists and writes new data to file. If true, appends the current data to the old file if it already exists. Defaults to false if no 'overwrite' value is passed.

Example Usage:

Example 1: Defers LogOpenOrders on main() return or panic

kc.StartOpenOrderManager()
kc.SubscribeOpenOrders(openOrdersCallback)
defer func() {
	err := kc.LogOpenOrders("open_orders.jsonl", true)
	if err != nil {
		fmt.Println("Error logging orders:", err)
	}
}()
defer func() {
	if r := recover(); r != nil {
		panic(r) // re-throw panic after Order logging
	}
}()

Example 2: Create channel and call LogOpenOrders() on shutdown signal

kc.StartOpenOrderManager()
kc.SubscribeOpenOrders(openOrdersCallback)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
// Start a goroutine that will perform cleanup when the program is interrupted
go func() {
	<-sigs
	err := kc.LogOpenOrders("open_orders.jsonl", true)
	if err != nil {
		fmt.Println("Error logging orders:", err)
	}
	os.Exit(0)
}()

func (*WebSocketManager) MapOpenOrders

func (ws *WebSocketManager) MapOpenOrders() map[string]WSOpenOrder

Returns a map of the current state of open orders managed by StartOpenOrderManager().

func (*WebSocketManager) SetOrderStatusCallback

func (ws *WebSocketManager) SetOrderStatusCallback(orderStatusCallback func(orderStatus interface{}))

Sets OrderStatusCallback to the function passed to arg 'orderStatus'. This function determines the behavior of the program when orderStatus type messages are received. Recommended to use with a switch case for each of the order status types.

Order Status Types:

WSAddOrderResp

WSEditOrderResp

WSCancelOrderResp

WSCancelAllResp

WSCancelAllAfterResp

Example Usage:

var orderID string
orderStatusCallback := func(orderStatus interface{}) {
	log.Println(orderStatus)
	switch s := orderStatus.(type) {
	case ks.WSAddOrderResp:
		log.Println(s)
		if s.Status == "ok" {
			log.Println("order added! updating orderID")
			orderID = s.TxID
		}
	case ks.WSEditOrderResp:
		log.Println(s)
		if s.Status == "ok" {
			log.Println("order edited! updating orderID")
			orderID = s.TxID
		}
	case ks.WSCancelOrderResp:
		log.Println(s)
		if s.Status == "ok" {
			log.Println("order cancelled!")
		}
	}
}
kc.WebSocketManager.SetOrderStatusCallback(orderStatusCallback)
for {
	select {
		case <-ticker1.C:
			kc.WSAddOrder(ks.WSLimit("10000"), "buy", "0.1", pair)
			ticker1.Stop()
		case <-ticker2.C:
			kc.WSEditOrder(orderID, pair, ks.WSNewPrice("8000"))
			ticker2.Stop()
		case <-ticker3.C:
			kc.WSCancelOrder(orderID)
			ticker3.Stop()
	}
}

func (*WebSocketManager) StartOpenOrderManager

func (ws *WebSocketManager) StartOpenOrderManager() error

Starts the open orders manager. Call this method before SubscribeOpenOrders(). It will build initial state of all currently open orders and maintain it in memory as new open order update messages come in.

Example Usage:

// Print current state of open orders every 15 seconds
err := kc.StartOpenOrderManager()
if err != nil...
err := kc.SubscribeOpenOrders()
if err != nil...
ticker := time.NewTicker(time.Second * 15)
for range ticker.C {
	orders := kc.MapOpenOrders()
	log.Println(orders)
}

func (*WebSocketManager) StartOrderBookManager

func (ws *WebSocketManager) StartOrderBookManager() error

StartOrderBookManager changes the flag for ws.OrderBookMgr to signal new SubscribeBook() subscription calls to track the current state of book in memory. Does not apply to already existing subscriptions, unsubscribe and resubscribe as necessary.

func (*WebSocketManager) StartTradeLogger

func (ws *WebSocketManager) StartTradeLogger(filename string) error

StartTradeLogger() starts a trade logger which opens, or creates if not exists, a file with 'filename' and writes all incoming trades from an "ownTrades" WebSocket channel subscription in json lines format. Suggested to call this method before SubscribeOwnTrades(). If errors occur, will log the errors to ErrorLogger (defaults to stdout if none is set) also structures the error message and logs it to the TradeLogger file.

Note: Ignores "snapshot" trades

Example Usage:

err := kc.StartTradeLogger("todays_trades.jsonl")
ownTradesCallback := func(ownTradesData interface{}) {
	// Don't need to do anything extra here for trades to be logged
	log.Println("an executed trade was logged by the logger!")
}
kc.SubscribeOwnTrades(ownTradesCallback, krakenspot.WithoutSnapshot())
// deferred function to close "todays_trades.log" in event of panic or shutdown
defer func() {
	if r := recover(); r != nil {
		fmt.Println("Recovered from panic:", r)
	}
	err := kc.StopTradeLogger()
	if err != nil {
		log.Fatal(err)
	}
}()

func (*WebSocketManager) StartTradingRateLimiter

func (ws *WebSocketManager) StartTradingRateLimiter(maxCounterBufferPercent ...uint8) error

StartTradingRateLimiter starts self rate-limiting for "order" type WebSocket methods. The "order" type methods include WSAddOrder(), WSEditOrder(), WSCancelOrder(), and WSCancelOrders(). Must have an active subscription to "openOrders" channel with SubscribeOpenOrders() before sending any orders for self rate-limiting logic to work correctly.

Note: It's recommended to start open orders internal management with StartOpenOrderManager() before subscribing to "openOrders" channel. If open order manager is not started before subscribing, rate-limiter for edit orders will default to assuming a max incremement penalty and cancel orders will simply skip rate-limiting logic. Accepts one or none optional arg passed to 'maxCounterBufferPercent' which is a percent of the total max counter for your verification tier that will act as a buffer to attempt to avoid exceeding max counter rate when multiple order methods for the same pair are called consecutively and race to pass the rate-limit check.

Note: Activating self rate-limiting may add significant processing overhead and waits and only attempts to prevent hitting the max. It is likely better to implement rate-limiting yourself and/or design your strategy not to approach rate-limits.

Enum:

'maxCounterBufferPercent' - [0..99]

Example Usage:

Note: error assignment and handling omitted throughout

// Creates new client, connects, starts required features for rate-limiting
// with a 20% buffer, subscribes, and sends an order
kc := NewKrakenClient(apikey, apisecret, 2)
kc.ConnectPrivate()
kc.StartOpenOrderManager()
kc.StartTradingRateLimiter(20)
kc.SubscribeOpenOrders(openOrdersCallback)
// send orders as needed
kc.WSAddOrder(krakenspot.WSLimit("42100.20"), "buy", "1.0", "XBT/USD", krakenspot.WSPostOnly(), krakenspot.WSCloseLimit("44000"))
// etc...

func (*WebSocketManager) StopBalanceManager

func (ws *WebSocketManager) StopBalanceManager() error

StopBalanceManager stops balance manager feature by changing its flag to false and calling its context cancel function. Returns an error if balance manager is already stopped.

func (*WebSocketManager) StopOpenOrderManager

func (ws *WebSocketManager) StopOpenOrderManager() error

StopOpenOrderManager() stops the internal tracking of current open orders. Closes channel and clears the internal OpenOrders map.

func (*WebSocketManager) StopOrderBookManager

func (ws *WebSocketManager) StopOrderBookManager() error

StopOrderBookManager changes the flag for ws.OrderBookMgr to signal new SubscribeBook() subscription calls not to track the current state of book in memory. Does not apply to already existing subscriptions, unsubscribe and resubscribe as necessary.

func (*WebSocketManager) StopTradeLogger

func (ws *WebSocketManager) StopTradeLogger() error

Waits until go routine finishes writing trades to file then closes TradeLogger channel and Tradelogger file. Recommended to call this method explicitly and/or inside of a defer func to ensure file close is triggered. Logic within this method is behind an atomic.bool check, so calling this method multiple times should not cause any issues in your program.

Example Usage:

// Create the WebSocketManager and start the TradeLogger
err := kc.StartTradeLogger("trades.log")
// Defer a function to recover from a panic and call StopTradeLogger() for "trades.log" file closure
defer func() {
	if r := recover(); r != nil {
		fmt.Println("Recovered from panic:", r)
	}
	err := ws.StopTradeLogger()
	if err != nil {
		log.Fatal(err)
	}
}()
//...Your program logic here...//
// Listen for shutdown signals
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
// Wait for a shutdown signal
<-shutdown

func (*WebSocketManager) StopTradingRateLimiter

func (ws *WebSocketManager) StopTradingRateLimiter() error

StopTradingRateLimiter stops self rate-limiting for "order" type WebSocket methods.

func (*WebSocketManager) SubscribeBook

func (ws *WebSocketManager) SubscribeBook(pair string, depth uint16, callback GenericCallback, options ...ReqIDOption) error

SubscribeBook subscribes to Kraken's "book" WebSocket channel for arg 'pair' and specified 'depth'. Where 'depth' is number of levels shown for each bids and asks side. On subscribing, the first message received will be the full initial state of the order book. Call StartOrderBookManager() method before SubscribeBook to maintain current state of book in memory.

May pass either a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to read/handle channel data manually. Accepts none or many functional options args 'options'.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

When nil is passed, access state of the orderbook with the following methods:

func (ws *WebSocketManager) GetBookState(pair string, depth uint16) (BookState, error)

func (ws *WebSocketManager) ListAsks(pair string, depth uint16) ([]InternalBookEntry, error)

func (ws *WebSocketManager) ListBids(pair string, depth uint16) ([]InternalBookEntry, error)

Accepts up to one functional options arg 'options' for reqID.

Enum:

'depth' - 10, 25, 100, 500, 1000

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

Method 1: Package will maintain book state internally by passing nil 'callback'

// subscribe to book
depth := uint16(10)
pair := "XBT/USD"
err = kc.SubscribeBook(pair, depth, nil)
if err != nil {
	log.Println(err)
}
// Print list of asks to terminal every 15 seconds
ticker := time.NewTicker(time.Second * 15)
for range ticker.C {
	asks, err := kc.ListAsks(pair, depth)
	if err != nil {
		log.Println(err)
	} else {
		log.Println(asks)
	}
}

Method 2: End user builds and maintains current book state with their own custom 'callback' function and helper functions

type Book struct {
	Asks []Level
	Bids []Level
}
var book Book
func initialStateMsg(msg krakenspot.WSOrderBookSnapshot) bool {
	//...your implementation here
}
func initializeBook(msg krakenspot.WSOrderBookSnapshot, book *Book) {
	//...your implementation here
}
func updateBook(msg krakenspot.WSOrderBookUpdate, book *Book) {
	//...your implementation here
}
// call functions for building and updating book as messages are received
func bookCallback(bookData interface{}) {
	if resp, ok := bookData.(krakenspot.WSBookResp); ok {
		msg := resp.OrderBook
		if initialStateMsg(msg) { // implement
			initializeBook(msg, &book)
		} else {
			updateBook(msg, book)
		}
	}
}
// subscribe to book
depth := uint16(10)
pair := "XBT/USD"
err := kc.SubscribeBook(pair, depth, bookCallback)
if err != nil {
	log.Println(err)
}
// Prints book to terminal every 15 seconds
ticker := time.NewTicker(time.Second * 15)
for range ticker.C {
	log.Println(book)
}

func (*WebSocketManager) SubscribeOHLC

func (ws *WebSocketManager) SubscribeOHLC(pair string, interval uint16, callback GenericCallback, options ...ReqIDOption) error

Subscribes to "ohlc" WebSocket channel for arg 'pair' and specified 'interval' in minutes. On subscribing, sends last valid closed candle (had at least one trade), irrespective of time. May pass a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to handle channels manually. Accepts up to one functional options arg 'options' for reqID.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Enum:

'interval' - 1, 5, 15, 30, 60, 240, 1440, 10080, 21600

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

ohlcCallback := func(ohlcData interface{}) {
	if msg, ok := ohlcData.(ks.WSOHLCResp); ok {
		log.Println(msg.OHLC)
	}
}
err = kc.SubscribeOHLC("XBT/USD", 5, ohlcCallback)
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) SubscribeOpenOrders

func (ws *WebSocketManager) SubscribeOpenOrders(callback GenericCallback, options ...SubscribeOpenOrdersOption) error

Subscribes to "openOrders" authenticated WebSocket channel. May pass either a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to read/handle channel data manually. Accepts none or many functional options arg passed to 'options'.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Functional Options:

// Whether to send rate-limit counter in updates  Defaults to false if not called.
func WithRateCounter() SubscribeOpenOrdersOption
// Attach optional request ID 'reqID' to request
func SubscribeOpenOrdersReqID(reqID string) SubscribeOpenOrdersOption

Example Usage:

openOrdersCallback := func(openOrdersData interface{}) {
	if msg, ok := openOrdersData.(ks.WSOpenOrdersResp); ok {
		log.Println(msg)
	}
}
err = kc.SubscribeOpenOrders(openOrdersCallback)
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) SubscribeOwnTrades

func (ws *WebSocketManager) SubscribeOwnTrades(callback GenericCallback, options ...SubscribeOwnTradesOption) error

Subscribes to "ownTrades" authenticated WebSocket channel. May pass either a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to read/handle channel data manually. Accepts none or many functional options args 'options'.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Functional Options:

// Whether to consolidate order fills by root taker trade(s). If false, all order fills will show separately. Defaults to true if not called.
func WithoutConsolidatedTaker()
// Whether to send historical feed data snapshot upon subscription. Defaults to true if not called.
func WithoutSnapshot()
// Attach optional request ID 'reqID' to request
func SubscribeOwnTradesReqID(reqID string) SubscribeOwnTradesOption

Example Usage:

ownTradesCallback := func(ownTradesData interface{}) {
	if msg, ok := ownTradesData.(ks.WSOwnTradesResp); ok {
		log.Println(msg)
	}
}
err = kc.SubscribeOwnTrades(ownTradesCallback, krakenspot.WithoutSnapshot())
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) SubscribeSpread

func (ws *WebSocketManager) SubscribeSpread(pair string, callback GenericCallback, options ...ReqIDOption) error

Subscribes to "spread" WebSocket channel for arg 'pair'. May pass either a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to read/handle channel data manually. Accepts up to one functional options arg 'options' for reqID.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

spreadCallback := func(spreadData interface{}) {
	if msg, ok := spreadData.(ks.WSSpreadResp); ok {
		log.Println(msg)
	}
}
err = kc.SubscribeSpread("XBT/USD", spreadCallback)
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) SubscribeTicker

func (ws *WebSocketManager) SubscribeTicker(pair string, callback GenericCallback, options ...ReqIDOption) error

Subscribes to "ticker" WebSocket channel for arg 'pair'. May pass a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to handle channels manually. Accepts up to one functional options arg 'options' for reqID.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

tickerCallback := func(tickerData interface{}) {
	if msg, ok := tickerData.(ks.WSTickerResp); ok {
		log.Println(msg.TickerInfo.Bid)
	}
}
err := kc.SubscribeTicker("XBT/USD", tickerCallback)
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) SubscribeTrade

func (ws *WebSocketManager) SubscribeTrade(pair string, callback GenericCallback, options ...ReqIDOption) error

Subscribes to "trade" WebSocket channel for arg 'pair'. May pass a valid function to arg 'callback' to dictate what to do with incoming data to the channel or pass a nil callback if you choose to handle channels manually. Accepts up to one functional options arg 'options' for reqID.

CAUTION: Passing both a non-nil callback function and reading the channels manually in your code will result in conflicts reading incoming data. Choose one solution or the other.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

tradeCallback := func(tradeData interface{}) {
	if msg, ok := tradeData.(ks.WSTradeResp); ok {
		log.Println(msg.Trades)
	}
}
err = kc.SubscribeTrade("XBT/USD", tradeCallback)
if err != nil {
	log.Println(err)
}

func (*WebSocketManager) UnsubscribeAll

func (ws *WebSocketManager) UnsubscribeAll(reqID ...string) error

Iterates through all open public and private subscriptions and sends an unsubscribe message to Kraken's WebSocket server for each. Accepts 0 or 1 optional arg 'reqID' request ID to send with all Unsubscribe<channel> methods

Example Usage:

err := kc.UnsubscribeAll()

func (*WebSocketManager) UnsubscribeBook

func (ws *WebSocketManager) UnsubscribeBook(pair string, depth uint16, options ...ReqIDOption) error

Unsubscribes from "book" WebSocket channel for arg 'pair' and specified 'depth' as number of book entries for each bids and asks. Accepts up to one functional options arg 'options' for reqID.

Enum:

'depth' - 10, 25, 100, 500, 1000

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

err := kc.UnsubscribeBook("XBT/USD", 10)
if err != nil...

func (*WebSocketManager) UnsubscribeOHLC

func (ws *WebSocketManager) UnsubscribeOHLC(pair string, interval uint16, options ...ReqIDOption) error

Unsubscribes from "ohlc" WebSocket channel for arg 'pair' and specified 'interval' in minutes. Accepts up to one functional options arg 'options' for reqID.

Enum:

'interval' - 1, 5, 15, 30, 60, 240, 1440, 10080, 21600

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

err := kc.UnsubscribeOHLC("XBT/USD", 1)
if err != nil...

func (*WebSocketManager) UnsubscribeOpenOrders

func (ws *WebSocketManager) UnsubscribeOpenOrders(options ...UnsubscribeOpenOrdersOption) error

Unsubscribes from "openOrders" authenticated WebSocket channel. Accepts up to one functional options arg 'options' for reqID.

Example Usage:

err := kc.UnsubscribeOpenOrders()
if err != nil...

func (*WebSocketManager) UnsubscribeOwnTrades

func (ws *WebSocketManager) UnsubscribeOwnTrades(options ...UnsubscribeOwnTradesOption) error

Unsubscribes from "ownTrades" WebSocket channel. Accepts up to one functional options arg 'options' for reqID.

Functional Options:

// Attach optional request ID 'reqID' to request
func UnsubscribeOwnTradesReqID(reqID string) UnsubscribeOwnTradesOption

Example Usage:

err := kc.UnsubscribeOwnTrades()
if err != nil...

func (*WebSocketManager) UnsubscribeSpread

func (ws *WebSocketManager) UnsubscribeSpread(pair string, options ...ReqIDOption) error

Unsubscribes from "spread" WebSocket channel for arg 'pair'. Accepts up to one functional options arg 'options' for reqID.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

err := kc.UnsubscribeSpread("XBT/USD")
if err != nil...

func (*WebSocketManager) UnsubscribeTicker

func (ws *WebSocketManager) UnsubscribeTicker(pair string, options ...ReqIDOption) error

Unsubscribes from "ticker" WebSocket channel for arg 'pair'. Accepts up to one functional options arg 'options' for reqID.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

err := kc.UnsubscribeTicker("XBT/USD")
if err != nil...

func (*WebSocketManager) UnsubscribeTrade

func (ws *WebSocketManager) UnsubscribeTrade(pair string, options ...ReqIDOption) error

Unsubscribes from "trade" WebSocket channel for arg 'pair' Accepts up to one functional options arg 'options' for reqID.

Functional Options:

func ReqID(reqID string) ReqIDOption

Example Usage:

err := kc.UnsubscribeTrade("XBT/USD")
if err != nil...

func (*WebSocketManager) WSAddOrder

func (ws *WebSocketManager) WSAddOrder(orderType WSOrderType, direction, volume, pair string, options ...WSAddOrderOption) error

Sends an 'orderType' order request on the side 'direction' (buy or sell) of amount/qty/size 'volume' for the specified 'pair' passed to args to Kraken's WebSocket server. See functions passable to 'orderType' below which may have required 'price' args included. Accepts none or many functional options passed to arg 'options' which can modify order behavior. Functional options listed below may conflict with eachother or have certain argument requirements. Only brief docstrings are included here, check each function's individual documentation for further related notes and nuance.

WSOrderType functions:

// Instantly market orders in at best current prices
func WSMarket() WSOrderType
// Order type of "limit" where arg 'price' is the level at which the limit order will be placed ...
func WSLimit(price string) WSOrderType
// Order type of "stop-loss" order type where arg 'price' is the stop loss trigger price ...
func WSStopLoss(price string) WSOrderType
// Order type of "take-profit" where arg 'price' is the take profit trigger price ...
func WSTakeProfit(price string) WSOrderType
// Order type of "stop-loss-limit" where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed ...
func WSStopLossLimit(price, price2 string) WSOrderType
// Order type of "take-profit-limit" where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed ...
func WSTakeProfitLimit(price, price2 string) WSOrderType
// Order type of "trailing-stop" where arg 'price' is the relative stop trigger price ...
func WSTrailingStop(price string) WSOrderType
// Order type of "trailing-stop-limit" where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed ...
func WSTrailingStopLimit(price, price2 string) WSOrderType
// Order type of "settle-position". Settles any open margin position of same 'direction' and 'pair' by amount 'volume' ...
func WSSettlePosition(leverage string) WSOrderType

Enums:

'direction': "buy", "sell"

'volume': ["0"...] Call Kraken API with *KrakenClient.GetTradeablePairsInfo(pair) field 'OrderMin' for specific pairs minimum order size

'pair': Call Kraken API with *KrakenClient.ListWebsocketNames() method for available tradeable pairs WebSocket names

Functional Options:

// User reference id 'userref' is an optional user-specified integer id that can be associated with any number of orders ...
func WSUserRef(userRef string) WSAddOrderOption
// Amount of leverage desired. Defaults to no leverage if function is not called. API accepts string of any number; in practice, must be some integer >= 2 ...
func WSLeverage(leverage string) WSAddOrderOption
// If true, order will only reduce a currently open position, not increase it or open a new position. Defaults to false if not passed ...
func WSReduceOnly() WSAddOrderOption
// Add all desired order 'flags' as a single comma-delimited list. Use either this function or call (one or many) the individual flag functions below ...
func WSOrderFlags(flags string) WSAddOrderOption
// Post-only order (available when ordertype = limit)
func WSPostOnly() WSAddOrderOption
// Prefer fee in base currency (default if selling) ...
func WSFCIB() WSAddOrderOption
// Prefer fee in quote currency (default if buying) ...
func WSFCIQ() WSAddOrderOption
// Disables market price protection for market orders
func WSNOMPP() WSAddOrderOption

~// Order volume expressed in quote currency. This is supported only for market orders ...~ ~func WSVIQC() WSAddOrderOption~

// Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "IOC" (Immediate Or Cancel) ...
func WSImmediateOrCancel() WSAddOrderOption
// Time-in-force of the order to specify how long it should remain in the order book before being cancelled. Overrides default value with "GTD" (Good Til Date) ...
func WSGoodTilDate(expireTime string) WSAddOrderOption
// Conditional close of "limit" order type where arg 'price' is the level at which the limit order will be placed ...
func WSCloseLimit(price string) WSAddOrderOption
// Conditional close of "stop-loss" order type where arg 'price' is the stop loss trigger price ...
func WSCloseStopLoss(price string) WSAddOrderOption
// Conditional close of "take-profit" order type where arg 'price' is the take profit trigger price ...
func WSCloseTakeProfit(price string) WSAddOrderOption
// Conditional close of "stop-loss-limit" order type where arg 'price' is the stop loss trigger price and arg 'price2' is the limit order that will be placed ...
func WSCloseStopLossLimit(price, price2 string) WSAddOrderOption
// Conditional close of "take-profit-limit" order type where arg 'price' is the take profit trigger price and arg 'price2' is the limit order that will be placed ...
func WSCloseTakeProfitLimit(price, price2 string) WSAddOrderOption
// Conditional close of "trailing-stop" order type where arg 'price' is the relative stop trigger price ...
func WSCloseTrailingStop(price string) WSAddOrderOption
// Conditional close of "trailing-stop-limit" order type where arg 'price' is the relative stop trigger price and arg 'price2' is the limit order that will be placed ...
func WSCloseTrailingStopLimit(price, price2 string) WSAddOrderOption
// Pass RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which the matching engine should reject the new order request to arg 'deadline' ...
func WSAddWithDeadline(deadline string) WSAddOrderOption
// Validates inputs only. Does not submit order. Defaults to "false" if not called.
func WSValidateAddOrder() WSAddOrderOption
// Attach optional request ID 'reqID' to request
func WSAddOrderReqID(reqID string) WSAddOrderOption

Example Usage:

// Sends a post only buy limit order request at price level 42100.20 on Bitcoin for 1.0 BTC. On filling, will open an opposite side sell order at price 44000
err := kc.WSAddOrder(krakenspot.WSLimit("42100.20"), "buy", "1.0", "XBT/USD", krakenspot.WSPostOnly(), krakenspot.WSCloseLimit("44000"))

func (*WebSocketManager) WSCancelAllOrders

func (ws *WebSocketManager) WSCancelAllOrders() error

Sends a request to Kraken's authenticated WebSocket server to cancel all open orders including partially filled orders.

Example Usage:

err := kc.WSCancelAllOrders()

func (*WebSocketManager) WSCancelAllOrdersAfter

func (ws *WebSocketManager) WSCancelAllOrdersAfter(timeout string) error

Sends a cancelAllOrdersAfter request to Kraken's authenticated WebSocket server that activates a countdown timer of 'timeout' number of seconds/

Note: From the Kraken Docs cancelAllOrdersAfter provides a "Dead Man's Switch" mechanism to protect the client from network malfunction, extreme latency or unexpected matching engine downtime. The client can send a request with a timeout (in seconds), that will start a countdown timer which will cancel *all* client orders when the timer expires. The client has to keep sending new requests to push back the trigger time, or deactivate the mechanism by specifying a timeout of 0. If the timer expires, all orders are cancelled and then the timer remains disabled until the client provides a new (non-zero) timeout.

The recommended use is to make a call every 15 to 30 seconds, providing a timeout of 60 seconds. This allows the client to keep the orders in place in case of a brief disconnection or transient delay, while keeping them safe in case of a network breakdown. It is also recommended to disable the timer ahead of regularly scheduled trading engine maintenance (if the timer is enabled, all orders will be cancelled when the trading engine comes back from downtime - planned or otherwise).

Example Usage:

kc.WSCancelAllOrdersAfter("60")

func (*WebSocketManager) WSCancelOrder

func (ws *WebSocketManager) WSCancelOrder(orderID string) error

Sends a cancel order request to Kraken's authenticated WebSocket server to cancel order with specified arg 'orderID'.

Example Usage:

err := kc.WSCancelOrder("O26VH7-COEPR-YFYXLK")

func (*WebSocketManager) WSCancelOrders

func (ws *WebSocketManager) WSCancelOrders(orderIDs []string) error

Sends a cancel order request to Kraken's authenticated WebSocket server to cancel multiple orders with specified orderIDs passed to slice 'orderIDs'.

Example Usage:

err := kc.WSCancelOrder([]string{"O26VH7-COEPR-YFYXLK", "OGTT3Y-C6I3P-X2I6HX"})

func (*WebSocketManager) WSEditOrder

func (ws *WebSocketManager) WSEditOrder(orderID, pair string, options ...WSEditOrderOption) error

WSEditOrder Sends an edit order request for the order with 'orderID' and 'pair'. Must have at least one of WSNewVolume() WSNewPrice() WSNewPrice2() functional options args passed to 'options', but may also have many.

Note: OrderID, Userref, and post-only flag will all be reset with the new order. Pass WSNewUserRef(userRef) with the old 'userRef' and WSNewPostOnly() to 'options' to retain these values.

Enum:

'pair': Call Kraken API with *KrakenClient.ListWebsocketNames() method for available tradeable pairs WebSocket names

Functional Options:

// Field "userref" is an optional user-specified integer id associated with edit request ...
func WSNewUserRef(userRef string) WSEditOrderOption
// Updates order quantity in terms of the base asset.
func WSNewVolume(volume string) WSEditOrderOption
// Updates limit price for "limit" orders. Updates trigger price for "stop-loss", "stop-loss-limit", "take-profit", "take-profit-limit", "trailing-stop" and "trailing-stop-limit" orders ...
func WSNewPrice(price string) WSEditOrderOption
// Updates limit price for "stop-loss-limit", "take-profit-limit" and "trailing-stop-limit" orders ...
func WSNewPrice2(price2 string) WSEditOrderOption
// Post-only order (available when ordertype = limit). All the flags from the parent order are retained except post-only. Post-only needs to be explicitly mentioned on every edit request.
func WSNewPostOnly() WSEditOrderOption
// Validate inputs only. Do not submit order. Defaults to false if not called.
func WSValidateEditOrder() WSEditOrderOption
// Attach optional request ID 'reqID' to request
func WSEditOrderReqID(reqID string) WSEditOrderOption

Example Usage:

kc.WSEditOrder("O26VH7-COEPR-YFYXLK", "XBT/USD", ks.WSNewPrice("21000"), krakenspot.WSNewPostOnly(), krakenspot.WSValidateEditOrder())

func (*WebSocketManager) WSLimitChase

func (ws *WebSocketManager) WSLimitChase(direction, volume, pair string, userRef int32, fillCallback func(*LimitChaseFill), closeCallback func()) error

WSLimitChase gets top of book prices and places a post-only limit order on the exchange, and then it manages the order by editing or cancel and replacing as necessary (if the order is partially filled) when the top of book level changes.

This method first retrieves top of book price for the given arg passed to 'pair' and places an order in the given 'direction' ("buy" or "sell") for the specified quantity/size passed to 'volume'. This method requires a unique user reference ID passed to 'userRef' that is not used for any other open orders whether made by this package or otherwise. This method requires internal management of orderbooks (use StartOrderBookManager()) a pre-existing active WebSocket subscription to the private "openOrders" channel, and a subscription to a public "book" channel for the given 'pair'.

Depth for the "book" channel can be any valid depth, but it is recommended to have only one depth subscribed per 'pair'. Larger depths will incur more unnecessary processing.

The 'fillCallBack' arg is a custom function where the end user can dictate what to do when a fill (partial or full) happens. This arg can be nil. The 'closeCallback' is the same, but gets called whenever the limit chase order ends whether it be closed due to order fully filled, errors encountered, or otherwise.

Enums:

'direction' - "buy", "sell"

'volume' - positive number value expressed as a string in quote currency. Must be above minimum size for 'pair' and have correct decimals. Use GetTradeablePairsInfo(pair) for 'pair' specific details

'pair' - valid tradeable pair and format for websocket. Use ListWebsocketNames() to get a slice of possible tradeable pairs

'userRef' - unique identifier not used for any other order. Will not return immediately if 'userRef' is not unique, will place initial order and then cancel both the limit-chase order and all other orders with the same 'userRef' and return with error.

Example Usage:

Error handling omitted throughout

// Typical client initialization and subscribe required channels
direction := "buy"
oppDirection := "sell"
krakenPair := "XBT/USD"
liquidExchangePair := "BTCUSDT"
depth := uint16(10)
volume := "0.0001"
userRef := 10010032
kc, err := krakenspot.NewKrakenClient(apiKey, apiSecret, 2)
err = kc.StartOrderBookManager()
subscriptionsDone := make(chan bool)
systemStatusCallback := func(status string) {
	if status == "online" {
		err = kc.SubscribeBook(krakenPair, depth, nil)
		err = kc.SubscribeOpenOrders(nil)
		close(subscriptionsDone)
	} else { // system not online
		close(subscriptionsDone)
		return
	}
}
err = kc.Connect(systemStatusCallback)
<-subscriptionsDone
limitChaseClosed := make(chan bool)
fillCallback := func(lcFill *krakenspot.LimitChaseFill) {
	bc.MarketOrderOnLiquidExchange(oppDirection, lcFill.FilledVol.String(), liquidExchangePair)
}
closeCallback := func() {
	log.Println("limit-chase order closed")
	close(limitChaseClosed)
}
kc.WSLimitChase(direction, volume, krakenPair, userRef, fillCallback, closeCallback)
<-limitChaseClosed
return

func (*WebSocketManager) WaitForConnect

func (ws *WebSocketManager) WaitForConnect(timeoutMilliseconds ...uint16) error

WaitForConnect blocks until the WebSocketManager has established all connections as confirmed by a "systemStatus" message (regardless of status) received from the WebSocket server, or until a timeout of 5 seconds has passed. It returns an error if the timeout is reached before all connections are established. If performing specific operations depending on system status message received is desired, write a systemStatusCallback func passed to the Connect() method instead. Intended to use to wait until connections are confirmed before subscribing to Kraken's WebSocket channels. Accepts none or one optional arg passed to 'timeoutMilliseconds' which is the number of milliseconds until this method times out and returns an error. Defaults to 5000 (5 seconds) if no args passed.

Example Usage:

kc, err := NewKrakenClient(apiKey, secretKey, 2)
err = kc.Connect(nil)
err = kc.WaitForConnect()
err = kc.SubscribeBook("XBT/USD", 10, nil)
err = kc.SubscribeOwnTrades(nil)
err = kc.WaitForSubscriptions()
//...start your program logic here...//

func (*WebSocketManager) WaitForDisconnect

func (ws *WebSocketManager) WaitForDisconnect()

WaitForDisconnect blocks and waits for disconnect signal to be broadcasted after any client is disconnected. Intended use at the start of a goroutine to block before reconnection/restart logic.

func (*WebSocketManager) WaitForReconnect

func (ws *WebSocketManager) WaitForReconnect()

WaitForReconnect blocks and waits for reconnected condition broadcasted after all clients are reconnected. Includes another call to Disconnected to prevent blocking in case reconnect happened during your shutdown/pause logic

func (*WebSocketManager) WaitForSubscriptions

func (ws *WebSocketManager) WaitForSubscriptions(timeoutMilliseconds ...uint16) error

WaitForSubscriptions blocks until all subscriptions (both private and public) by the WebSocketManager have received a "subscribed" event type message from Kraken WebSocket server or until a timeout of 5 seconds has passed. It returns an error if the timeout is reached before all subscriptions are received. Accepts none or one optional arg passed to 'timeoutMilliseconds' which is the number of milliseconds until this method times out and returns an error. Defaults to 5000 (5 seconds) if no args passed.

Note: SubscribeBook() calls perform an additional wait group increment if state of book is being managed internally. The wait group is decremented after initial state of book is built in memory. This prevents race errors if the program following logic requires state of book.

Example Usage:

kc, err := NewKrakenClient(apiKey, secretKey, 2)
err = kc.StartOrderBookManager()
err = kc.Connect(nil)
err = kc.WaitForConnect()
err = kc.SubscribeBook("XBT/USD", 10, nil)
err = kc.SubscribeOwnTrades(nil)
err = kc.WaitForSubscriptions()
//...start your program logic here...//
bookState, err = GetBookState("XBT/USD", 10) // safe to call "immediately"

type WebSocketsToken

type WebSocketsToken struct {
	Token   string `json:"token"`
	Expires uint16 `json:"expires"`
}

type WithdrawFundsOption

type WithdrawFundsOption func(payload url.Values)

For *KrakenClient method WithdrawFunds()

func WFWithAddress

func WFWithAddress(address string) WithdrawFundsOption

Optional, crypto address that can be used to confirm address matches key (will return Invalid withdrawal address error if different)

func WFWithMaxFee

func WFWithMaxFee(maxFee string) WithdrawFundsOption

Optional, if the processed withdrawal fee is higher than max_fee, withdrawal will fail with EFunding:Max fee exceeded

type WithdrawFundsResponse

type WithdrawFundsResponse struct {
	RefID string `json:"refid"`
}

type WithdrawalAddress

type WithdrawalAddress struct {
	Address  string `json:"address"`
	Asset    string `json:"asset"`
	Method   string `json:"method"`
	Key      string `json:"key"`
	Memo     string `json:"memo"`
	Verified bool   `json:"verified"`
}

type WithdrawalInfo

type WithdrawalInfo struct {
	Method string `json:"method"`
	Limit  string `json:"limit"`
	Amount string `json:"amount"`
	Fee    string `json:"fee"`
}

type WithdrawalMethod

type WithdrawalMethod struct {
	Asset   string `json:"asset"`
	Method  string `json:"method"`
	Network string `json:"network"`
	Minimum string `json:"minimum"`
}

type WithdrawalStatus

type WithdrawalStatus struct {
	Method         string      `json:"method"`
	Network        string      `json:"network"`
	AssetClass     string      `json:"aclass"`
	Asset          string      `json:"asset"`
	RefID          string      `json:"refid"`
	TxID           string      `json:"txid"`
	Info           string      `json:"info"`
	Amount         string      `json:"amount"`
	Fee            interface{} `json:"fee"`
	TimeRequested  int32       `json:"time"`
	Status         string      `json:"status"`
	StatusProperty string      `json:"status-prop"`
	Key            string      `json:"key"`
}

type WithdrawalStatusPaginated

type WithdrawalStatusPaginated struct {
	Withdrawals []WithdrawalStatus `json:"withdrawals"`
	NextCursor  string             `json:"next_cursor"`
}

type YieldSource

type YieldSource struct {
	Type string `json:"type"`
}

Jump to

Keyboard shortcuts

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