kraken

package module
v0.20260622.2 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 13 Imported by: 0

README

go-kraken

Go Reference

A Go SDK for the Kraken spot exchange, covering the full Spot REST API.

API Aligned to
Spot REST&Websocket 2026-06-22

Response structs are reconciled against the live API (not just the docs): every endpoint is tested by diffing the real JSON keys against the struct, so they stay in sync with the date above.

Install

go get github.com/UnipayFI/go-kraken@latest

Highlights

  • One signing/transport core shared by every endpoint (client + request + common).
  • Fluent per-endpoint API: NewXxxService(...).SetFoo(...).Do(ctx).
  • Amounts as decimal.Decimal, timestamps as time.Time — Kraken's string-encoded numbers, UNIX-seconds (and the occasional RFC3339 / nanosecond) times, and false/""/"0" "not set" sentinels are decoded for you.
  • Kraken's positional-array payloads (OHLC, order book, trades, spreads, ticker fields, fee tiers) are decoded into named struct fields.
  • Every endpoint is tested against the live API; trading is exercised with tiny, reversible, large-cap orders.

Quick start

package main

import (
	"context"
	"fmt"

	kraken "github.com/UnipayFI/go-kraken"
	"github.com/UnipayFI/go-kraken/client"
	"github.com/shopspring/decimal"
)

func main() {
	ctx := context.Background()

	c := kraken.NewClient(
		client.WithAuth("apiKey", "apiSecret"),
		// client.WithProxy("socks5://127.0.0.1:7890"),
	)

	// Public market data (no auth).
	srv, _ := c.NewGetServerTimeService().Do(ctx)
	fmt.Println("server time:", srv.UnixTime)

	ticker, _ := c.NewGetTickerService().SetPair("XBTUSD").Do(ctx)
	fmt.Println("BTC last:", ticker["XXBTZUSD"].Last.Price)

	// Private account data.
	balances, _ := c.NewGetAccountBalanceService().Do(ctx)
	fmt.Println("USDT:", balances["USDT"])

	// Place a post-only limit order.
	ref, err := c.NewAddOrderService("XBTUSDT", kraken.OrderSideBuy, kraken.OrderTypeLimit,
		decimal.RequireFromString("0.0001")).
		SetPrice(decimal.RequireFromString("30000")).
		SetOrderFlags(kraken.OrderFlagPost).
		Do(ctx)
	if err != nil {
		panic(err)
	}
	fmt.Println("txid:", ref.TxID)
}

Authentication

Pass credentials from the Kraken API-management page:

c := kraken.NewClient(client.WithAuth(apiKey, apiSecret))

apiSecret is the base64-encoded Private Key shown when the key was created. Private requests are signed with

API-Sign = base64( HMAC-SHA512( base64decode(secret), uriPath + SHA256(nonce + postData) ) )

placed in the API-Sign header alongside API-Key. Each request carries an always-increasing nonce in its url-encoded body; the SDK generates a strictly-monotonic nonce for you (nanosecond-based, so it survives restarts). For an external signer pass client.WithSignFn(fn); to share or override the nonce sequence pass client.WithNonce(fn).

Other options: WithProxy (http/https/socks5), WithBaseURL, WithNetwork, WithLogger, WithHTTPClient.

WebSocket

The v2 streams (wss://ws.kraken.com/v2 public, wss://ws-auth.kraken.com/v2 private) are exposed with the same NewXxxService(...).Do(ctx, cb) shape. Private channels and order entry need credentials; the short-lived auth token is fetched from the REST API and cached for you.

ws := kraken.NewWebSocketClient(
    client.WithWebSocketAuth(apiKey, apiSecret), // private channels + order entry only
    // client.WithWebSocketProxy("socks5://127.0.0.1:7890"),
)

// Public ticker.
done, _, _ := ws.NewSubscribeTickerService("BTC/USD").
    Do(ctx, func(p *kraken.WsPush[[]kraken.WsTicker], err error) {
        if err != nil {
            return
        }
        fmt.Println(p.Type, p.Data[0].Last) // "snapshot"/"update", last price
    })
close(done) // unsubscribe + close

// Private balances (token fetched + cached automatically).
ws.NewSubscribeBalancesService().Do(ctx, func(p *kraken.WsPush[[]kraken.WsBalance], err error) {
    // p.Data[0].Asset, p.Data[0].Balance, ...
})

Each Do returns (done chan<- struct{}, stop <-chan struct{}, err error): close done to unsubscribe and close; stop closes when the reader exits. A {"method":"ping"} keepalive is sent automatically.

Orders can also be placed over a persistent, authenticated connection — a low-latency alternative to the REST trade endpoints:

tc, _ := ws.DialTrade(ctx)
defer tc.Close()
ack, _ := tc.AddOrder(ctx, kraken.WsAddOrder{
    Symbol: "BTC/USDT", Side: kraken.OrderSideBuy, OrderType: kraken.OrderTypeLimit,
    OrderQty: decimal.RequireFromString("0.0001"), LimitPrice: decimal.RequireFromString("30000"),
    PostOnly: true,
})
fmt.Println(ack.Result.OrderID)
// tc.AmendOrder / tc.EditOrder / tc.CancelOrder / tc.BatchAdd / tc.CancelAll / ...

Public channels: ticker, book, ohlc, trade, instrument. Private channels: executions, balances, level3 (per-order book; entitlement-gated).

Packages

Spot REST (root package kraken)

Area File Endpoints
Market data market.go Time, SystemStatus, Assets, AssetPairs, Ticker, OHLC, Depth (order book), Trades, Spread, GroupedBook, Level3 (authenticated)
Account data account.go Balance, BalanceEx, TradeBalance, Open/Closed/Query Orders, OrderAmends, Trades History, Query Trades, Open Positions, Ledgers, Query Ledgers, Trade Volume, export reports (Add/Status/Retrieve/Remove), CreditLines, GetApiKeyInfo
Trading trade.go AddOrder, AddOrderBatch, AmendOrder, EditOrder, CancelOrder, CancelAll, CancelAllOrdersAfter, CancelOrderBatch
Funding funding.go Deposit Methods/Addresses/Status, Withdraw Methods/Addresses/Info, Withdraw, Withdraw Status/Cancel, WalletTransfer
Subaccounts subaccount.go CreateSubaccount, AccountTransfer (institutional)
Earn earn.go Allocate, Deallocate, Allocate/Deallocate Status, Strategies, Allocations
Transparency transparency.go PreTrade, PostTrade (MiFID pre/post-trade data)
WebSocket auth websocket.go GetWebSocketsToken (REST)
Shared types types.go order enums, NanoTime, MethodLimit

WebSocket v2 (ws*.go)

Area File Channels / methods
Entry ws.go NewWebSocketClient, WsPush, SubscribeRaw
Public channels ws_public.go ticker, book, ohlc, trade, instrument
Private channels ws_private.go executions, balances, level3
Order entry ws_trade.go add/amend/edit/cancel order, cancel-all, cancel-all-after, batch add/cancel

Core

Package Scope
kraken.go entry point: NewClient (REST) + NewWebSocketClient (in ws.go)
client/ REST + WebSocket clients, options, nonce generator, HMAC-SHA512 signer config, WS token cache, APIError
request/ request builder (form-urlencoded), generic Do[T] envelope decode, signer, WS subscribe/order-entry framework
common/ constants, global time.Time (UNIX-seconds/RFC3339) + decimal.Decimal JSON codec
internal/apitest/ test-only field-coverage helpers
cmd/kraw/ dev tool: sign + dump any endpoint's raw response

Testing

Tests hit the live API and read credentials from the environment, skipping when unset:

export KRAKEN_API_KEY=...  KRAKEN_API_SECRET=...
export KRAKEN_PROXY=socks5://127.0.0.1:7890   # optional

go test ./ -run TestMarketData -v                 # one module at a time
go test ./ -run TestWsPublicChannels -v           # live WebSocket channels
KRAKEN_TEST_WRITE=1 go test ./ -run TestTradeLifecycle -v     # live REST order tests (tiny, reversible)
KRAKEN_TEST_WRITE=1 go test ./ -run TestWsTradeLifecycle -v   # live WebSocket order entry
  • Run per module (-run TestXxx). Kraken enforces a per-key rate counter, so firing the whole suite at once can trip EAPI:Rate limit exceeded; individual modules stay under the limit.
  • REST tests diff the real response JSON against the typed structs (AssertCovers), so a missing or renamed field fails the test. WebSocket tests subscribe live and verify each push decodes cleanly into the typed struct (a wrong field type surfaces as a decode error).
  • Capability-gated endpoints (subaccounts, some funding/earn operations, the level3 stream) are tolerated when the account lacks the capability — signing and the request path are still exercised.
  • State-changing trade/earn tests are gated behind KRAKEN_TEST_WRITE=1 and use minimal amounts on large-cap pairs (a post-only order far from market never fills; one tiny market round-trip is immediately unwound). The fund-moving Withdraw endpoint is implemented but never executed.

The cmd/kraw helper signs and dumps any endpoint's raw response:

go run ./cmd/kraw GET  /0/public/Ticker "pair=XBTUSD"
go run ./cmd/kraw POST /0/private/Balance
go run ./cmd/kraw POST /0/private/Ledgers "asset=USDT&type=deposit"

CHANGE_LOG

2026-06-25 (WebSocket v2)
  • Added the full Kraken Spot WebSocket v2 surface, in the same NewXxxService(...).Do(ctx, cb) style:
    • Public channels (5): ticker, book, ohlc, trade, instrument.
    • Private channels (3): executions, balances, level3 (entitlement-gated).
    • Order entry (8 methods): add_order, amend_order, edit_order, cancel_order, cancel_all, cancel_all_orders_after, batch_add, batch_cancel — over a persistent DialTrade connection.
  • Token-based auth: the WebSocket token is fetched from REST GetWebSocketsToken and cached (auto-refresh near expiry); proxy is shared with the stream dial. Automatic {"method":"ping"} keepalive.
  • All channels verified against the live stream (push received + clean typed decode); WebSocket order entry verified with tiny reversible orders and live executions events.
2026-06-25
  • Initial release. Full Kraken Spot REST API coverage (59 endpoints) across all categories: market data, account data, trading, funding, subaccounts, Earn, Transparency, and the WebSockets auth token.
    • Market data (11): Time, SystemStatus, Assets, AssetPairs, Ticker, OHLC, Depth, Trades, Spread, GroupedBook, Level3.
    • Account data (19): balances, orders, order amends, trades, positions, ledgers, trade volume, export reports, credit lines, API-key info.
    • Trading (8), Funding (10), Subaccounts (2), Earn (6), Transparency (2: PreTrade/PostTrade), WebSockets auth (1).
  • Signing core: HMAC-SHA512 over uriPath + SHA256(nonce + postData), strictly-monotonic nanosecond nonce, form-urlencoded bodies (with bracketed orders[i][...] arrays for batch endpoints).
  • Global JSON codec: decimal.Decimal for amounts, time.Time for UNIX-seconds/RFC3339 timestamps, NanoTime for nanosecond timestamps, MethodLimit for the false-or-amount union.
  • All public and private endpoints reconciled against the live API; trading verified with tiny reversible orders and one large-cap market round-trip, Earn with a reversible allocate/deallocate round-trip.

License

MIT

Documentation

Overview

Package kraken is a Go SDK for the Kraken spot exchange REST API.

Install: go get github.com/UnipayFI/go-kraken Import: import "github.com/UnipayFI/go-kraken"

The SDK covers Kraken's spot REST API at https://api.kraken.com/0 — public market data plus the private account, trading, funding, subaccount and Earn endpoints. One signing/transport core (client + request + common) is shared by every endpoint; the public/private split and the endpoint name are encoded in the request path.

Authentication uses Kraken's HMAC-SHA512 scheme: each private request carries an always-increasing nonce in its url-encoded body and an API-Sign header computed as base64(HMAC-SHA512(base64decode(secret), path + SHA256(nonce + postData))). See client.WithAuth.

Quick start:

c := kraken.NewClient(client.WithAuth(apiKey, apiSecret))

// Public market data (no auth).
srv, _ := c.NewGetServerTimeService().Do(ctx)
fmt.Println(srv.UnixTime)

// Private account data.
bal, _ := c.NewGetAccountBalanceService().Do(ctx)
fmt.Println(bal["XXBT"])

Index

Constants

View Source
const (
	OrderFlagPost  = "post"  // post-only (limit orders only)
	OrderFlagFCIB  = "fcib"  // prefer fee in base currency
	OrderFlagFCIQ  = "fciq"  // prefer fee in quote currency
	OrderFlagNOMPP = "nompp" // disable market price protection
	OrderFlagVIQC  = "viqc"  // order volume expressed in quote currency
)

Order flags (oflags) — combine as a comma-delimited string.

View Source
const (
	WsPushTypeSnapshot = request.WsPushTypeSnapshot // full snapshot frame
	WsPushTypeUpdate   = request.WsPushTypeUpdate   // incremental update frame
)
View Source
const MaxClOrdIDLen = 18

MaxClOrdIDLen is the maximum length of the free-text form of a client order id (cl_ord_id) accepted by Kraken's add_order endpoint.

Kraken accepts a cl_ord_id in one of three forms (verified empirically with add_order's validate mode):

  • free text up to MaxClOrdIDLen characters, restricted to lowercase letters and digits — uppercase or over-length text is rejected with "EGeneral:Invalid arguments:cl_ord_id";
  • a standard UUID (8-4-4-4-12 hexadecimal, any case);
  • a 32-character hexadecimal string (no hyphens).

Variables

View Source
var ErrBookChecksumMismatch = errors.New("kraken: book checksum mismatch")

ErrBookChecksumMismatch is returned by BookChecksummer.Verify when the locally computed CRC32 disagrees with the value the server attached to the frame, signalling the maintained book has drifted (the caller should resubscribe to fetch a fresh snapshot).

View Source
var ErrInvalidClOrdID = errors.New("kraken: cl_ord_id must be <=18 lowercase alphanumerics, a standard UUID, or 32 hex characters")

ErrInvalidClOrdID reports a cl_ord_id Kraken's add_order will reject. See MaxClOrdIDLen for the accepted forms.

Functions

func ValidateClOrdID added in v0.20260622.1

func ValidateClOrdID(s string) error

ValidateClOrdID reports whether s is a client order id Kraken's add_order will accept, returning ErrInvalidClOrdID otherwise. An empty string is valid (the field is optional). See MaxClOrdIDLen for the accepted forms.

Types

type APIKeyInfo

type APIKeyInfo struct {
	APIKey       string    `json:"api_key"`       // the public API key
	APIKeyName   string    `json:"api_key_name"`  // user-assigned key name
	IBAN         string    `json:"iban"`          // the account IBAN
	Permissions  []string  `json:"permissions"`   // granted permissions
	IPAllowlist  []string  `json:"ip_allowlist"`  // allowed source IPs (empty = any)
	Nonce        string    `json:"nonce"`         // last nonce seen for the key
	NonceWindow  string    `json:"nonce_window"`  // configured nonce window (seconds)
	CreatedTime  time.Time `json:"created_time"`  // when the key was created
	ModifiedTime time.Time `json:"modified_time"` // when the key was last modified
	LastUsed     time.Time `json:"last_used"`     // when the key was last used
	QueryFrom    time.Time `json:"query_from"`    // start of the key's allowed query window
	QueryTo      time.Time `json:"query_to"`      // end of the key's allowed query window
	ValidUntil   time.Time `json:"valid_until"`   // key expiry (zero = no expiry)
}

APIKeyInfo describes the signing API key.

type AccountTransferResult

type AccountTransferResult struct {
	TransferID string `json:"transfer_id"` // transfer id
	Status     string `json:"status"`      // pending or complete
}

AccountTransferResult is the AccountTransfer response.

type AccountTransferService

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

AccountTransferService transfers funds between the master account and a subaccount, or between subaccounts (institutional accounts only). The API key must belong to the master account.

func (*AccountTransferService) Do

func (*AccountTransferService) SetAssetClass

func (s *AccountTransferService) SetAssetClass(aclass string) *AccountTransferService

SetAssetClass sets the asset class of the asset being transferred.

type AddOrderBatchResult

type AddOrderBatchResult struct {
	Orders []BatchOrderResult `json:"orders"`
}

AddOrderBatchResult is the AddOrderBatch response, one entry per submitted order in request order.

type AddOrderBatchService

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

AddOrderBatchService places 2-15 orders for a single pair in one request.

func (*AddOrderBatchService) AddOrder

AddOrder appends an order to the batch.

func (*AddOrderBatchService) Do

func (*AddOrderBatchService) SetDeadline

func (s *AddOrderBatchService) SetDeadline(deadline string) *AddOrderBatchService

SetDeadline sets an RFC3339 rejection deadline (now + 2..60s).

func (*AddOrderBatchService) SetValidate

func (s *AddOrderBatchService) SetValidate(validate bool) *AddOrderBatchService

SetValidate validates the batch without submitting it when true.

type AddOrderResult

type AddOrderResult struct {
	Description OrderDescr `json:"descr"` // order description(s)
	TxID        []string   `json:"txid"`  // transaction id(s) of the placed order(s)
}

AddOrderResult is the AddOrder response. In validate mode TxID is empty.

type AddOrderService

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

AddOrderService places a new order. Required parameters (pair, side, order type, volume) are constructor arguments; everything else is an optional setter. Use SetValidate(true) to validate without submitting.

func (*AddOrderService) Do

func (*AddOrderService) SetClientOrderID

func (s *AddOrderService) SetClientOrderID(clOrdID string) *AddOrderService

SetClientOrderID sets a client order id. Kraken accepts one of three forms (see MaxClOrdIDLen / ValidateClOrdID): up to 18 lowercase alphanumerics, a standard UUID, or a 32-character hex string. It is not validated here; an unacceptable value is rejected by the server with "EGeneral:Invalid arguments:cl_ord_id".

func (*AddOrderService) SetCloseOrder

func (s *AddOrderService) SetCloseOrder(orderType OrderType, price, price2 decimal.Decimal) *AddOrderService

SetCloseOrder attaches a conditional close order. Pass a zero price2 to omit the secondary price.

func (*AddOrderService) SetDeadline

func (s *AddOrderService) SetDeadline(deadline string) *AddOrderService

SetDeadline sets an RFC3339 rejection deadline (now + 2..60s).

func (*AddOrderService) SetDisplayVolume

func (s *AddOrderService) SetDisplayVolume(displayVol decimal.Decimal) *AddOrderService

SetDisplayVolume sets the displayed quantity for iceberg orders.

func (*AddOrderService) SetExpireTime

func (s *AddOrderService) SetExpireTime(expireTime string) *AddOrderService

SetExpireTime sets the GTD expiry time (a unix timestamp or "+<n>" seconds).

func (*AddOrderService) SetLeverage

func (s *AddOrderService) SetLeverage(leverage string) *AddOrderService

SetLeverage sets the desired leverage amount (e.g. "2:1" or "2").

func (*AddOrderService) SetOrderFlags

func (s *AddOrderService) SetOrderFlags(oflags string) *AddOrderService

SetOrderFlags sets the comma-delimited order flags (OrderFlagPost, ...).

func (*AddOrderService) SetPrice

func (s *AddOrderService) SetPrice(price decimal.Decimal) *AddOrderService

SetPrice sets the limit price or trigger price (depending on order type).

func (*AddOrderService) SetPrice2

func (s *AddOrderService) SetPrice2(price2 decimal.Decimal) *AddOrderService

SetPrice2 sets the secondary price (for stop-loss-limit / take-profit-limit).

func (*AddOrderService) SetReduceOnly

func (s *AddOrderService) SetReduceOnly(reduceOnly bool) *AddOrderService

SetReduceOnly marks the order as reduce-only (margin).

func (*AddOrderService) SetSTPType

SetSTPType sets the self-trade-prevention behavior.

func (*AddOrderService) SetStartTime

func (s *AddOrderService) SetStartTime(startTime string) *AddOrderService

SetStartTime sets the scheduled start time ("0", a unix timestamp, or "+<n>" seconds from now).

func (*AddOrderService) SetTimeInForce

func (s *AddOrderService) SetTimeInForce(tif TimeInForce) *AddOrderService

SetTimeInForce sets the time-in-force (default GTC).

func (*AddOrderService) SetTrigger

func (s *AddOrderService) SetTrigger(trigger TriggerSignal) *AddOrderService

SetTrigger sets the price signal for stop/take-profit triggers (default last).

func (*AddOrderService) SetUserRef

func (s *AddOrderService) SetUserRef(userRef int) *AddOrderService

SetUserRef sets a non-unique numeric identifier for grouping orders.

func (*AddOrderService) SetValidate

func (s *AddOrderService) SetValidate(validate bool) *AddOrderService

SetValidate validates the order without submitting it when true.

type AllocateEarnFundsService

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

AllocateEarnFundsService allocates funds to an Earn strategy. The operation is asynchronous; poll GetAllocationStatus for completion.

func (*AllocateEarnFundsService) Do

Do reports whether the allocation request was accepted (Kraken returns a bare boolean; the allocation itself completes asynchronously).

type AmendOrderResult

type AmendOrderResult struct {
	AmendID string `json:"amend_id"` // unique id of this amend transaction
}

AmendOrderResult is the AmendOrder response.

type AmendOrderService

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

AmendOrderService amends an open order in place (preserving queue priority where possible) without a cancel-replace.

func (*AmendOrderService) Do

func (*AmendOrderService) SetClientOrderID

func (s *AmendOrderService) SetClientOrderID(clOrdID string) *AmendOrderService

SetClientOrderID amends by client order id instead of txid.

func (*AmendOrderService) SetDeadline

func (s *AmendOrderService) SetDeadline(deadline string) *AmendOrderService

SetDeadline sets an RFC3339 rejection deadline.

func (*AmendOrderService) SetDisplayQty

func (s *AmendOrderService) SetDisplayQty(qty decimal.Decimal) *AmendOrderService

SetDisplayQty sets the new iceberg display quantity.

func (*AmendOrderService) SetLimitPrice

func (s *AmendOrderService) SetLimitPrice(price decimal.Decimal) *AmendOrderService

SetLimitPrice sets the new limit price.

func (*AmendOrderService) SetOrderQty

func (s *AmendOrderService) SetOrderQty(qty decimal.Decimal) *AmendOrderService

SetOrderQty sets the new order quantity (base asset).

func (*AmendOrderService) SetPostOnly

func (s *AmendOrderService) SetPostOnly(postOnly bool) *AmendOrderService

SetPostOnly restricts the amended order from taking liquidity.

func (*AmendOrderService) SetTriggerPrice

func (s *AmendOrderService) SetTriggerPrice(price decimal.Decimal) *AmendOrderService

SetTriggerPrice sets the new trigger price (for trigger order types).

type Asset

type Asset struct {
	AssetClass      string          `json:"aclass"`           // asset class, usually "currency"
	AltName         string          `json:"altname"`          // alternate (common) name, e.g. "XBT"
	Decimals        int             `json:"decimals"`         // scaling decimal places for record keeping
	DisplayDecimals int             `json:"display_decimals"` // scaling decimal places for display
	CollateralValue decimal.Decimal `json:"collateral_value"` // valuation as margin collateral (if applicable)
	MarginRate      decimal.Decimal `json:"margin_rate"`      // margin rate (if applicable)
	Status          string          `json:"status"`           // asset status: enabled, deposit_only, withdrawal_only, funding_temporarily_disabled
}

Asset describes one tradable/fundable asset.

type AssetPair

type AssetPair struct {
	AltName            string          `json:"altname"`              // alternate pair name
	WSName             string          `json:"wsname"`               // WebSocket pair name (if available)
	AssetClassBase     string          `json:"aclass_base"`          // asset class of base component
	Base               string          `json:"base"`                 // asset id of base component
	AssetClassQuote    string          `json:"aclass_quote"`         // asset class of quote component
	Quote              string          `json:"quote"`                // asset id of quote component
	Lot                string          `json:"lot"`                  // volume lot size
	CostDecimals       int             `json:"cost_decimals"`        // scaling decimals for cost
	PairDecimals       int             `json:"pair_decimals"`        // scaling decimals for pair price
	LotDecimals        int             `json:"lot_decimals"`         // scaling decimals for volume
	LotMultiplier      int             `json:"lot_multiplier"`       // amount to multiply lot volume by to get currency volume
	LeverageBuy        []int           `json:"leverage_buy"`         // array of leverage amounts available when buying
	LeverageSell       []int           `json:"leverage_sell"`        // array of leverage amounts available when selling
	Fees               []FeeTier       `json:"fees"`                 // taker fee schedule [volume, percent]
	FeesMaker          []FeeTier       `json:"fees_maker"`           // maker fee schedule [volume, percent]
	FeeVolumeCurrency  string          `json:"fee_volume_currency"`  // volume discount currency
	MarginCall         int             `json:"margin_call"`          // margin call level
	MarginStop         int             `json:"margin_stop"`          // stop-out / liquidation margin level
	OrderMin           decimal.Decimal `json:"ordermin"`             // minimum order size (in base currency)
	CostMin            decimal.Decimal `json:"costmin"`              // minimum order cost (in quote currency)
	TickSize           decimal.Decimal `json:"tick_size"`            // minimum price increment
	Status             string          `json:"status"`               // online | cancel_only | post_only | limit_only | reduce_only
	LongPositionLimit  int             `json:"long_position_limit"`  // maximum long margin position size (in base currency)
	ShortPositionLimit int             `json:"short_position_limit"` // maximum short margin position size (in base currency)
	ExecutionVenue     string          `json:"execution_venue"`      // execution venue, e.g. "international"
}

AssetPair describes one tradable asset pair.

type AssetPairsInfo

type AssetPairsInfo string

AssetPairsInfo selects which subset of fields AssetPairs returns.

const (
	AssetPairsInfoAll      AssetPairsInfo = "info"
	AssetPairsInfoLeverage AssetPairsInfo = "leverage"
	AssetPairsInfoFees     AssetPairsInfo = "fees"
	AssetPairsInfoMargin   AssetPairsInfo = "margin"
)

type BatchOrder

type BatchOrder struct {
	OrderType     OrderType           // required: execution model
	Side          OrderSide           // required: buy or sell
	Volume        decimal.Decimal     // required: base-currency quantity
	Price         decimal.Decimal     // limit/trigger price (omitted if zero)
	Price2        decimal.Decimal     // secondary price (omitted if zero)
	OrderFlags    string              // comma-delimited order flags
	TimeInForce   TimeInForce         // time in force
	Trigger       TriggerSignal       // trigger price signal
	STPType       SelfTradePrevention // self-trade prevention
	ReduceOnly    bool                // reduce-only (margin)
	DisplayVolume decimal.Decimal     // iceberg display quantity (omitted if zero)
	UserRef       int                 // group identifier (omitted if zero)
	ClientOrderID string              // client order id
	StartTime     string              // scheduled start time
	ExpireTime    string              // GTD expiry
}

BatchOrder is one leg of an AddOrderBatch request. Zero-valued optional fields are omitted from the request.

type BatchOrderResult

type BatchOrderResult struct {
	TxID        string     `json:"txid"`  // transaction id, if successful
	Description OrderDescr `json:"descr"` // order description
	Error       string     `json:"error"` // per-order error message, if any
}

BatchOrderResult is the outcome of one batched order.

type BookChecksummer added in v0.20260622.1

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

BookChecksummer maintains the top-of-book state required to verify the CRC32 checksum Kraken sends with every level-2 "book" channel frame (WsBook.Checksum).

Kraken's WS v2 book channel carries no sequence numbers, so the per-frame CRC32 is the only way to detect a desynchronised local book. Kraken transmits the checksum but provides no way to validate it: a consumer must reconstruct the top-10 book in the exact fixed-precision wire representation and re-run the algorithm. BookChecksummer owns that representation and the (easy-to-get-wrong) algorithm so consumers need not reimplement it.

It deliberately keeps only what the checksum needs — the price/quantity levels in fixed-precision form — and is NOT a general-purpose order book. Feed it the same WsBook frames you receive (ApplySnapshot for a "snapshot" frame, ApplyUpdate for an "update" frame) and call Verify (or Checksum) afterwards.

A BookChecksummer is not safe for concurrent use; callers serialise frame handling (the book channel is a single ordered stream).

func NewBookChecksummer added in v0.20260622.1

func NewBookChecksummer(priceDecimals, qtyDecimals int32) *BookChecksummer

NewBookChecksummer returns a checksummer for a pair whose price and quantity are formatted to priceDecimals and qtyDecimals respectively. For Kraken spot these are AssetPair.PairDecimals and AssetPair.LotDecimals.

func (*BookChecksummer) ApplySnapshot added in v0.20260622.1

func (b *BookChecksummer) ApplySnapshot(book WsBook)

ApplySnapshot replaces the maintained book with a snapshot frame's full depth.

func (*BookChecksummer) ApplyUpdate added in v0.20260622.1

func (b *BookChecksummer) ApplyUpdate(book WsBook)

ApplyUpdate merges an update frame's changed levels into the maintained book. A level with quantity <= 0 removes that price.

func (*BookChecksummer) Checksum added in v0.20260622.1

func (b *BookChecksummer) Checksum() uint32

Checksum computes the CRC32 (IEEE) of the current top-10 book per Kraken's WS v2 spec: the top 10 asks (ascending price) followed by the top 10 bids (descending price); for each level the price (formatted to priceDecimals) then the quantity (formatted to qtyDecimals), each with its decimal point and leading zeros removed, all concatenated.

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

func (*BookChecksummer) Reset added in v0.20260622.1

func (b *BookChecksummer) Reset()

Reset clears the maintained book. Call it before applying a fresh snapshot after a reconnect so stale levels do not leak into the next checksum.

func (*BookChecksummer) Verify added in v0.20260622.1

func (b *BookChecksummer) Verify(serverChecksum int64) error

Verify compares the locally computed checksum against the value carried on the frame (WsBook.Checksum, a uint32 widened to int64). A non-positive server value is treated as "no checksum on this frame" and returns nil; a mismatch returns an error wrapping ErrBookChecksumMismatch.

type BookEntry

type BookEntry struct {
	Price     decimal.Decimal
	Volume    decimal.Decimal
	Timestamp time.Time
}

BookEntry is one order-book level: [price, volume, timestamp].

func (BookEntry) MarshalJSON

func (e BookEntry) MarshalJSON() ([]byte, error)

func (*BookEntry) UnmarshalJSON

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

type CancelAllOrdersAfterResult

type CancelAllOrdersAfterResult struct {
	CurrentTime time.Time `json:"currentTime"` // when the request was received (RFC3339)
	TriggerTime time.Time `json:"triggerTime"` // when orders will be cancelled (RFC3339)
}

CancelAllOrdersAfterResult is the CancelAllOrdersAfter response.

type CancelAllOrdersAfterService

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

CancelAllOrdersAfterService arms (or disarms, with timeout 0) a dead-man's switch that cancels all open orders after the given number of seconds unless the timer is reset.

func (*CancelAllOrdersAfterService) Do

type CancelAllOrdersResult

type CancelAllOrdersResult struct {
	Count int `json:"count"` // number of orders cancelled
}

CancelAllOrdersResult is the CancelAll response.

type CancelAllOrdersService

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

CancelAllOrdersService cancels all open orders.

func (*CancelAllOrdersService) Do

type CancelOrderBatchResult

type CancelOrderBatchResult struct {
	Count int `json:"count"` // number of orders cancelled
}

CancelOrderBatchResult is the CancelOrderBatch response.

type CancelOrderBatchService

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

CancelOrderBatchService cancels up to 50 open orders by txid (or userref) in one request.

func (*CancelOrderBatchService) Do

type CancelOrderResult

type CancelOrderResult struct {
	Count   int  `json:"count"`   // number of orders cancelled
	Pending bool `json:"pending"` // whether cancellation is still pending
}

CancelOrderResult is the CancelOrder response.

type CancelOrderService

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

CancelOrderService cancels a single open order by txid (or userref).

func (*CancelOrderService) Do

func (*CancelOrderService) SetClientOrderID

func (s *CancelOrderService) SetClientOrderID(clOrdID string) *CancelOrderService

SetClientOrderID cancels by client order id instead of txid.

type Candle

type Candle struct {
	Time   time.Time       // candle start time
	Open   decimal.Decimal // opening price
	High   decimal.Decimal // highest price
	Low    decimal.Decimal // lowest price
	Close  decimal.Decimal // closing price
	VWAP   decimal.Decimal // volume weighted average price
	Volume decimal.Decimal // traded volume
	Count  int64           // number of trades
}

Candle is one OHLC row: [time, open, high, low, close, vwap, volume, count].

func (Candle) MarshalJSON

func (k Candle) MarshalJSON() ([]byte, error)

func (*Candle) UnmarshalJSON

func (k *Candle) UnmarshalJSON(data []byte) error

type Client

type Client struct {
	*client.Client
}

Client is the Kraken spot REST client. It embeds the shared transport/signing core and exposes every endpoint as a NewXxxService(...).Do(ctx) method.

func NewClient

func NewClient(options ...client.Options) *Client

NewClient constructs a Kraken spot REST client from the standard options (client.WithAuth, client.WithProxy, client.WithBaseURL, ...).

func (*Client) NewAccountTransferService

func (c *Client) NewAccountTransferService(asset string, amount decimal.Decimal, from, to string) *AccountTransferService

NewAccountTransferService transfers amount of asset from the source account id to the destination account id.

func (*Client) NewAddOrderBatchService

func (c *Client) NewAddOrderBatchService(pair string) *AddOrderBatchService

NewAddOrderBatchService starts a batch for the given pair.

func (*Client) NewAddOrderService

func (c *Client) NewAddOrderService(pair string, side OrderSide, orderType OrderType, volume decimal.Decimal) *AddOrderService

NewAddOrderService builds an order for pair with the given side, order type and volume (base currency).

func (*Client) NewAllocateEarnFundsService

func (c *Client) NewAllocateEarnFundsService(strategyID string, amount decimal.Decimal) *AllocateEarnFundsService

NewAllocateEarnFundsService allocates amount of the strategy's asset to the strategy.

func (*Client) NewAmendOrderService

func (c *Client) NewAmendOrderService(txid string) *AmendOrderService

NewAmendOrderService amends the order with the given Kraken txid. To amend by client order id instead, pass "" and call SetClientOrderID.

func (*Client) NewCancelAllOrdersAfterService

func (c *Client) NewCancelAllOrdersAfterService(timeout int) *CancelAllOrdersAfterService

NewCancelAllOrdersAfterService sets the timer to timeout seconds (0 disables).

func (*Client) NewCancelAllOrdersService

func (c *Client) NewCancelAllOrdersService() *CancelAllOrdersService

func (*Client) NewCancelOrderBatchService

func (c *Client) NewCancelOrderBatchService(txids ...string) *CancelOrderBatchService

NewCancelOrderBatchService cancels the given order txids (or userref strings).

func (*Client) NewCancelOrderService

func (c *Client) NewCancelOrderService(txid string) *CancelOrderService

NewCancelOrderService cancels the order with the given txid. A numeric userref string cancels all orders sharing that reference.

func (*Client) NewCreateSubaccountService

func (c *Client) NewCreateSubaccountService(username, email string) *CreateSubaccountService

NewCreateSubaccountService creates a subaccount with the given username and email.

func (*Client) NewDeallocateEarnFundsService

func (c *Client) NewDeallocateEarnFundsService(strategyID string, amount decimal.Decimal) *DeallocateEarnFundsService

NewDeallocateEarnFundsService deallocates amount from the strategy.

func (*Client) NewDeleteExportReportService

func (c *Client) NewDeleteExportReportService(id string, opType DeleteExportReportType) *DeleteExportReportService

NewDeleteExportReportService removes the report with the given id. Use DeleteExportReportTypeCancel for a queued report and ...Delete for a processed one.

func (*Client) NewEditOrderService

func (c *Client) NewEditOrderService(pair, txid string) *EditOrderService

NewEditOrderService edits the order txid on pair.

func (*Client) NewGetAccountBalanceService

func (c *Client) NewGetAccountBalanceService() *GetAccountBalanceService

func (*Client) NewGetAllocationStatusService

func (c *Client) NewGetAllocationStatusService(strategyID string) *GetAllocationStatusService

func (*Client) NewGetApiKeyInfoService

func (c *Client) NewGetApiKeyInfoService() *GetApiKeyInfoService

func (*Client) NewGetAssetInfoService

func (c *Client) NewGetAssetInfoService() *GetAssetInfoService

func (*Client) NewGetClosedOrdersService

func (c *Client) NewGetClosedOrdersService() *GetClosedOrdersService

func (*Client) NewGetCreditLinesService

func (c *Client) NewGetCreditLinesService() *GetCreditLinesService

func (*Client) NewGetDeallocationStatusService

func (c *Client) NewGetDeallocationStatusService(strategyID string) *GetDeallocationStatusService

func (*Client) NewGetDepositAddressesService

func (c *Client) NewGetDepositAddressesService(asset, method string) *GetDepositAddressesService

NewGetDepositAddressesService lists addresses for asset/method.

func (*Client) NewGetDepositMethodsService

func (c *Client) NewGetDepositMethodsService(asset string) *GetDepositMethodsService

NewGetDepositMethodsService lists deposit methods for the given asset.

func (*Client) NewGetDepositStatusService

func (c *Client) NewGetDepositStatusService() *GetDepositStatusService

func (*Client) NewGetExportReportStatusService

func (c *Client) NewGetExportReportStatusService(report ReportType) *GetExportReportStatusService

NewGetExportReportStatusService lists reports of the given type (trades/ledgers).

func (*Client) NewGetExtendedBalanceService

func (c *Client) NewGetExtendedBalanceService() *GetExtendedBalanceService

func (*Client) NewGetGroupedOrderBookService

func (c *Client) NewGetGroupedOrderBookService(pair string) *GetGroupedOrderBookService

func (*Client) NewGetLedgersService

func (c *Client) NewGetLedgersService() *GetLedgersService

func (*Client) NewGetOHLCDataService

func (c *Client) NewGetOHLCDataService(pair string) *GetOHLCDataService

func (*Client) NewGetOpenOrdersService

func (c *Client) NewGetOpenOrdersService() *GetOpenOrdersService

func (*Client) NewGetOpenPositionsService

func (c *Client) NewGetOpenPositionsService() *GetOpenPositionsService

func (*Client) NewGetOrderAmendsService

func (c *Client) NewGetOrderAmendsService(orderID string) *GetOrderAmendsService

NewGetOrderAmendsService queries amends for one Kraken order id.

func (*Client) NewGetOrderBookService

func (c *Client) NewGetOrderBookService(pair string) *GetOrderBookService

func (*Client) NewGetPostTradeDataService

func (c *Client) NewGetPostTradeDataService() *GetPostTradeDataService

func (*Client) NewGetPreTradeDataService

func (c *Client) NewGetPreTradeDataService(symbol string) *GetPreTradeDataService

NewGetPreTradeDataService queries pre-trade data for a symbol (e.g. "BTC/USD").

func (*Client) NewGetRecentSpreadsService

func (c *Client) NewGetRecentSpreadsService(pair string) *GetRecentSpreadsService

func (*Client) NewGetRecentTradesService

func (c *Client) NewGetRecentTradesService(pair string) *GetRecentTradesService

func (*Client) NewGetServerTimeService

func (c *Client) NewGetServerTimeService() *GetServerTimeService

func (*Client) NewGetSystemStatusService

func (c *Client) NewGetSystemStatusService() *GetSystemStatusService

func (*Client) NewGetTickerService

func (c *Client) NewGetTickerService() *GetTickerService

func (*Client) NewGetTradableAssetPairsService

func (c *Client) NewGetTradableAssetPairsService() *GetTradableAssetPairsService

func (*Client) NewGetTradeBalanceService

func (c *Client) NewGetTradeBalanceService() *GetTradeBalanceService

func (*Client) NewGetTradeVolumeService

func (c *Client) NewGetTradeVolumeService() *GetTradeVolumeService

func (*Client) NewGetTradesHistoryService

func (c *Client) NewGetTradesHistoryService() *GetTradesHistoryService

func (*Client) NewGetWebSocketsTokenService

func (c *Client) NewGetWebSocketsTokenService() *GetWebSocketsTokenService

func (*Client) NewGetWithdrawAddressesService

func (c *Client) NewGetWithdrawAddressesService() *GetWithdrawAddressesService

func (*Client) NewGetWithdrawInfoService

func (c *Client) NewGetWithdrawInfoService(asset, key string, amount decimal.Decimal) *GetWithdrawInfoService

NewGetWithdrawInfoService queries withdrawal info for the asset, withdrawal key name and amount.

func (*Client) NewGetWithdrawMethodsService

func (c *Client) NewGetWithdrawMethodsService() *GetWithdrawMethodsService

func (*Client) NewGetWithdrawStatusService

func (c *Client) NewGetWithdrawStatusService() *GetWithdrawStatusService

func (*Client) NewListEarnAllocationsService

func (c *Client) NewListEarnAllocationsService() *ListEarnAllocationsService

func (*Client) NewListEarnStrategiesService

func (c *Client) NewListEarnStrategiesService() *ListEarnStrategiesService

func (*Client) NewQueryL3OrderBookService

func (c *Client) NewQueryL3OrderBookService(pair string) *QueryL3OrderBookService

func (*Client) NewQueryLedgersService

func (c *Client) NewQueryLedgersService(ids ...string) *QueryLedgersService

NewQueryLedgersService queries up to 20 ledger entries by their ids.

func (*Client) NewQueryOrdersService

func (c *Client) NewQueryOrdersService(txids ...string) *QueryOrdersService

NewQueryOrdersService queries up to 50 orders by their tx ids.

func (*Client) NewQueryTradesService

func (c *Client) NewQueryTradesService(txids ...string) *QueryTradesService

NewQueryTradesService queries up to 20 trades by their tx ids.

func (*Client) NewRequestExportReportService

func (c *Client) NewRequestExportReportService(report ReportType, description string) *RequestExportReportService

NewRequestExportReportService starts an export of the given report type with a human-readable description.

func (*Client) NewRetrieveDataExportService

func (c *Client) NewRetrieveDataExportService(id string) *RetrieveDataExportService

NewRetrieveDataExportService retrieves the report with the given id.

func (*Client) NewWalletTransferService

func (c *Client) NewWalletTransferService(asset string, amount decimal.Decimal) *WalletTransferService

NewWalletTransferService transfers amount of asset from "Spot Wallet" to "Futures Wallet".

func (*Client) NewWithdrawCancelService

func (c *Client) NewWithdrawCancelService(asset, refID string) *WithdrawCancelService

NewWithdrawCancelService cancels the withdrawal identified by asset and refid.

func (*Client) NewWithdrawService

func (c *Client) NewWithdrawService(asset, key string, amount decimal.Decimal) *WithdrawService

NewWithdrawService withdraws amount of asset to the withdrawal key.

type ClosedOrdersResult

type ClosedOrdersResult struct {
	Closed map[string]OrderInfo `json:"closed"`
	Count  int                  `json:"count"`
}

ClosedOrdersResult holds the closed-orders map plus the total count.

type CreateSubaccountService

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

CreateSubaccountService creates a trading subaccount (institutional accounts only).

func (*CreateSubaccountService) Do

Do reports whether the subaccount was created (Kraken returns a bare boolean).

type CreditAssetDetail

type CreditAssetDetail struct {
	Balance         decimal.Decimal `json:"balance"`          // asset balance
	CollateralValue decimal.Decimal `json:"collateral_value"` // collateral valuation factor
	HoldTrade       decimal.Decimal `json:"hold_trade"`       // balance held for open orders
}

CreditAssetDetail is the collateral detail for one asset.

type CreditLimitsMonitor

type CreditLimitsMonitor struct {
	DebtToEquity            decimal.Decimal `json:"debt_to_equity"`             // debt-to-equity ratio
	EquityUSD               decimal.Decimal `json:"equity_usd"`                 // total equity (USD)
	TotalCollateralValueUSD decimal.Decimal `json:"total_collateral_value_usd"` // total collateral value (USD)
	TotalCreditUSD          decimal.Decimal `json:"total_credit_usd"`           // total credit line (USD)
	TotalCreditUsedUSD      decimal.Decimal `json:"total_credit_used_usd"`      // credit currently used (USD)
}

CreditLimitsMonitor is the aggregate margin-limits snapshot.

type CreditLines

type CreditLines struct {
	AssetDetails  map[string]CreditAssetDetail `json:"asset_details"`  // per-asset collateral details
	LimitsMonitor CreditLimitsMonitor          `json:"limits_monitor"` // aggregate margin limits
}

CreditLines summarizes margin collateral and limits.

type DeallocateEarnFundsService

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

DeallocateEarnFundsService removes previously allocated funds from an Earn strategy. The operation is asynchronous; poll GetDeallocationStatus.

func (*DeallocateEarnFundsService) Do

Do reports whether the deallocation request was accepted.

type DeleteExportReportService

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

DeleteExportReportService cancels a queued report or deletes a processed one.

func (*DeleteExportReportService) Do

type DeleteExportReportType

type DeleteExportReportType string

DeleteExportReportType is the operation to perform on an export report.

const (
	DeleteExportReportTypeCancel DeleteExportReportType = "cancel"
	DeleteExportReportTypeDelete DeleteExportReportType = "delete"
)

type DeleteExportResult

type DeleteExportResult struct {
	Delete bool `json:"delete"` // whether deletion was successful
	Cancel bool `json:"cancel"` // whether cancellation was successful
}

DeleteExportResult reports the outcome of a delete/cancel operation.

type DepositAddress

type DepositAddress struct {
	Address    string    `json:"address"`  // deposit address
	ExpireTime time.Time `json:"expiretm"` // expiration time (zero if it does not expire)
	New        bool      `json:"new"`      // whether the address was newly generated
	Memo       string    `json:"memo"`     // memo for the deposit (some assets)
	Tag        string    `json:"tag"`      // destination tag (some assets)
}

DepositAddress is one deposit address.

type DepositMethod

type DepositMethod struct {
	Method     string          `json:"method"`      // name of the deposit method
	Limit      MethodLimit     `json:"limit"`       // deposit limit (false if none)
	Fee        decimal.Decimal `json:"fee"`         // deposit fee, if any
	GenAddress bool            `json:"gen-address"` // whether new addresses can be generated
	Minimum    decimal.Decimal `json:"minimum"`     // minimum deposit amount
}

DepositMethod is one available deposit method.

type EarnAPREstimate

type EarnAPREstimate struct {
	High decimal.Decimal `json:"high"`
	Low  decimal.Decimal `json:"low"`
}

EarnAPREstimate is the estimated APR range for a strategy.

type EarnAllocation

type EarnAllocation struct {
	StrategyID      string              `json:"strategy_id"`      // strategy id
	NativeAsset     string              `json:"native_asset"`     // asset allocated
	AssetClass      string              `json:"asset_class"`      // asset class of the allocated asset
	IsUtilized      bool                `json:"is_utilized"`      // whether the allocation is currently utilized
	AmountAllocated EarnAmountAllocated `json:"amount_allocated"` // breakdown of allocated amounts
	TotalRewarded   EarnConvertedAmount `json:"total_rewarded"`   // total rewards earned
	Payout          EarnPayout          `json:"payout"`           // current payout period info
}

EarnAllocation is the account's allocation to a single strategy.

type EarnAllocationDetail

type EarnAllocationDetail struct {
	Native    decimal.Decimal `json:"native"`     // amount in the native asset
	Converted decimal.Decimal `json:"converted"`  // amount in the converted asset
	CreatedAt time.Time       `json:"created_at"` // when the allocation was created
	Expires   time.Time       `json:"expires"`    // when bonding/unbonding completes
}

EarnAllocationDetail is one individual allocation record within a state.

type EarnAllocationState

type EarnAllocationState struct {
	Native          decimal.Decimal        `json:"native"`           // amount in native asset
	Converted       decimal.Decimal        `json:"converted"`        // amount in converted asset
	AllocationCount int                    `json:"allocation_count"` // number of individual allocations
	Allocations     []EarnAllocationDetail `json:"allocations"`      // individual allocation records
}

EarnAllocationState is an allocation lifecycle bucket with its individual allocation records.

type EarnAllocationStatus

type EarnAllocationStatus struct {
	Pending bool `json:"pending"` // whether the operation is still being processed
}

EarnAllocationStatus reports whether an (de)allocation is pending.

type EarnAllocationsResult

type EarnAllocationsResult struct {
	ConvertedAsset      string           `json:"converted_asset"`       // asset the converted values are in
	ConvertedAssetClass string           `json:"converted_asset_class"` // class of the converted asset
	TotalAllocated      decimal.Decimal  `json:"total_allocated"`       // total allocated (converted asset)
	TotalRewarded       decimal.Decimal  `json:"total_rewarded"`        // total rewarded (converted asset)
	NextCursor          string           `json:"next_cursor"`           // pagination cursor
	Items               []EarnAllocation `json:"items"`                 // per-strategy allocations
}

EarnAllocationsResult is the account's Earn allocation summary.

type EarnAmountAllocated

type EarnAmountAllocated struct {
	Bonding   EarnAllocationState `json:"bonding"`    // amount currently bonding
	ExitQueue EarnAllocationState `json:"exit_queue"` // amount in the exit queue
	Pending   EarnConvertedAmount `json:"pending"`    // amount pending allocation
	Unbonding EarnAllocationState `json:"unbonding"`  // amount currently unbonding
	Total     EarnConvertedAmount `json:"total"`      // total allocated
}

EarnAmountAllocated breaks an allocation into its lifecycle states.

type EarnConvertedAmount

type EarnConvertedAmount struct {
	Native    decimal.Decimal `json:"native"`    // amount in the native asset
	Converted decimal.Decimal `json:"converted"` // amount in the converted asset
}

EarnConvertedAmount is an amount expressed in both the native and converted assets.

type EarnLockType

type EarnLockType struct {
	Type                    string `json:"type"`                      // flex, bonded, timed, instant
	PayoutFrequency         int64  `json:"payout_frequency"`          // reward payout frequency (seconds)
	BondingPeriod           int64  `json:"bonding_period"`            // bonding period (seconds)
	BondingPeriodVariable   bool   `json:"bonding_period_variable"`   // whether the bonding period varies
	BondingRewards          bool   `json:"bonding_rewards"`           // whether rewards accrue while bonding
	ExitQueuePeriod         int64  `json:"exit_queue_period"`         // exit-queue period (seconds)
	UnbondingPeriod         int64  `json:"unbonding_period"`          // unbonding period (seconds)
	UnbondingPeriodVariable bool   `json:"unbonding_period_variable"` // whether the unbonding period varies
	UnbondingRewards        bool   `json:"unbonding_rewards"`         // whether rewards accrue while unbonding
}

EarnLockType describes a strategy's lock/bonding terms. Bonding/unbonding fields are present only for bonded/timed strategies.

type EarnNamedType

type EarnNamedType struct {
	Type string `json:"type"`
}

EarnNamedType is a simple "{type: ...}" descriptor used by auto_compound and yield_source.

type EarnPayout

type EarnPayout struct {
	AccumulatedReward EarnConvertedAmount `json:"accumulated_reward"` // reward accrued this period
	EstimatedReward   EarnConvertedAmount `json:"estimated_reward"`   // estimated reward for the period
	PeriodStart       time.Time           `json:"period_start"`       // start of the payout period
	PeriodEnd         time.Time           `json:"period_end"`         // end of the payout period
}

EarnPayout describes the current reward payout period.

type EarnStrategiesResult

type EarnStrategiesResult struct {
	Items      []EarnStrategy `json:"items"`
	NextCursor string         `json:"next_cursor"`
}

EarnStrategiesResult is a page of Earn strategies.

type EarnStrategy

type EarnStrategy struct {
	ID                        string          `json:"id"`                          // strategy id
	Asset                     string          `json:"asset"`                       // asset that can be allocated
	AssetClass                string          `json:"asset_class"`                 // asset class
	AllocationFee             decimal.Decimal `json:"allocation_fee"`              // fee charged on allocation
	DeallocationFee           decimal.Decimal `json:"deallocation_fee"`            // fee charged on deallocation
	AllocationRestrictionInfo []string        `json:"allocation_restriction_info"` // reasons allocation may be restricted
	APREstimate               EarnAPREstimate `json:"apr_estimate"`                // estimated APR range
	AutoCompound              EarnNamedType   `json:"auto_compound"`               // auto-compound behavior
	CanAllocate               bool            `json:"can_allocate"`                // whether allocation is currently allowed
	CanDeallocate             bool            `json:"can_deallocate"`              // whether deallocation is currently allowed
	LockType                  EarnLockType    `json:"lock_type"`                   // lock/bonding terms
	UserCap                   decimal.Decimal `json:"user_cap"`                    // maximum the user may allocate
	UserMinAllocation         decimal.Decimal `json:"user_min_allocation"`         // minimum the user may allocate
	YieldSource               EarnNamedType   `json:"yield_source"`                // source of the yield
}

EarnStrategy describes one Earn strategy.

type EditOrderResult

type EditOrderResult struct {
	Status          string          `json:"status"`           // Ok or Err
	TxID            string          `json:"txid"`             // new transaction id
	OriginalTxID    string          `json:"originaltxid"`     // original transaction id
	OrdersCancelled int             `json:"orders_cancelled"` // number of orders cancelled (0 or 1)
	Description     OrderDescr      `json:"descr"`            // new order description
	NewUserRef      string          `json:"newuserref"`       // new user reference
	OldUserRef      string          `json:"olduserref"`       // original user reference
	Volume          decimal.Decimal `json:"volume"`           // updated volume
	Price           decimal.Decimal `json:"price"`            // updated price
	Price2          decimal.Decimal `json:"price2"`           // updated secondary price
	ErrorMessage    string          `json:"error_message"`    // error detail, if unsuccessful
}

EditOrderResult is the EditOrder response.

type EditOrderService

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

EditOrderService cancel-replaces an existing order with new parameters (yielding a new txid).

func (*EditOrderService) Do

func (*EditOrderService) SetCancelResponse

func (s *EditOrderService) SetCancelResponse(cancelResponse bool) *EditOrderService

SetCancelResponse includes the cancellation result in the response.

func (*EditOrderService) SetDeadline

func (s *EditOrderService) SetDeadline(deadline string) *EditOrderService

SetDeadline sets an RFC3339 rejection deadline.

func (*EditOrderService) SetDisplayVolume

func (s *EditOrderService) SetDisplayVolume(displayVol decimal.Decimal) *EditOrderService

SetDisplayVolume sets the new iceberg display volume.

func (*EditOrderService) SetOrderFlags

func (s *EditOrderService) SetOrderFlags(oflags string) *EditOrderService

SetOrderFlags sets the comma-delimited order flags.

func (*EditOrderService) SetPrice

func (s *EditOrderService) SetPrice(price decimal.Decimal) *EditOrderService

SetPrice sets the new price.

func (*EditOrderService) SetPrice2

func (s *EditOrderService) SetPrice2(price2 decimal.Decimal) *EditOrderService

SetPrice2 sets the new secondary price.

func (*EditOrderService) SetUserRef

func (s *EditOrderService) SetUserRef(userRef int) *EditOrderService

SetUserRef sets a new user reference id.

func (*EditOrderService) SetValidate

func (s *EditOrderService) SetValidate(validate bool) *EditOrderService

SetValidate validates the edit without submitting it when true.

func (*EditOrderService) SetVolume

func (s *EditOrderService) SetVolume(volume decimal.Decimal) *EditOrderService

SetVolume sets the new order volume (base currency).

type ExportReport

type ExportReport struct {
	ID            string    `json:"id"`            // unique report identifier
	Description   string    `json:"descr"`         // report description/name
	Format        string    `json:"format"`        // file format (CSV/TSV)
	Report        string    `json:"report"`        // report type (trades/ledgers)
	SubType       string    `json:"subtype"`       // report subtype
	Status        string    `json:"status"`        // Queued, Processing, Processed
	Error         string    `json:"error"`         // error code if failed
	Flags         string    `json:"flags"`         // legacy flag field (deprecated)
	Fields        string    `json:"fields"`        // fields included
	CreatedTime   time.Time `json:"createdtm"`     // time the report was requested
	ExpireTime    time.Time `json:"expiretm"`      // expiration timestamp (deprecated)
	StartTime     time.Time `json:"starttm"`       // time processing began
	CompletedTime time.Time `json:"completedtm"`   // time processing finished
	DataStartTime time.Time `json:"datastarttm"`   // report data period start
	DataEndTime   time.Time `json:"dataendtm"`     // report data period end
	AssetClass    string    `json:"aclass"`        // asset class (deprecated)
	Asset         string    `json:"asset"`         // assets included
	Assets        string    `json:"assets"`        // assets included (current key)
	AssetClasses  []string  `json:"asset_classes"` // asset classes covered
	EndTime       time.Time `json:"endtm"`         // report end time
	Delete        bool      `json:"delete"`        // whether marked for deletion
}

ExportReport is the status of one export report.

type ExportReportRef

type ExportReportRef struct {
	ID string `json:"id"` // unique report identifier
}

ExportReportRef references a newly created export report.

type ExtendedBalance

type ExtendedBalance struct {
	Balance   decimal.Decimal `json:"balance"`    // total balance of the asset
	HoldTrade decimal.Decimal `json:"hold_trade"` // balance held for open orders/positions
}

ExtendedBalance is one asset's total balance and the portion held for orders.

type FeeInfo

type FeeInfo struct {
	Fee        decimal.Decimal `json:"fee"`        // current fee (percent)
	MinFee     decimal.Decimal `json:"minfee"`     // minimum fee (percent, if not fixed)
	MaxFee     decimal.Decimal `json:"maxfee"`     // maximum fee (percent, if not fixed)
	NextFee    decimal.Decimal `json:"nextfee"`    // next-tier fee (percent, if not fixed)
	TierVolume decimal.Decimal `json:"tiervolume"` // volume level of current tier
	NextVolume decimal.Decimal `json:"nextvolume"` // volume level of next tier
}

FeeInfo is the fee schedule for one pair.

type FeeTier

type FeeTier struct {
	Volume  decimal.Decimal // 30-day volume threshold (quote currency)
	Percent decimal.Decimal // fee percentage at or above that volume
}

FeeTier is one [volume, percent] row of a fee schedule.

func (FeeTier) MarshalJSON

func (f FeeTier) MarshalJSON() ([]byte, error)

func (*FeeTier) UnmarshalJSON

func (f *FeeTier) UnmarshalJSON(data []byte) error

type GetAccountBalanceService

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

GetAccountBalanceService returns all cash balances, net of pending withdrawals, keyed by Kraken asset name.

func (*GetAccountBalanceService) Do

type GetAllocationStatusService

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

GetAllocationStatusService reports whether an allocation to a strategy is still being processed.

func (*GetAllocationStatusService) Do

type GetApiKeyInfoService

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

GetApiKeyInfoService returns metadata about the API key used to sign the request: its name, permissions, IP allowlist and nonce settings.

func (*GetApiKeyInfoService) Do

type GetAssetInfoService

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

GetAssetInfoService returns information about the assets available for trading and funding, keyed by Kraken asset name (e.g. "XXBT", "ZUSD").

func (*GetAssetInfoService) Do

func (*GetAssetInfoService) SetAsset

func (s *GetAssetInfoService) SetAsset(assets ...string) *GetAssetInfoService

SetAsset filters to specific assets (comma-separated, e.g. "XBT,ETH").

func (*GetAssetInfoService) SetAssetClass

func (s *GetAssetInfoService) SetAssetClass(aclass string) *GetAssetInfoService

SetAssetClass filters by asset class (default "currency").

type GetClosedOrdersService

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

GetClosedOrdersService returns the account's closed orders (most recent first), with pagination.

func (*GetClosedOrdersService) Do

func (*GetClosedOrdersService) SetClientOrderID

func (s *GetClosedOrdersService) SetClientOrderID(clOrdID string) *GetClosedOrdersService

SetClientOrderID filters by client order id.

func (*GetClosedOrdersService) SetCloseTime

func (s *GetClosedOrdersService) SetCloseTime(closeTime string) *GetClosedOrdersService

SetCloseTime selects which timestamp to use for searching (open, close, both).

func (*GetClosedOrdersService) SetEnd

SetEnd sets the ending unix timestamp or order tx id (inclusive).

func (*GetClosedOrdersService) SetOffset

SetOffset sets the result offset for pagination.

func (*GetClosedOrdersService) SetStart

SetStart sets the starting unix timestamp or order tx id (inclusive).

func (*GetClosedOrdersService) SetTrades

func (s *GetClosedOrdersService) SetTrades(trades bool) *GetClosedOrdersService

SetTrades includes related trade ids in the output.

func (*GetClosedOrdersService) SetUserRef

func (s *GetClosedOrdersService) SetUserRef(userRef int) *GetClosedOrdersService

SetUserRef filters by user reference id.

func (*GetClosedOrdersService) SetWithoutCount

func (s *GetClosedOrdersService) SetWithoutCount(withoutCount bool) *GetClosedOrdersService

SetWithoutCount skips the total-count calculation to improve speed.

type GetCreditLinesService

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

GetCreditLinesService returns the account's margin credit lines: per-asset collateral details and a margin-limits monitor. Available to eligible (typically VIP) accounts.

func (*GetCreditLinesService) Do

type GetDeallocationStatusService

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

GetDeallocationStatusService reports whether a deallocation from a strategy is still being processed.

func (*GetDeallocationStatusService) Do

type GetDepositAddressesService

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

GetDepositAddressesService lists (or generates) deposit addresses for an asset and method.

func (*GetDepositAddressesService) Do

func (*GetDepositAddressesService) SetAmount

SetAmount requests an address for a Lightning deposit of the given amount.

func (*GetDepositAddressesService) SetNew

SetNew generates a new address (instead of returning existing ones).

type GetDepositMethodsService

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

GetDepositMethodsService lists the deposit methods available for an asset.

func (*GetDepositMethodsService) Do

func (*GetDepositMethodsService) SetAssetClass

func (s *GetDepositMethodsService) SetAssetClass(aclass string) *GetDepositMethodsService

SetAssetClass filters by asset class (default currency).

type GetDepositStatusService

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

GetDepositStatusService lists recent deposits.

func (*GetDepositStatusService) Do

func (*GetDepositStatusService) SetAsset

SetAsset filters by asset.

func (*GetDepositStatusService) SetAssetClass

func (s *GetDepositStatusService) SetAssetClass(aclass string) *GetDepositStatusService

SetAssetClass filters by asset class (default currency).

func (*GetDepositStatusService) SetMethod

SetMethod filters by deposit method.

type GetExportReportStatusService

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

GetExportReportStatusService lists the status of the account's export reports of a given type.

func (*GetExportReportStatusService) Do

type GetExtendedBalanceService

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

GetExtendedBalanceService returns all cash balances with a breakdown of the amount held for open orders/positions, keyed by Kraken asset name.

func (*GetExtendedBalanceService) Do

type GetGroupedOrderBookService

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

GetGroupedOrderBookService returns an order book whose volume is aggregated over a configurable tick range ("grouping"), for one pair.

func (*GetGroupedOrderBookService) Do

func (*GetGroupedOrderBookService) SetDepth

SetDepth sets the number of price levels per side (10, 25, 100, 250, 1000; default 10).

func (*GetGroupedOrderBookService) SetGrouping

func (s *GetGroupedOrderBookService) SetGrouping(grouping int) *GetGroupedOrderBookService

SetGrouping sets the number of ticks aggregated per price level (1, 5, 10, 25, 50, 100, 250, 500, 1000; default 1).

type GetLedgersService

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

GetLedgersService returns the account's ledger entries with pagination.

func (*GetLedgersService) Do

func (*GetLedgersService) SetAsset

func (s *GetLedgersService) SetAsset(assets ...string) *GetLedgersService

SetAsset filters by asset(s) (comma-separated, default all).

func (*GetLedgersService) SetAssetClass

func (s *GetLedgersService) SetAssetClass(aclass string) *GetLedgersService

SetAssetClass filters by asset class (default currency).

func (*GetLedgersService) SetEnd

func (s *GetLedgersService) SetEnd(end string) *GetLedgersService

SetEnd sets the ending unix timestamp or ledger id (inclusive).

func (*GetLedgersService) SetOffset

func (s *GetLedgersService) SetOffset(ofs int) *GetLedgersService

SetOffset sets the result offset for pagination.

func (*GetLedgersService) SetStart

func (s *GetLedgersService) SetStart(start string) *GetLedgersService

SetStart sets the starting unix timestamp or ledger id (exclusive).

func (*GetLedgersService) SetType

func (s *GetLedgersService) SetType(ledgerType string) *GetLedgersService

SetType filters by ledger entry type (all, deposit, withdrawal, trade, margin, rollover, credit, transfer, settled, staking, sale, ...).

func (*GetLedgersService) SetWithoutCount

func (s *GetLedgersService) SetWithoutCount(withoutCount bool) *GetLedgersService

SetWithoutCount skips the count calculation to improve speed.

type GetOHLCDataService

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

GetOHLCDataService returns OHLC candle data for a pair, plus a cursor (Last) to fetch incremental updates via SetSince.

func (*GetOHLCDataService) Do

func (*GetOHLCDataService) SetInterval

func (s *GetOHLCDataService) SetInterval(interval Interval) *GetOHLCDataService

SetInterval sets the candle interval (default Interval1m).

func (*GetOHLCDataService) SetSince

SetSince returns only committed candles at or after t (use a prior result's Last for incremental polling).

type GetOpenOrdersService

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

GetOpenOrdersService returns the account's open orders.

func (*GetOpenOrdersService) Do

func (*GetOpenOrdersService) SetClientOrderID

func (s *GetOpenOrdersService) SetClientOrderID(clOrdID string) *GetOpenOrdersService

SetClientOrderID filters by client order id.

func (*GetOpenOrdersService) SetTrades

func (s *GetOpenOrdersService) SetTrades(trades bool) *GetOpenOrdersService

SetTrades includes related trade ids in the output.

func (*GetOpenOrdersService) SetUserRef

func (s *GetOpenOrdersService) SetUserRef(userRef int) *GetOpenOrdersService

SetUserRef filters by user reference id.

type GetOpenPositionsService

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

GetOpenPositionsService returns the account's open margin positions.

func (*GetOpenPositionsService) Do

func (*GetOpenPositionsService) SetConsolidation

func (s *GetOpenPositionsService) SetConsolidation(consolidation string) *GetOpenPositionsService

SetConsolidation consolidates positions by market/pair (value: "market").

func (*GetOpenPositionsService) SetDoCalcs

func (s *GetOpenPositionsService) SetDoCalcs(doCalcs bool) *GetOpenPositionsService

SetDoCalcs includes profit/loss calculations (value and net).

func (*GetOpenPositionsService) SetTxID

SetTxID limits output to specific position tx ids (comma-separated).

type GetOrderAmendsService

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

GetOrderAmendsService returns the amendment history of a single order.

func (*GetOrderAmendsService) Do

type GetOrderBookService

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

GetOrderBookService returns the order book (asks and bids) for one pair.

func (*GetOrderBookService) Do

func (*GetOrderBookService) SetCount

func (s *GetOrderBookService) SetCount(count int) *GetOrderBookService

SetCount caps the number of asks/bids returned (1-500, default 100).

type GetPostTradeDataService

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

GetPostTradeDataService returns executed-trade (post-trade transparency) data. With no filters it returns the most recent trades across all pairs.

func (*GetPostTradeDataService) Do

func (*GetPostTradeDataService) SetCount

SetCount caps the number of trades returned (1-1000, default 1000).

func (*GetPostTradeDataService) SetFromTime

SetFromTime returns trades at or after t.

func (*GetPostTradeDataService) SetSymbol

SetSymbol filters to one currency pair (e.g. "BTC/USD").

func (*GetPostTradeDataService) SetToTime

SetToTime returns trades at or before t.

type GetPreTradeDataService

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

GetPreTradeDataService returns the top aggregated order-book levels (pre-trade transparency) for a symbol.

func (*GetPreTradeDataService) Do

type GetRecentSpreadsService

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

GetRecentSpreadsService returns recent bid/ask spreads for a pair plus a cursor (Last) for incremental polling via SetSince.

func (*GetRecentSpreadsService) Do

func (*GetRecentSpreadsService) SetSince

SetSince returns spreads at or after t (use a prior result's Last).

type GetRecentTradesService

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

GetRecentTradesService returns recent trades for a pair plus a nanosecond cursor (Last) to fetch newer trades via SetSince.

func (*GetRecentTradesService) Do

func (*GetRecentTradesService) SetCount

SetCount caps the number of trades returned (1-1000, default 1000).

func (*GetRecentTradesService) SetSince

SetSince returns trades after the given cursor (a prior result's Last, a nanosecond timestamp string).

type GetServerTimeService

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

GetServerTimeService returns Kraken's current server time. Useful as an unauthenticated connectivity/latency probe.

func (*GetServerTimeService) Do

type GetSystemStatusService

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

GetSystemStatusService returns the current trading-system status (online, maintenance, cancel_only, post_only).

func (*GetSystemStatusService) Do

type GetTickerService

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

GetTickerService returns 24h ticker data, keyed by Kraken pair name. Note the values are calculated within the last 24 hours.

func (*GetTickerService) Do

func (s *GetTickerService) Do(ctx context.Context) (map[string]Ticker, error)

func (*GetTickerService) SetPair

func (s *GetTickerService) SetPair(pairs ...string) *GetTickerService

SetPair filters to specific pairs (comma-separated). When omitted, ticker for all pairs is returned.

type GetTradableAssetPairsService

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

GetTradableAssetPairsService returns tradable asset pair info, keyed by Kraken pair name (e.g. "XXBTZUSD").

func (*GetTradableAssetPairsService) Do

func (*GetTradableAssetPairsService) SetCountryCode

SetCountryCode filters to pairs tradable from the given ISO 3166-1 alpha-2 (optionally region-suffixed) country code.

func (*GetTradableAssetPairsService) SetInfo

SetInfo selects the field subset to return (default AssetPairsInfoAll).

func (*GetTradableAssetPairsService) SetPair

SetPair filters to specific pairs (comma-separated, e.g. "XBTUSD,ETHUSD").

type GetTradeBalanceService

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

GetTradeBalanceService returns a summary of collateral balances, margin position valuations, equity and margin level.

func (*GetTradeBalanceService) Do

func (*GetTradeBalanceService) SetAsset

SetAsset sets the base asset used to determine the balance (default ZUSD).

type GetTradeVolumeService

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

GetTradeVolumeService returns the account's 30-day USD trade volume and the resulting fee schedule.

func (*GetTradeVolumeService) Do

func (*GetTradeVolumeService) SetPair

func (s *GetTradeVolumeService) SetPair(pairs ...string) *GetTradeVolumeService

SetPair returns fee info for the given pair(s) (comma-separated).

type GetTradesHistoryService

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

GetTradesHistoryService returns the account's trade history with pagination.

func (*GetTradesHistoryService) Do

func (*GetTradesHistoryService) SetConsolidateTaker

func (s *GetTradesHistoryService) SetConsolidateTaker(consolidate bool) *GetTradesHistoryService

SetConsolidateTaker consolidates trades by individual taker trades.

func (*GetTradesHistoryService) SetEnd

SetEnd sets the ending unix timestamp or trade tx id (inclusive).

func (*GetTradesHistoryService) SetLedgers

func (s *GetTradesHistoryService) SetLedgers(ledgers bool) *GetTradesHistoryService

SetLedgers includes related ledger ids for each trade.

func (*GetTradesHistoryService) SetOffset

SetOffset sets the result offset for pagination.

func (*GetTradesHistoryService) SetStart

SetStart sets the starting unix timestamp or trade tx id (exclusive).

func (*GetTradesHistoryService) SetTrades

SetTrades includes trades related to a position in the output.

func (*GetTradesHistoryService) SetType

SetType filters by trade type (all, any position, closed position, closing position, no position).

func (*GetTradesHistoryService) SetWithoutCount

func (s *GetTradesHistoryService) SetWithoutCount(withoutCount bool) *GetTradesHistoryService

SetWithoutCount skips the count calculation to improve speed.

type GetWebSocketsTokenService

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

GetWebSocketsTokenService issues a single-use authentication token for connecting to Kraken's private WebSocket API. The token must be used within 15 minutes of creation; once a successful WebSocket connection is established it remains valid for the life of that connection.

func (*GetWebSocketsTokenService) Do

type GetWithdrawAddressesService

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

GetWithdrawAddressesService lists the withdrawal addresses set up on the account.

func (*GetWithdrawAddressesService) Do

func (*GetWithdrawAddressesService) SetAsset

SetAsset filters by asset.

func (*GetWithdrawAddressesService) SetAssetClass

SetAssetClass filters by asset class (default currency).

func (*GetWithdrawAddressesService) SetKey

SetKey filters by withdrawal key name.

func (*GetWithdrawAddressesService) SetMethod

SetMethod filters by withdrawal method.

func (*GetWithdrawAddressesService) SetVerified

SetVerified filters by whether the address is verified.

type GetWithdrawInfoService

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

GetWithdrawInfoService returns fee and limit information for a prospective withdrawal, without performing it.

func (*GetWithdrawInfoService) Do

type GetWithdrawMethodsService

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

GetWithdrawMethodsService lists the withdrawal methods available to the user.

func (*GetWithdrawMethodsService) Do

func (*GetWithdrawMethodsService) SetAsset

SetAsset filters by asset.

func (*GetWithdrawMethodsService) SetAssetClass

SetAssetClass filters by asset class (default currency).

func (*GetWithdrawMethodsService) SetNetwork

SetNetwork filters by network name.

type GetWithdrawStatusService

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

GetWithdrawStatusService lists recent withdrawals.

func (*GetWithdrawStatusService) Do

func (*GetWithdrawStatusService) SetAsset

SetAsset filters by asset.

func (*GetWithdrawStatusService) SetAssetClass

func (s *GetWithdrawStatusService) SetAssetClass(aclass string) *GetWithdrawStatusService

SetAssetClass filters by asset class (default currency).

func (*GetWithdrawStatusService) SetMethod

SetMethod filters by withdrawal method.

type GroupedLevel

type GroupedLevel struct {
	Price decimal.Decimal `json:"price"` // grouped price level
	Qty   decimal.Decimal `json:"qty"`   // aggregated quantity at the level
}

GroupedLevel is one aggregated price level.

type GroupedOrderBook

type GroupedOrderBook struct {
	Pair     string         `json:"pair"`     // canonical pair name
	Grouping int            `json:"grouping"` // tick grouping applied
	Asks     []GroupedLevel `json:"asks"`     // aggregated ask levels
	Bids     []GroupedLevel `json:"bids"`     // aggregated bid levels
}

GroupedOrderBook is the aggregated order book for one pair.

type Interval

type Interval int

Interval is an OHLC candle interval in minutes.

const (
	Interval1m  Interval = 1
	Interval5m  Interval = 5
	Interval15m Interval = 15
	Interval30m Interval = 30
	Interval1h  Interval = 60
	Interval4h  Interval = 240
	Interval1d  Interval = 1440
	Interval1w  Interval = 10080
	Interval15d Interval = 21600
)

type L3Entry

type L3Entry struct {
	OrderID   string          `json:"order_id"`  // order identifier
	Price     decimal.Decimal `json:"price"`     // limit price
	Qty       decimal.Decimal `json:"qty"`       // remaining quantity
	Timestamp NanoTime        `json:"timestamp"` // order timestamp (UNIX nanoseconds)
}

L3Entry is one resting order in the level-3 book.

type L3OrderBook

type L3OrderBook struct {
	Pair string    `json:"pair"` // canonical pair name
	Asks []L3Entry `json:"asks"` // individual ask orders
	Bids []L3Entry `json:"bids"` // individual bid orders
}

L3OrderBook is the per-order (level 3) order book for one pair.

type LedgerEntry

type LedgerEntry struct {
	RefID      string          `json:"refid"`   // reference id
	Time       time.Time       `json:"time"`    // time of ledger entry
	Type       string          `json:"type"`    // deposit, withdrawal, trade, margin, rollover, ...
	SubType    string          `json:"subtype"` // additional info on the type
	AssetClass string          `json:"aclass"`  // asset class
	Asset      string          `json:"asset"`   // asset
	Amount     decimal.Decimal `json:"amount"`  // transaction amount (signed)
	Fee        decimal.Decimal `json:"fee"`     // transaction fee
	Balance    decimal.Decimal `json:"balance"` // resulting balance
}

LedgerEntry is one ledger record.

type LedgersResult

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

LedgersResult holds the ledger map plus the total count.

type ListEarnAllocationsService

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

ListEarnAllocationsService lists the account's current Earn allocations.

func (*ListEarnAllocationsService) Do

func (*ListEarnAllocationsService) SetAscending

func (s *ListEarnAllocationsService) SetAscending(ascending bool) *ListEarnAllocationsService

SetAscending returns allocations in ascending order.

func (*ListEarnAllocationsService) SetConvertedAsset

func (s *ListEarnAllocationsService) SetConvertedAsset(asset string) *ListEarnAllocationsService

SetConvertedAsset values allocations in the given asset (default USD).

func (*ListEarnAllocationsService) SetHideZeroAllocations

func (s *ListEarnAllocationsService) SetHideZeroAllocations(hide bool) *ListEarnAllocationsService

SetHideZeroAllocations omits strategies with no current allocation.

type ListEarnStrategiesService

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

ListEarnStrategiesService lists the Earn strategies available to the account.

func (*ListEarnStrategiesService) Do

func (*ListEarnStrategiesService) SetAscending

func (s *ListEarnStrategiesService) SetAscending(ascending bool) *ListEarnStrategiesService

SetAscending returns strategies in ascending order.

func (*ListEarnStrategiesService) SetAsset

SetAsset filters strategies by asset.

func (*ListEarnStrategiesService) SetCursor

SetCursor sets the pagination cursor.

func (*ListEarnStrategiesService) SetLimit

SetLimit caps the number of strategies returned.

func (*ListEarnStrategiesService) SetLockType

func (s *ListEarnStrategiesService) SetLockType(lockTypes ...string) *ListEarnStrategiesService

SetLockType filters by lock type(s) (flex, bonded, timed, instant).

type MethodLimit

type MethodLimit struct {
	HasLimit bool            // whether a limit applies
	Amount   decimal.Decimal // the limit amount, when HasLimit and a number was returned
}

MethodLimit is the "limit" field of a deposit/withdrawal method: Kraken encodes it as either the boolean false (no limit) or a maximum amount. It is a small union type so a plain field can decode both forms.

func (MethodLimit) MarshalJSON

func (m MethodLimit) MarshalJSON() ([]byte, error)

func (*MethodLimit) UnmarshalJSON

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

type NanoTime

type NanoTime time.Time

NanoTime is a timestamp Kraken encodes as UNIX *nanoseconds* — used by a few newer endpoints (e.g. order amends) — as opposed to the UNIX seconds used by the rest of the API and handled by the global time.Time codec. It is a distinct type so the seconds-based codec does not misread it.

func (NanoTime) MarshalJSON

func (t NanoTime) MarshalJSON() ([]byte, error)

func (NanoTime) Time

func (t NanoTime) Time() time.Time

Time returns the timestamp as a standard time.Time.

func (*NanoTime) UnmarshalJSON

func (t *NanoTime) UnmarshalJSON(data []byte) error

type OHLCResult

type OHLCResult struct {
	Pair    string    // Kraken pair name the candles belong to
	Candles []Candle  // committed candles, oldest first
	Last    time.Time // cursor: id of the last candle, pass to SetSince to poll
}

OHLCResult holds the candles for one pair plus the pagination cursor.

func (OHLCResult) MarshalJSON

func (r OHLCResult) MarshalJSON() ([]byte, error)

func (*OHLCResult) UnmarshalJSON

func (r *OHLCResult) UnmarshalJSON(data []byte) error

type OpenOrdersResult

type OpenOrdersResult struct {
	Open map[string]OrderInfo `json:"open"`
}

OpenOrdersResult holds the open-orders map keyed by order tx id.

type OrderAmend

type OrderAmend struct {
	AmendID      string          `json:"amend_id"`      // amendment identifier
	AmendType    string          `json:"amend_type"`    // original, user, or restated
	OrderQty     decimal.Decimal `json:"order_qty"`     // order quantity (base asset)
	DisplayQty   decimal.Decimal `json:"display_qty"`   // quantity shown in book for iceberg orders
	RemainingQty decimal.Decimal `json:"remaining_qty"` // remaining un-traded quantity
	LimitPrice   decimal.Decimal `json:"limit_price"`   // limit price restriction
	TriggerPrice decimal.Decimal `json:"trigger_price"` // trigger price on trigger order types
	Reason       string          `json:"reason"`        // reason for this amend
	PostOnly     bool            `json:"post_only"`     // whether restricted from taking liquidity
	Timestamp    NanoTime        `json:"timestamp"`     // amendment time (UNIX nanoseconds)
}

OrderAmend is one amendment record.

type OrderAmendsResult

type OrderAmendsResult struct {
	Count  int          `json:"count"`  // total count incl. the original order
	Amends []OrderAmend `json:"amends"` // amendment records
}

OrderAmendsResult holds the amendment history of an order.

type OrderBook

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

OrderBook is the raw asks/bids object Kraken returns under the pair key.

type OrderBookResult

type OrderBookResult struct {
	Pair string
	Asks []BookEntry
	Bids []BookEntry
}

OrderBookResult is the order book for one pair, flattened with its name.

type OrderDescr

type OrderDescr struct {
	Order string `json:"order"` // order description
	Close string `json:"close"` // conditional close order description, if any
}

OrderDescr is the human-readable description returned for a placed order.

type OrderDescription

type OrderDescription struct {
	Pair       string          `json:"pair"`      // asset pair
	Type       string          `json:"type"`      // buy or sell
	OrderType  string          `json:"ordertype"` // market, limit, stop-loss, take-profit, ...
	Price      decimal.Decimal `json:"price"`     // primary price
	Price2     decimal.Decimal `json:"price2"`    // secondary price
	Leverage   string          `json:"leverage"`  // amount of leverage (e.g. "none", "5:1")
	Order      string          `json:"order"`     // order description
	Close      string          `json:"close"`     // conditional close order description, if any
	AssetClass string          `json:"aclass"`    // asset class of the pair
}

OrderDescription is the human-readable description of an order's parameters.

type OrderInfo

type OrderInfo struct {
	RefID          string           `json:"refid"`         // referral order tx id that created this order (nullable)
	UserRef        int64            `json:"userref"`       // optional client identifier (nullable)
	ClientOrderID  string           `json:"cl_ord_id"`     // optional alphanumeric client identifier (nullable)
	Status         string           `json:"status"`        // pending, open, closed, canceled, expired
	Reason         string           `json:"reason"`        // reason order was closed/canceled (nullable)
	OpenTime       time.Time        `json:"opentm"`        // time order was placed
	StartTime      time.Time        `json:"starttm"`       // order start time (0 if not set)
	ExpireTime     time.Time        `json:"expiretm"`      // order end time (0 if not set)
	CloseTime      time.Time        `json:"closetm"`       // time order was closed (ClosedOrders/QueryOrders)
	Description    OrderDescription `json:"descr"`         // order description
	Volume         decimal.Decimal  `json:"vol"`           // order volume (base currency)
	VolumeExecuted decimal.Decimal  `json:"vol_exec"`      // volume executed (base currency)
	Cost           decimal.Decimal  `json:"cost"`          // total cost (quote currency)
	Fee            decimal.Decimal  `json:"fee"`           // total fee (quote currency)
	Price          decimal.Decimal  `json:"price"`         // average price (quote currency)
	StopPrice      decimal.Decimal  `json:"stopprice"`     // stop price (quote currency)
	LimitPrice     decimal.Decimal  `json:"limitprice"`    // triggered limit price (quote currency)
	Trigger        string           `json:"trigger"`       // price signal for stop/take-profit: last or index
	Margin         bool             `json:"margin"`        // whether order is funded on margin
	Misc           string           `json:"misc"`          // comma-delimited misc info (stopped, touched, ...)
	SenderSubID    string           `json:"sender_sub_id"` // underlying sub-account for STP (nullable)
	OrderFlags     string           `json:"oflags"`        // comma-delimited order flags (post, fcib, fciq, ...)
	TimeInForce    string           `json:"time_in_force"` // gtc, ioc, gtd, fok
	Trades         []string         `json:"trades"`        // related trade ids (if requested and available)
}

OrderInfo is the full state of an order, shared by OpenOrders, ClosedOrders and QueryOrders. Optional fields (closetm, reason, margin, trigger, sender_sub_id, trades) appear only in the relevant context.

type OrderSide

type OrderSide string

OrderSide is the direction of an order.

const (
	OrderSideBuy  OrderSide = "buy"
	OrderSideSell OrderSide = "sell"
)

type OrderType

type OrderType string

OrderType is the execution model of an order.

const (
	OrderTypeMarket            OrderType = "market"
	OrderTypeLimit             OrderType = "limit"
	OrderTypeIceberg           OrderType = "iceberg"
	OrderTypeStopLoss          OrderType = "stop-loss"
	OrderTypeTakeProfit        OrderType = "take-profit"
	OrderTypeStopLossLimit     OrderType = "stop-loss-limit"
	OrderTypeTakeProfitLimit   OrderType = "take-profit-limit"
	OrderTypeTrailingStop      OrderType = "trailing-stop"
	OrderTypeTrailingStopLimit OrderType = "trailing-stop-limit"
	OrderTypeSettlePosition    OrderType = "settle-position"
)

type PositionInfo

type PositionInfo struct {
	OrderTxID      string          `json:"ordertxid"`  // order id responsible for the position
	AssetClass     string          `json:"class"`      // asset class of the position
	PositionStatus string          `json:"posstatus"`  // position status (open)
	Pair           string          `json:"pair"`       // asset pair
	Time           time.Time       `json:"time"`       // time the position was opened
	Type           string          `json:"type"`       // buy or sell (direction)
	OrderType      string          `json:"ordertype"`  // order type used to open
	Cost           decimal.Decimal `json:"cost"`       // opening cost (quote currency)
	Fee            decimal.Decimal `json:"fee"`        // opening fee (quote currency)
	Volume         decimal.Decimal `json:"vol"`        // opening size (base currency)
	VolumeClosed   decimal.Decimal `json:"vol_closed"` // quantity closed (base currency)
	Margin         decimal.Decimal `json:"margin"`     // initial margin consumed (quote currency)
	Value          decimal.Decimal `json:"value"`      // current value (if docalcs)
	Net            decimal.Decimal `json:"net"`        // unrealized P&L of remaining position (if docalcs)
	Terms          string          `json:"terms"`      // funding cost and term of position
	RolloverTime   time.Time       `json:"rollovertm"` // timestamp of next margin rollover fee
	Misc           string          `json:"misc"`       // comma-delimited additional info
	OrderFlags     string          `json:"oflags"`     // comma-delimited opening order flags
}

PositionInfo is one open margin position.

type PostTrade

type PostTrade struct {
	TradeID           string          `json:"trade_id"`             // trade identifier
	Symbol            string          `json:"symbol"`               // currency pair symbol
	Description       string          `json:"description"`          // human-readable description
	Price             decimal.Decimal `json:"price"`                // execution price
	Quantity          decimal.Decimal `json:"quantity"`             // executed quantity
	BaseAsset         string          `json:"base_asset"`           // base asset
	BaseDTICode       string          `json:"base_dti_code"`        // base Digital Token Identifier
	BaseDTIShortName  string          `json:"base_dti_short_name"`  // base DTI short name
	BaseNotation      string          `json:"base_notation"`        // base quantity notation
	QuoteAsset        string          `json:"quote_asset"`          // quote asset
	QuoteDTICode      string          `json:"quote_dti_code"`       // quote Digital Token Identifier
	QuoteDTIShortName string          `json:"quote_dti_short_name"` // quote DTI short name
	QuoteNotation     string          `json:"quote_notation"`       // quote notation (e.g. MONE)
	TradeVenue        string          `json:"trade_venue"`          // execution venue (MIC)
	TradeTime         time.Time       `json:"trade_ts"`             // execution time
	PublicationVenue  string          `json:"publication_venue"`    // publication venue (MIC)
	PublicationTime   time.Time       `json:"publication_ts"`       // data publication time
}

PostTrade is one executed-trade transparency record.

type PostTradeData

type PostTradeData struct {
	Count    int         `json:"count"`   // number of trades returned
	LastTime time.Time   `json:"last_ts"` // timestamp of the last trade in the page
	Trades   []PostTrade `json:"trades"`  // executed trades
}

PostTradeData is a page of executed-trade transparency records.

type PreTradeData

type PreTradeData struct {
	Symbol            string          `json:"symbol"`               // currency pair symbol
	Description       string          `json:"description"`          // human-readable description
	BaseAsset         string          `json:"base_asset"`           // base asset
	BaseDTICode       string          `json:"base_dti_code"`        // base Digital Token Identifier
	BaseDTIShortName  string          `json:"base_dti_short_name"`  // base DTI short name
	BaseNotation      string          `json:"base_notation"`        // base quantity notation
	QuoteAsset        string          `json:"quote_asset"`          // quote asset
	QuoteDTICode      string          `json:"quote_dti_code"`       // quote Digital Token Identifier
	QuoteDTIShortName string          `json:"quote_dti_short_name"` // quote DTI short name
	QuoteNotation     string          `json:"quote_notation"`       // quote notation (e.g. MONE)
	Venue             string          `json:"venue"`                // market identifier code (MIC)
	System            string          `json:"system"`               // trading system (e.g. CLOB)
	Asks              []PreTradeLevel `json:"asks"`                 // aggregated ask levels
	Bids              []PreTradeLevel `json:"bids"`                 // aggregated bid levels
}

PreTradeData is the aggregated order book for one symbol with instrument reference data.

type PreTradeLevel

type PreTradeLevel struct {
	Side            string          `json:"side"`           // BUY or SELL
	Price           decimal.Decimal `json:"price"`          // price level
	Qty             decimal.Decimal `json:"qty"`            // aggregated quantity
	Count           int             `json:"count"`          // number of orders aggregated
	SubmissionTime  time.Time       `json:"submission_ts"`  // order submission time
	PublicationTime time.Time       `json:"publication_ts"` // data publication time
}

PreTradeLevel is one aggregated transparency order-book level.

type QueryL3OrderBookService

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

QueryL3OrderBookService returns the level-3 (per-order) order book for a pair. Despite being market data, it is an authenticated endpoint.

func (*QueryL3OrderBookService) Do

func (*QueryL3OrderBookService) SetCount

SetCount caps the number of orders returned per side.

type QueryLedgersService

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

QueryLedgersService returns full information for specific ledger entries by id.

func (*QueryLedgersService) Do

func (*QueryLedgersService) SetTrades

func (s *QueryLedgersService) SetTrades(trades bool) *QueryLedgersService

SetTrades includes related trade info in the output.

type QueryOrdersService

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

QueryOrdersService returns full information for specific orders by tx id.

func (*QueryOrdersService) Do

func (*QueryOrdersService) SetConsolidateTaker

func (s *QueryOrdersService) SetConsolidateTaker(consolidate bool) *QueryOrdersService

SetConsolidateTaker consolidates trades by individual taker trades.

func (*QueryOrdersService) SetTrades

func (s *QueryOrdersService) SetTrades(trades bool) *QueryOrdersService

SetTrades includes related trade ids in the output.

func (*QueryOrdersService) SetUserRef

func (s *QueryOrdersService) SetUserRef(userRef int) *QueryOrdersService

SetUserRef restricts results to the given user reference id.

type QueryTradesService

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

QueryTradesService returns full information for specific trades by tx id.

func (*QueryTradesService) Do

func (*QueryTradesService) SetTrades

func (s *QueryTradesService) SetTrades(trades bool) *QueryTradesService

SetTrades includes trades related to a position in the output.

type ReportType

type ReportType string

ReportType is the kind of data export to generate.

const (
	ReportTypeTrades  ReportType = "trades"
	ReportTypeLedgers ReportType = "ledgers"
)

type RequestExportReportService

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

RequestExportReportService requests generation of a trades/ledgers export report and returns its id.

func (*RequestExportReportService) Do

func (*RequestExportReportService) SetEndTime

SetEndTime sets the report data end time.

func (*RequestExportReportService) SetFields

SetFields sets the comma-delimited fields to include (default all).

func (*RequestExportReportService) SetFormat

SetFormat sets the file format (CSV or TSV; default CSV).

func (*RequestExportReportService) SetStartTime

SetStartTime sets the report data start time.

type RetrieveDataExportService

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

RetrieveDataExportService downloads a processed export report. The response is a binary ZIP archive, returned as raw bytes (not the usual JSON envelope).

func (*RetrieveDataExportService) Do

Do returns the raw ZIP archive bytes. If the API instead returns a JSON error envelope (e.g. an unknown id), that error is surfaced.

type SelfTradePrevention

type SelfTradePrevention string

SelfTradePrevention selects how self-trades are prevented (stptype).

const (
	SelfTradePreventionCancelNewest SelfTradePrevention = "cancel-newest"
	SelfTradePreventionCancelOldest SelfTradePrevention = "cancel-oldest"
	SelfTradePreventionCancelBoth   SelfTradePrevention = "cancel-both"
)

type ServerTime

type ServerTime struct {
	UnixTime time.Time `json:"unixtime"` // server time as unix seconds
	RFC1123  string    `json:"rfc1123"`  // server time as an RFC 1123 string
}

ServerTime is the GET /0/public/Time payload.

type Spread

type Spread struct {
	Time time.Time       // sample time
	Bid  decimal.Decimal // best bid price
	Ask  decimal.Decimal // best ask price
}

Spread is one bid/ask spread sample: [time, bid, ask].

func (Spread) MarshalJSON

func (s Spread) MarshalJSON() ([]byte, error)

func (*Spread) UnmarshalJSON

func (s *Spread) UnmarshalJSON(data []byte) error

type SpreadResult

type SpreadResult struct {
	Pair    string    // Kraken pair name the spreads belong to
	Spreads []Spread  // recent spreads, oldest first
	Last    time.Time // cursor; pass to SetSince to poll for newer spreads
}

SpreadResult holds recent spreads for one pair plus the pagination cursor.

func (SpreadResult) MarshalJSON

func (r SpreadResult) MarshalJSON() ([]byte, error)

func (*SpreadResult) UnmarshalJSON

func (r *SpreadResult) UnmarshalJSON(data []byte) error

type SubscribeBalancesService

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

SubscribeBalancesService subscribes to the private "balances" channel, which streams account balance snapshots and ledger-driven updates.

func (*SubscribeBalancesService) Do

func (s *SubscribeBalancesService) Do(ctx context.Context, cb func(*WsPush[[]WsBalance], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeBalancesService) SetSnapshot

func (s *SubscribeBalancesService) SetSnapshot(snapshot bool) *SubscribeBalancesService

SetSnapshot controls whether an initial balance snapshot is sent on subscribe.

type SubscribeBookService

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

SubscribeBookService subscribes to the public "book" (level 2) channel.

func (*SubscribeBookService) Do

func (s *SubscribeBookService) Do(ctx context.Context, cb func(*WsPush[[]WsBook], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeBookService) SetDepth

func (s *SubscribeBookService) SetDepth(depth int) *SubscribeBookService

SetDepth sets the book depth per side (10, 25, 100, 500, 1000; default 10).

func (*SubscribeBookService) SetSnapshot

func (s *SubscribeBookService) SetSnapshot(snapshot bool) *SubscribeBookService

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SubscribeExecutionsService

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

SubscribeExecutionsService subscribes to the private "executions" channel, which streams order lifecycle events and trade fills.

func (*SubscribeExecutionsService) Do

func (s *SubscribeExecutionsService) Do(ctx context.Context, cb func(*WsPush[[]WsExecution], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeExecutionsService) SetOrderStatus

func (s *SubscribeExecutionsService) SetOrderStatus(enabled bool) *SubscribeExecutionsService

SetOrderStatus controls whether full order-status detail is included.

func (*SubscribeExecutionsService) SetRateCounter

func (s *SubscribeExecutionsService) SetRateCounter(enabled bool) *SubscribeExecutionsService

SetRateCounter includes API rate-limit counter info in updates.

func (*SubscribeExecutionsService) SetSnapOrders

SetSnapOrders includes a snapshot of open orders on subscribe.

func (*SubscribeExecutionsService) SetSnapTrades

SetSnapTrades includes a snapshot of recent trades on subscribe.

type SubscribeInstrumentService

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

SubscribeInstrumentService subscribes to the public "instrument" channel, which streams reference data for all assets and tradable pairs.

func (*SubscribeInstrumentService) Do

func (s *SubscribeInstrumentService) Do(ctx context.Context, cb func(*WsPush[WsInstrument], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeInstrumentService) SetSnapshot

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SubscribeLevel3Service

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

SubscribeLevel3Service subscribes to the private "level3" (per-order) order book channel. It requires authentication.

func (*SubscribeLevel3Service) Do

func (s *SubscribeLevel3Service) Do(ctx context.Context, cb func(*WsPush[[]WsLevel3], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeLevel3Service) SetDepth

SetDepth sets the number of orders per side (10, 100, 1000; default 10).

func (*SubscribeLevel3Service) SetSnapshot

func (s *SubscribeLevel3Service) SetSnapshot(snapshot bool) *SubscribeLevel3Service

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SubscribeOHLCService

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

SubscribeOHLCService subscribes to the public "ohlc" candlestick channel.

func (*SubscribeOHLCService) Do

func (s *SubscribeOHLCService) Do(ctx context.Context, cb func(*WsPush[[]WsOHLC], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeOHLCService) SetSnapshot

func (s *SubscribeOHLCService) SetSnapshot(snapshot bool) *SubscribeOHLCService

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SubscribeTickerService

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

SubscribeTickerService subscribes to the public "ticker" channel for one or more symbols (e.g. "BTC/USD").

func (*SubscribeTickerService) Do

func (s *SubscribeTickerService) Do(ctx context.Context, cb func(*WsPush[[]WsTicker], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeTickerService) SetEventTrigger

func (s *SubscribeTickerService) SetEventTrigger(trigger string) *SubscribeTickerService

SetEventTrigger selects the update trigger: "trades" (default, push on every trade) or "bbo" (push only when the best bid/offer changes).

func (*SubscribeTickerService) SetSnapshot

func (s *SubscribeTickerService) SetSnapshot(snapshot bool) *SubscribeTickerService

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SubscribeTradeService

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

SubscribeTradeService subscribes to the public "trade" channel.

func (*SubscribeTradeService) Do

func (s *SubscribeTradeService) Do(ctx context.Context, cb func(*WsPush[[]WsTrade], error)) (chan<- struct{}, <-chan struct{}, error)

func (*SubscribeTradeService) SetSnapshot

func (s *SubscribeTradeService) SetSnapshot(snapshot bool) *SubscribeTradeService

SetSnapshot controls whether an initial snapshot is sent on subscribe.

type SystemStatus

type SystemStatus struct {
	Status    string    `json:"status"`    // online | maintenance | cancel_only | post_only
	Timestamp time.Time `json:"timestamp"` // RFC3339 time the status was last updated
}

SystemStatus is the GET /0/public/SystemStatus payload.

type Ticker

type Ticker struct {
	Ask       TickerLevel       `json:"a"` // ask [price, wholeLotVolume, lotVolume]
	Bid       TickerLevel       `json:"b"` // bid [price, wholeLotVolume, lotVolume]
	Last      TickerLastTrade   `json:"c"` // last trade closed [price, lotVolume]
	Volume    TickerWindow      `json:"v"` // volume [today, last24Hours]
	VWAP      TickerWindow      `json:"p"` // volume weighted average price [today, last24Hours]
	Trades    TickerCountWindow `json:"t"` // number of trades [today, last24Hours]
	Low       TickerWindow      `json:"l"` // low [today, last24Hours]
	High      TickerWindow      `json:"h"` // high [today, last24Hours]
	OpenPrice decimal.Decimal   `json:"o"` // today's opening price
}

Ticker is one pair's 24h ticker snapshot.

type TickerCountWindow

type TickerCountWindow struct {
	Today       int64
	Last24Hours int64
}

TickerCountWindow holds a [today, last24Hours] pair of trade counts.

func (TickerCountWindow) MarshalJSON

func (t TickerCountWindow) MarshalJSON() ([]byte, error)

func (*TickerCountWindow) UnmarshalJSON

func (t *TickerCountWindow) UnmarshalJSON(data []byte) error

type TickerLastTrade

type TickerLastTrade struct {
	Price     decimal.Decimal
	LotVolume decimal.Decimal
}

TickerLastTrade is the last-trade-closed level: [price, lotVolume].

func (TickerLastTrade) MarshalJSON

func (t TickerLastTrade) MarshalJSON() ([]byte, error)

func (*TickerLastTrade) UnmarshalJSON

func (t *TickerLastTrade) UnmarshalJSON(data []byte) error

type TickerLevel

type TickerLevel struct {
	Price          decimal.Decimal
	WholeLotVolume decimal.Decimal
	LotVolume      decimal.Decimal
}

TickerLevel is an ask/bid level: [price, wholeLotVolume, lotVolume].

func (TickerLevel) MarshalJSON

func (t TickerLevel) MarshalJSON() ([]byte, error)

func (*TickerLevel) UnmarshalJSON

func (t *TickerLevel) UnmarshalJSON(data []byte) error

type TickerWindow

type TickerWindow struct {
	Today       decimal.Decimal
	Last24Hours decimal.Decimal
}

TickerWindow holds a [today, last24Hours] pair of decimal values.

func (TickerWindow) MarshalJSON

func (t TickerWindow) MarshalJSON() ([]byte, error)

func (*TickerWindow) UnmarshalJSON

func (t *TickerWindow) UnmarshalJSON(data []byte) error

type TimeInForce

type TimeInForce string

TimeInForce controls how long an order remains active.

const (
	TimeInForceGTC TimeInForce = "GTC" // good till canceled
	TimeInForceIOC TimeInForce = "IOC" // immediate or cancel
	TimeInForceGTD TimeInForce = "GTD" // good till date
	TimeInForceFOK TimeInForce = "FOK" // fill or kill
)

type Trade

type Trade struct {
	Price     decimal.Decimal // execution price
	Volume    decimal.Decimal // executed volume (base currency)
	Time      time.Time       // execution time
	Side      string          // "b" buy, "s" sell
	OrderType string          // "l" limit, "m" market
	Misc      string          // miscellaneous info
	TradeID   int64           // unique trade id
}

Trade is one public trade: [price, volume, time, side, ordertype, misc, id].

func (Trade) MarshalJSON

func (t Trade) MarshalJSON() ([]byte, error)

func (*Trade) UnmarshalJSON

func (t *Trade) UnmarshalJSON(data []byte) error

type TradeBalance

type TradeBalance struct {
	EquivalentBalance   decimal.Decimal `json:"eb"`  // combined balance of all currencies
	TradeBalance        decimal.Decimal `json:"tb"`  // combined balance of all equity currencies
	MarginOpenPositions decimal.Decimal `json:"m"`   // margin amount of open positions
	UnrealizedNetPnL    decimal.Decimal `json:"n"`   // unrealized net profit/loss of open positions
	CostBasis           decimal.Decimal `json:"c"`   // cost basis of open positions
	FloatingValuation   decimal.Decimal `json:"v"`   // current floating valuation of open positions
	Equity              decimal.Decimal `json:"e"`   // trade balance + unrealized net profit/loss
	FreeMargin          decimal.Decimal `json:"mf"`  // equity - initial margin (max margin available)
	MarginFreeForOrders decimal.Decimal `json:"mfo"` // available margin usable for new orders
	MarginLevel         decimal.Decimal `json:"ml"`  // (equity / initial margin) * 100, when positions open
	UnexecutedValue     decimal.Decimal `json:"uv"`  // value of unfilled and partially filled orders
}

TradeBalance summarizes collateral, margin and equity.

type TradeConn

type TradeConn struct {
	*request.WsTradeConn
}

TradeConn is a persistent, authenticated connection for placing and managing orders over WebSocket — a low-latency alternative to the REST trade endpoints. It is request/response: each method blocks for its matching reply.

func (*TradeConn) AddOrder

AddOrder places a new order.

func (*TradeConn) AmendOrder

AmendOrder amends an open order in place (preserving queue priority where possible).

func (*TradeConn) BatchAdd

func (t *TradeConn) BatchAdd(ctx context.Context, symbol string, orders ...WsAddOrder) (*WsTradeResponse[[]WsAddOrderResult], error)

BatchAdd places 2-15 orders for a single pair in one request.

func (*TradeConn) BatchCancel

func (t *TradeConn) BatchCancel(ctx context.Context, orderIDs ...string) (*WsTradeResponse[WsBatchCancelResult], error)

BatchCancel cancels up to 50 open orders by order id in one request. Kraken returns an (empty) result on success, so the response's Success flag — not a count — is the authoritative outcome.

func (*TradeConn) CancelAll

CancelAll cancels all open orders.

func (*TradeConn) CancelAllOrdersAfter

func (t *TradeConn) CancelAllOrdersAfter(ctx context.Context, timeout int) (*WsTradeResponse[WsCancelAllAfterResult], error)

CancelAllOrdersAfter arms (or, with timeout 0, disarms) a dead-man's switch that cancels all open orders after timeout seconds unless reset.

func (*TradeConn) CancelOrder

func (t *TradeConn) CancelOrder(ctx context.Context, orderIDs ...string) (*WsTradeResponse[WsCancelOrderResult], error)

CancelOrder cancels one or more open orders by order id.

func (*TradeConn) CancelOrderByClientID

func (t *TradeConn) CancelOrderByClientID(ctx context.Context, clOrdIDs ...string) (*WsTradeResponse[WsCancelOrderResult], error)

CancelOrderByClientID cancels one or more open orders by client order id.

func (*TradeConn) EditOrder

EditOrder cancel-replaces an existing order with new parameters.

func (*TradeConn) Trade

func (t *TradeConn) Trade(ctx context.Context, method string, params map[string]any) (*WsTradeResponse[jsonRaw], error)

Trade is the low-level escape hatch: it sends an arbitrary method with the given params (the auth token is injected automatically) and returns the raw decoded result. Prefer the typed methods below.

type TradeHistoryEntry

type TradeHistoryEntry struct {
	OrderTxID      string          `json:"ordertxid"`      // order responsible for the trade
	PositionTxID   string          `json:"postxid"`        // position responsible for the trade
	Pair           string          `json:"pair"`           // asset pair
	Time           time.Time       `json:"time"`           // time of trade
	Type           string          `json:"type"`           // buy or sell
	OrderType      string          `json:"ordertype"`      // order type
	Price          decimal.Decimal `json:"price"`          // average execution price (quote currency)
	Cost           decimal.Decimal `json:"cost"`           // total cost (quote currency)
	Fee            decimal.Decimal `json:"fee"`            // total fee (quote currency)
	Volume         decimal.Decimal `json:"vol"`            // volume (base currency)
	Margin         decimal.Decimal `json:"margin"`         // initial margin (quote currency)
	Leverage       decimal.Decimal `json:"leverage"`       // amount of leverage used
	Misc           string          `json:"misc"`           // comma-delimited misc info
	TradeID        int64           `json:"trade_id"`       // unique trade id
	Maker          bool            `json:"maker"`          // true if maker, false if taker
	AssetClass     string          `json:"aclass"`         // asset class of the traded pair
	TradeOrderType string          `json:"tradeordertype"` // actual execution order type (may differ)
	PositionStatus string          `json:"posstatus"`      // position status (only if trade opened a position)
	ClosedPrice    decimal.Decimal `json:"cprice"`         // avg price of closed portion of position
	ClosedCost     decimal.Decimal `json:"ccost"`          // total cost of closed portion of position
	ClosedFee      decimal.Decimal `json:"cfee"`           // total fee of closed portion of position
	ClosedVolume   decimal.Decimal `json:"cvol"`           // total volume of closed portion of position
	ClosedMargin   decimal.Decimal `json:"cmargin"`        // total margin freed in closed portion
	Net            decimal.Decimal `json:"net"`            // net profit/loss of closed portion
	ClosingTrades  []string        `json:"trades"`         // list of closing trades for position
	Ledgers        []string        `json:"ledgers"`        // related ledger ids (if requested)
}

TradeHistoryEntry is one trade execution, shared by TradesHistory and QueryTrades. Position-close fields (cprice, ccost, ...) appear only when the trade closed a margin position.

type TradeVolume

type TradeVolume struct {
	Currency   string             `json:"currency"`    // volume currency
	Volume     decimal.Decimal    `json:"volume"`      // current 30-day discount volume
	Fees       map[string]FeeInfo `json:"fees"`        // taker fee schedule per pair (if pair given)
	FeesMaker  map[string]FeeInfo `json:"fees_maker"`  // maker fee schedule per pair (if pair given)
	AssetClass string             `json:"asset_class"` // asset class of the volume
	Inputs     TradeVolumeInputs  `json:"inputs"`      // inputs used to compute the discount volume
}

TradeVolume is the account's fee-volume summary.

type TradeVolumeInputs

type TradeVolumeInputs struct {
	DomainAssetsOnPlatform decimal.Decimal `json:"domain_assets_on_platform"`
	DomainFuturesVolume30d decimal.Decimal `json:"domain_futures_volume_30d"`
	DomainSpotVolume30d    decimal.Decimal `json:"domain_spot_volume_30d"`
}

TradeVolumeInputs are the volume inputs used to compute the fee tier.

type TradesHistoryResult

type TradesHistoryResult struct {
	Trades map[string]TradeHistoryEntry `json:"trades"`
	Count  int                          `json:"count"`
}

TradesHistoryResult holds the trades map plus the total count.

type TradesResult

type TradesResult struct {
	Pair   string  // Kraken pair name the trades belong to
	Trades []Trade // recent trades, oldest first
	Last   string  // nanosecond cursor; pass to SetSince to fetch newer trades
}

TradesResult holds recent trades for one pair plus the pagination cursor.

func (TradesResult) MarshalJSON

func (r TradesResult) MarshalJSON() ([]byte, error)

func (*TradesResult) UnmarshalJSON

func (r *TradesResult) UnmarshalJSON(data []byte) error

type TransferStatus

type TransferStatus struct {
	Method     string          `json:"method"`      // transfer method
	AssetClass string          `json:"aclass"`      // asset class
	Asset      string          `json:"asset"`       // asset
	RefID      string          `json:"refid"`       // reference id
	TxID       string          `json:"txid"`        // on-chain transaction id
	Info       string          `json:"info"`        // address / info
	Amount     decimal.Decimal `json:"amount"`      // amount
	Fee        decimal.Decimal `json:"fee"`         // fee
	Time       time.Time       `json:"time"`        // unix timestamp of the transfer
	Status     string          `json:"status"`      // status (Success, Failure, Pending, ...)
	StatusProp string          `json:"status-prop"` // additional status property (return, onhold, ...)
	Key        string          `json:"key"`         // withdrawal key name (withdrawals only)
	Network    string          `json:"network"`     // network (withdrawals only)
}

TransferStatus is one deposit or withdrawal record. Withdrawal-only fields (key, network) are empty for deposits.

type TriggerSignal

type TriggerSignal string

TriggerSignal selects the price signal for stop/take-profit triggers.

const (
	TriggerSignalLast  TriggerSignal = "last"
	TriggerSignalIndex TriggerSignal = "index"
)

type WalletTransferRef

type WalletTransferRef struct {
	RefID string `json:"refid"` // reference id of the transfer
}

WalletTransferRef references a wallet transfer.

type WalletTransferService

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

WalletTransferService transfers funds from the Kraken Spot wallet to the Kraken Futures wallet. (Reverse transfers use the Futures API.)

func (*WalletTransferService) Do

func (*WalletTransferService) SetFrom

SetFrom overrides the source wallet (default "Spot Wallet").

func (*WalletTransferService) SetTo

SetTo overrides the destination wallet (default "Futures Wallet").

type WebSocketClient

type WebSocketClient struct {
	*client.WebSocketClient
}

WebSocketClient streams Kraken's v2 public and private channels and supports WebSocket order entry. Public channels need no credentials; private channels and order entry require client.WithWebSocketAuth (used to fetch a short-lived auth token from the REST GetWebSocketsToken endpoint).

func NewWebSocketClient

func NewWebSocketClient(options ...client.WebSocketOptions) *WebSocketClient

NewWebSocketClient constructs a Kraken v2 WebSocket client. When client.WithWebSocketAuth is supplied, the token required by private channels and order entry is fetched (and cached, honoring WithWebSocketProxy) from the REST API automatically.

func (*WebSocketClient) DialTrade

func (c *WebSocketClient) DialTrade(ctx context.Context) (*TradeConn, error)

DialTrade opens the private v2 gateway, fetches an auth token, and returns a ready order-entry connection. Close it when done.

func (*WebSocketClient) NewSubscribeBalancesService

func (c *WebSocketClient) NewSubscribeBalancesService() *SubscribeBalancesService

func (*WebSocketClient) NewSubscribeBookService

func (c *WebSocketClient) NewSubscribeBookService(symbols ...string) *SubscribeBookService

func (*WebSocketClient) NewSubscribeExecutionsService

func (c *WebSocketClient) NewSubscribeExecutionsService() *SubscribeExecutionsService

func (*WebSocketClient) NewSubscribeInstrumentService

func (c *WebSocketClient) NewSubscribeInstrumentService() *SubscribeInstrumentService

func (*WebSocketClient) NewSubscribeLevel3Service

func (c *WebSocketClient) NewSubscribeLevel3Service(symbols ...string) *SubscribeLevel3Service

func (*WebSocketClient) NewSubscribeOHLCService

func (c *WebSocketClient) NewSubscribeOHLCService(interval int, symbols ...string) *SubscribeOHLCService

NewSubscribeOHLCService subscribes for the given symbols at the given interval in minutes (1, 5, 15, 30, 60, 240, 1440, 10080, 21600).

func (*WebSocketClient) NewSubscribeTickerService

func (c *WebSocketClient) NewSubscribeTickerService(symbols ...string) *SubscribeTickerService

func (*WebSocketClient) NewSubscribeTradeService

func (c *WebSocketClient) NewSubscribeTradeService(symbols ...string) *SubscribeTradeService

func (*WebSocketClient) SubscribeRaw

func (c *WebSocketClient) SubscribeRaw(ctx context.Context, channel string, params map[string]any, private bool, cb func([]byte, error)) (chan<- struct{}, <-chan struct{}, error)

SubscribeRaw is the low-level escape hatch: it subscribes to an arbitrary channel (public or private) with the given params and delivers each data frame's raw bytes. Prefer the typed NewSubscribe* services.

type WebSocketsToken

type WebSocketsToken struct {
	Token   string `json:"token"`   // websocket authentication token
	Expires int64  `json:"expires"` // seconds until the token expires (e.g. 900)
}

WebSocketsToken is the private-WebSocket auth token.

type WithdrawAddress

type WithdrawAddress struct {
	Address  string `json:"address"`  // withdrawal address
	Asset    string `json:"asset"`    // asset
	Method   string `json:"method"`   // withdrawal method
	Key      string `json:"key"`      // address key name
	Memo     string `json:"memo"`     // memo (some assets)
	Tag      string `json:"tag"`      // destination tag (some assets)
	Network  string `json:"network"`  // network (if applicable)
	Verified bool   `json:"verified"` // whether the address is verified
}

WithdrawAddress is one saved withdrawal address.

type WithdrawCancelService

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

WithdrawCancelService requests cancellation of a recently-requested withdrawal that has not yet been fully processed.

func (*WithdrawCancelService) Do

Do reports whether cancellation was accepted. Kraken returns a bare boolean.

type WithdrawInfo

type WithdrawInfo struct {
	Method string          `json:"method"` // withdrawal method that will be used
	Limit  decimal.Decimal `json:"limit"`  // maximum net amount withdrawable now
	Amount decimal.Decimal `json:"amount"` // net amount that will be sent, after fees
	Fee    decimal.Decimal `json:"fee"`    // fees that will be paid
}

WithdrawInfo is the fee/limit preview for a withdrawal.

type WithdrawLimit

type WithdrawLimit struct {
	Description string                         `json:"description"` // human description
	LimitType   string                         `json:"limit_type"`  // equiv_amount | amount
	Limits      map[string]WithdrawLimitWindow `json:"limits"`      // window-seconds -> usage
}

WithdrawLimit is one withdrawal-limit dimension (e.g. by USD-equivalent or by asset amount), keyed by rolling-window length in seconds.

type WithdrawLimitWindow

type WithdrawLimitWindow struct {
	Maximum   decimal.Decimal `json:"maximum"`   // maximum allowed in the window
	Remaining decimal.Decimal `json:"remaining"` // remaining allowance
	Used      decimal.Decimal `json:"used"`      // amount already used
}

WithdrawLimitWindow is the usage of one rolling limit window.

type WithdrawMethod

type WithdrawMethod struct {
	Asset     string            `json:"asset"`      // asset
	Method    string            `json:"method"`     // withdrawal method name
	MethodID  string            `json:"method_id"`  // method identifier
	Network   string            `json:"network"`    // network name
	NetworkID string            `json:"network_id"` // network identifier
	Minimum   decimal.Decimal   `json:"minimum"`    // minimum withdrawal amount
	Fee       WithdrawMethodFee `json:"fee"`        // withdrawal fee
	Limits    []WithdrawLimit   `json:"limits"`     // withdrawal limits per dimension
}

WithdrawMethod is one available withdrawal method.

type WithdrawMethodFee

type WithdrawMethodFee struct {
	AssetClass string          `json:"aclass"` // asset class of the fee
	Asset      string          `json:"asset"`  // asset the fee is charged in
	Fee        decimal.Decimal `json:"fee"`    // fee amount
}

WithdrawMethodFee is the fee charged for a withdrawal method.

type WithdrawRef

type WithdrawRef struct {
	RefID string `json:"refid"` // reference id of the withdrawal
}

WithdrawRef references a submitted withdrawal.

type WithdrawService

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

WithdrawService submits a withdrawal to a pre-configured withdrawal address (identified by its key name). This is a fund-moving endpoint; it is provided for completeness and is intentionally never exercised by the test suite.

func (*WithdrawService) Do

func (*WithdrawService) SetAddress

func (s *WithdrawService) SetAddress(address string) *WithdrawService

SetAddress confirms the withdrawal address matches the key.

func (*WithdrawService) SetAssetClass

func (s *WithdrawService) SetAssetClass(aclass string) *WithdrawService

SetAssetClass sets the asset class of the asset being withdrawn.

func (*WithdrawService) SetMaxFee

func (s *WithdrawService) SetMaxFee(maxFee decimal.Decimal) *WithdrawService

SetMaxFee caps the acceptable fee; the withdrawal fails if exceeded.

type WsAddOrder

type WsAddOrder struct {
	Symbol        string          // required: currency pair, e.g. "BTC/USD"
	Side          OrderSide       // required: buy or sell
	OrderType     OrderType       // required: limit, market, ...
	OrderQty      decimal.Decimal // required: order quantity (base)
	LimitPrice    decimal.Decimal // limit price (omitted if zero)
	TimeInForce   TimeInForce     // time in force
	PostOnly      bool            // post-only
	ReduceOnly    bool            // reduce-only (margin)
	Margin        bool            // fund on margin
	Validate      bool            // validate only, do not submit
	DisplayQty    decimal.Decimal // iceberg display quantity (omitted if zero)
	ClientOrderID string          // client order id (see MaxClOrdIDLen / ValidateClOrdID)
	OrderUserRef  int             // numeric client reference (omitted if zero)
	FeePreference string          // "base" or "quote"
	StpType       string          // self-trade prevention
}

WsAddOrder describes a new order placed over WebSocket. Required: Symbol, Side, OrderType, OrderQty. Zero-valued optional fields are omitted.

type WsAddOrderResult

type WsAddOrderResult struct {
	OrderID       string   `json:"order_id"`      // new order id
	ClientOrderID string   `json:"cl_ord_id"`     // client order id, if supplied
	OrderUserRef  int64    `json:"order_userref"` // numeric client reference, if supplied
	Warnings      []string `json:"warnings"`      // non-fatal warnings
}

WsAddOrderResult is the add_order result.

type WsAmendOrder

type WsAmendOrder struct {
	OrderID       string          // order to amend (or use ClientOrderID)
	ClientOrderID string          // client order id (alternative to OrderID)
	OrderQty      decimal.Decimal // new quantity (omitted if zero)
	DisplayQty    decimal.Decimal // new iceberg display quantity (omitted if zero)
	LimitPrice    decimal.Decimal // new limit price (omitted if zero)
	TriggerPrice  decimal.Decimal // new trigger price (omitted if zero)
	PostOnly      *bool           // toggle post-only (nil leaves unchanged)
}

WsAmendOrder amends an open order in place. Identify it by OrderID or ClientOrderID; set the fields to change.

type WsAmendOrderResult

type WsAmendOrderResult struct {
	AmendID       string   `json:"amend_id"`  // amendment id
	OrderID       string   `json:"order_id"`  // amended order id
	ClientOrderID string   `json:"cl_ord_id"` // client order id, if supplied
	Warnings      []string `json:"warnings"`  // non-fatal warnings
}

WsAmendOrderResult is the amend_order result.

type WsBalance

type WsBalance struct {
	Asset      string            `json:"asset"`       // asset name
	AssetClass string            `json:"asset_class"` // asset class
	Balance    decimal.Decimal   `json:"balance"`     // total balance
	Wallets    []WsBalanceWallet `json:"wallets"`     // per-wallet breakdown (snapshot)
	// Update-only ledger fields:
	Amount     decimal.Decimal `json:"amount"`      // ledger amount (signed)
	Fee        decimal.Decimal `json:"fee"`         // ledger fee
	LedgerID   string          `json:"ledger_id"`   // ledger entry id
	RefID      string          `json:"ref_id"`      // reference id
	Timestamp  time.Time       `json:"timestamp"`   // ledger time
	Type       string          `json:"type"`        // ledger type
	SubType    string          `json:"subtype"`     // ledger subtype
	Category   string          `json:"category"`    // ledger category
	WalletType string          `json:"wallet_type"` // wallet type
	WalletID   string          `json:"wallet_id"`   // wallet id
}

WsBalance is one element of the "balances" channel data array. Snapshot elements carry asset/balance/wallets; update elements additionally carry the driving ledger entry (amount, fee, ledger_id, ...).

type WsBalanceWallet

type WsBalanceWallet struct {
	Type    string          `json:"type"`    // wallet type (spot, earn, ...)
	ID      string          `json:"id"`      // wallet id
	Balance decimal.Decimal `json:"balance"` // wallet balance
}

WsBalanceWallet is one wallet's balance within a balances snapshot.

type WsBatchCancelResult

type WsBatchCancelResult struct {
	Count    int      `json:"count"`    // number cancelled (not always returned)
	Warnings []string `json:"warnings"` // non-fatal warnings
}

WsBatchCancelResult is the batch_cancel result. Kraken returns an empty result on success; Warnings is populated only when present.

type WsBook

type WsBook struct {
	Symbol    string        `json:"symbol"`    // currency pair
	Bids      []WsBookLevel `json:"bids"`      // changed/snapshot bid levels
	Asks      []WsBookLevel `json:"asks"`      // changed/snapshot ask levels
	Checksum  int64         `json:"checksum"`  // CRC32 of the top-10 book (uint32)
	Timestamp time.Time     `json:"timestamp"` // event time
}

WsBook is one element of the "book" channel data array. A snapshot carries the full depth; an update carries only changed levels (a level with qty 0 is removed).

type WsBookLevel

type WsBookLevel struct {
	Price decimal.Decimal `json:"price"` // price level
	Qty   decimal.Decimal `json:"qty"`   // aggregated quantity (0 = level removed)
}

WsBookLevel is one price level in the level-2 book.

type WsCancelAllAfterResult

type WsCancelAllAfterResult struct {
	CurrentTime time.Time `json:"currentTime"` // when the request was received
	TriggerTime time.Time `json:"triggerTime"` // when orders will be cancelled
}

WsCancelAllAfterResult is the cancel_all_orders_after result.

type WsCancelAllResult

type WsCancelAllResult struct {
	Count    int      `json:"count"`    // number of orders cancelled
	Warnings []string `json:"warnings"` // non-fatal warnings
}

WsCancelAllResult is the cancel_all / batch_cancel result.

type WsCancelOrderResult

type WsCancelOrderResult struct {
	OrderID       string   `json:"order_id"`  // cancelled order id
	ClientOrderID string   `json:"cl_ord_id"` // client order id, if supplied
	Warnings      []string `json:"warnings"`  // non-fatal warnings
}

WsCancelOrderResult is the cancel_order result.

type WsEditOrder

type WsEditOrder struct {
	OrderID      string          // required: order to replace
	Symbol       string          // required: currency pair
	OrderQty     decimal.Decimal // new quantity (omitted if zero)
	LimitPrice   decimal.Decimal // new limit price (omitted if zero)
	DisplayQty   decimal.Decimal // new iceberg display quantity (omitted if zero)
	OrderUserRef int             // new numeric reference (omitted if zero)
	PostOnly     *bool           // toggle post-only (nil leaves unchanged)
}

WsEditOrder cancel-replaces an existing order (yielding a new order id).

type WsEditOrderResult

type WsEditOrderResult struct {
	OrderID         string   `json:"order_id"`          // new order id
	OriginalOrderID string   `json:"original_order_id"` // replaced order id
	Warnings        []string `json:"warnings"`          // non-fatal warnings
}

WsEditOrderResult is the edit_order result.

type WsExecTriggers

type WsExecTriggers struct {
	Reference   string          `json:"reference"`    // last or index
	Price       decimal.Decimal `json:"price"`        // trigger price
	PriceType   string          `json:"price_type"`   // static or pct
	ActualPrice decimal.Decimal `json:"actual_price"` // resolved trigger price
	PeakPrice   decimal.Decimal `json:"peak_price"`   // trailing peak price
	LastPrice   decimal.Decimal `json:"last_price"`   // last reference price
	Status      string          `json:"status"`       // untriggered or triggered
	Timestamp   time.Time       `json:"timestamp"`    // trigger time
}

WsExecTriggers describes the trigger of a conditional order.

type WsExecution

type WsExecution struct {
	OrderID       string           `json:"order_id"`       // Kraken order id
	OrderUserRef  int64            `json:"order_userref"`  // client numeric reference
	ClientOrderID string           `json:"cl_ord_id"`      // client order id
	ExecID        string           `json:"exec_id"`        // execution id
	TradeID       int64            `json:"trade_id"`       // trade id (fills)
	ExecType      string           `json:"exec_type"`      // new, filled, canceled, expired, trade, ...
	OrderStatus   string           `json:"order_status"`   // pending, open, closed, canceled, expired
	OrderType     string           `json:"order_type"`     // limit, market, ...
	Symbol        string           `json:"symbol"`         // currency pair
	Side          string           `json:"side"`           // buy or sell
	TimeInForce   string           `json:"time_in_force"`  // gtc, ioc, gtd
	OrderQty      decimal.Decimal  `json:"order_qty"`      // order quantity (base)
	CumQty        decimal.Decimal  `json:"cum_qty"`        // cumulative filled quantity
	LastQty       decimal.Decimal  `json:"last_qty"`       // quantity of the last fill
	DisplayQty    decimal.Decimal  `json:"display_qty"`    // iceberg display quantity
	LimitPrice    decimal.Decimal  `json:"limit_price"`    // limit price
	StopPrice     decimal.Decimal  `json:"stop_price"`     // stop/trigger price
	AvgPrice      decimal.Decimal  `json:"avg_price"`      // average fill price
	LastPrice     decimal.Decimal  `json:"last_price"`     // last fill price
	Cost          decimal.Decimal  `json:"cost"`           // cost of the last fill
	CumCost       decimal.Decimal  `json:"cum_cost"`       // cumulative cost
	FeeUSDEquiv   decimal.Decimal  `json:"fee_usd_equiv"`  // fee in USD equivalent
	FeeCcyPref    string           `json:"fee_ccy_pref"`   // fee currency preference
	Fees          []WsExecutionFee `json:"fees"`           // fees charged
	PostOnly      bool             `json:"post_only"`      // post-only flag
	ReduceOnly    bool             `json:"reduce_only"`    // reduce-only flag
	Margin        bool             `json:"margin"`         // funded on margin
	Liquidated    bool             `json:"liquidated"`     // resulted from a liquidation
	Amended       bool             `json:"amended"`        // order was amended
	LiquidityInd  string           `json:"liquidity_ind"`  // maker (m) or taker (t)
	Timestamp     time.Time        `json:"timestamp"`      // event time
	EffectiveTime time.Time        `json:"effective_time"` // scheduled start time
	ExpireTime    time.Time        `json:"expire_time"`    // expiry time
	Reason        string           `json:"reason"`         // status reason
	CancelReason  string           `json:"cancel_reason"`  // cancellation reason
	SenderSubID   string           `json:"sender_sub_id"`  // STP sub-account id
	Triggers      *WsExecTriggers  `json:"triggers"`       // trigger details (conditional orders)
}

WsExecution is one element of the "executions" channel data array: an order or fill event. Fields are populated according to exec_type; many are present only for the relevant event.

type WsExecutionFee

type WsExecutionFee struct {
	Asset string          `json:"asset"` // fee asset
	Qty   decimal.Decimal `json:"qty"`   // fee amount
}

WsExecutionFee is one fee charged on an execution.

type WsInstrument

type WsInstrument struct {
	Assets []WsInstrumentAsset `json:"assets"` // asset reference data
	Pairs  []WsInstrumentPair  `json:"pairs"`  // pair reference data
}

WsInstrument is the "instrument" channel data object (assets and pairs).

type WsInstrumentAsset

type WsInstrumentAsset struct {
	ID               string          `json:"id"`                // asset id
	Status           string          `json:"status"`            // asset status
	Precision        int             `json:"precision"`         // record-keeping precision
	PrecisionDisplay int             `json:"precision_display"` // display precision
	Borrowable       bool            `json:"borrowable"`        // whether the asset can be borrowed
	CollateralValue  decimal.Decimal `json:"collateral_value"`  // collateral valuation factor
	MarginRate       decimal.Decimal `json:"margin_rate"`       // margin rate (if applicable)
	Multiplier       decimal.Decimal `json:"multiplier"`        // unit multiplier
	Class            string          `json:"class"`             // asset class
}

WsInstrumentAsset is reference data for one asset.

type WsInstrumentPair

type WsInstrumentPair struct {
	Symbol                  string          `json:"symbol"`                     // pair symbol
	Base                    string          `json:"base"`                       // base asset
	Quote                   string          `json:"quote"`                      // quote asset
	Status                  string          `json:"status"`                     // pair status
	QtyPrecision            int             `json:"qty_precision"`              // quantity precision
	QtyIncrement            decimal.Decimal `json:"qty_increment"`              // minimum quantity increment
	QtyMin                  decimal.Decimal `json:"qty_min"`                    // minimum order quantity
	PricePrecision          int             `json:"price_precision"`            // price precision
	PriceIncrement          decimal.Decimal `json:"price_increment"`            // minimum price increment
	CostPrecision           int             `json:"cost_precision"`             // cost precision
	CostMin                 decimal.Decimal `json:"cost_min"`                   // minimum order cost
	Marginable              bool            `json:"marginable"`                 // whether margin trading is allowed
	MarginInitial           decimal.Decimal `json:"margin_initial"`             // initial margin (if marginable)
	PositionLimitLong       int             `json:"position_limit_long"`        // long position limit
	PositionLimitShort      int             `json:"position_limit_short"`       // short position limit
	HasIndex                bool            `json:"has_index"`                  // whether an index price exists
	WSDisplayPricePrecision int             `json:"ws_display_price_precision"` // websocket display price precision
	TickSize                decimal.Decimal `json:"tick_size"`                  // price tick size
}

WsInstrumentPair is reference data for one tradable pair.

type WsLevel3

type WsLevel3 struct {
	Symbol   string          `json:"symbol"`   // currency pair
	Checksum int64           `json:"checksum"` // CRC32 of the book (uint32)
	Bids     []WsLevel3Order `json:"bids"`     // individual bid orders
	Asks     []WsLevel3Order `json:"asks"`     // individual ask orders
}

WsLevel3 is one element of the "level3" channel data array.

type WsLevel3Order

type WsLevel3Order struct {
	OrderID    string          `json:"order_id"`    // order id
	LimitPrice decimal.Decimal `json:"limit_price"` // limit price
	OrderQty   decimal.Decimal `json:"order_qty"`   // remaining quantity
	Timestamp  time.Time       `json:"timestamp"`   // order timestamp
	Event      string          `json:"event"`       // add, modify, delete
}

WsLevel3Order is one resting order in the level-3 book.

type WsOHLC

type WsOHLC struct {
	Symbol        string          `json:"symbol"`         // currency pair
	Open          decimal.Decimal `json:"open"`           // open price
	High          decimal.Decimal `json:"high"`           // high price
	Low           decimal.Decimal `json:"low"`            // low price
	Close         decimal.Decimal `json:"close"`          // close price
	VWAP          decimal.Decimal `json:"vwap"`           // volume-weighted average price
	Trades        int64           `json:"trades"`         // number of trades
	Volume        decimal.Decimal `json:"volume"`         // traded volume (base)
	IntervalBegin time.Time       `json:"interval_begin"` // candle start time
	Interval      int             `json:"interval"`       // candle interval (minutes)
	Timestamp     time.Time       `json:"timestamp"`      // event time
}

WsOHLC is one element of the "ohlc" channel data array.

type WsPush

type WsPush[T any] = request.WsPush[T]

WsPush is the channel data envelope Kraken pushes ({channel, type, data}). Type is WsPushTypeSnapshot (full) or WsPushTypeUpdate (incremental). It is re-exported from the request package for convenience: a callback receives *kraken.WsPush[[]WsTicker] and similar.

type WsPushType added in v0.20260622.1

type WsPushType = request.WsPushType

WsPushType classifies a channel data frame as a full snapshot or an incremental update. Re-exported from the request package.

type WsTicker

type WsTicker struct {
	Symbol    string          `json:"symbol"`     // currency pair
	Bid       decimal.Decimal `json:"bid"`        // best bid price
	BidQty    decimal.Decimal `json:"bid_qty"`    // best bid quantity (base)
	Ask       decimal.Decimal `json:"ask"`        // best ask price
	AskQty    decimal.Decimal `json:"ask_qty"`    // best ask quantity (base)
	Last      decimal.Decimal `json:"last"`       // last traded price
	Volume    decimal.Decimal `json:"volume"`     // 24h base-currency volume
	VWAP      decimal.Decimal `json:"vwap"`       // 24h volume-weighted average price
	Low       decimal.Decimal `json:"low"`        // 24h low
	High      decimal.Decimal `json:"high"`       // 24h high
	Change    decimal.Decimal `json:"change"`     // 24h price change (quote currency)
	ChangePct decimal.Decimal `json:"change_pct"` // 24h price change (percent)
	Timestamp time.Time       `json:"timestamp"`  // event time
}

WsTicker is one element of the "ticker" channel data array.

type WsTrade

type WsTrade struct {
	Symbol    string          `json:"symbol"`    // currency pair
	Side      string          `json:"side"`      // buy or sell
	Qty       decimal.Decimal `json:"qty"`       // executed quantity (base)
	Price     decimal.Decimal `json:"price"`     // execution price
	OrderType string          `json:"ord_type"`  // market or limit
	TradeID   int64           `json:"trade_id"`  // trade id
	Timestamp time.Time       `json:"timestamp"` // execution time
}

WsTrade is one element of the "trade" channel data array.

type WsTradeResponse

type WsTradeResponse[T any] = request.WsTradeResponse[T]

WsTradeResponse re-exports the request-layer trade response for convenience.

Directories

Path Synopsis
cmd
kraw command
Command kraw signs and executes a single Kraken spot REST call and pretty prints the raw response.
Command kraw signs and executes a single Kraken spot REST call and pretty prints the raw response.
internal
apitest
Package apitest holds the shared, test-only helpers used by the Kraken SDK's _test.go files to verify that the typed endpoint structs cover every field the live Kraken API returns.
Package apitest holds the shared, test-only helpers used by the Kraken SDK's _test.go files to verify that the typed endpoint structs cover every field the live Kraken API returns.
pkg
log

Jump to

Keyboard shortcuts

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