gokraken

package module
v0.0.0-...-9f05c4e Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2018 License: MIT Imports: 18 Imported by: 0

README

Go Kraken GoDoc License Go Report Card Build Status

A Go API client for the Kraken cryptocurrency exchange

Usage

Public API
package main

import (
	"context"
	"fmt"
	"log"
	
	"github.com/danmrichards/gokraken"
)

func main() {
	kraken := gokraken.New()
	
	res, err := kraken.Market.Time(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	
	fmt.Printf("server unix time: %d\n", res.UnixTime)
	fmt.Printf("service rfc1123 time: %s\n", res.Rfc1123)
}
Private API
package main

import (
	"context"
	"fmt"
	"log"
	
	"github.com/danmrichards/gokraken"
)

func main() {
	kraken := gokraken.NewWithAuth("API_KEY", "PRIVATE_KEY")
	
	res, err := kraken.UserData.Balance(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	
	for currency, balance := range res {
	    fmt.Printf("%s: %f'n", currency, balance)
	}
}

Roadmap

  • Base repo structure
  • Public API calls working
  • Private API calls working
  • Travis CI
  • Implement public market data endpoints
  • Implement private user data endpoints
  • Implement private user trading endpoints
  • Implement private user funding endpoints
  • Test all the things!

Documentation

Index

Constants

View Source
const (
	// AssetsResource is the API resource for the Kraken API asset info.
	AssetsResource = "Assets"

	// AssetInfo is the info level for asset.
	AssetInfo AssetsInfoLevel = "info"

	// AssetCurrency is the asset class for asset.
	AssetCurrency AssetsClass = "currency"
)
View Source
const (
	// BalanceResource is the API resource for balance.
	BalanceResource = "Balance"

	// TradeBalanceResource is the API resource for trade balance.
	TradeBalanceResource = "TradeBalance"
)
View Source
const (
	// DepositMethodsResource is the API resource for deposit methods.
	DepositMethodsResource = "DepositMethods"

	// DepositAddressesResource is the API resource for deposit addresses.
	DepositAddressesResource = "DepositAddresses"

	// DepositStatusResource is the API resource for deposit status.
	DepositStatusResource = "DepositStatus"
)
View Source
const (
	// APIBaseURL is the base URI of the Kraken API.
	APIBaseURL = "https://api.kraken.com"

	// APIKeyHeader is the header to send the API key to Kraken in.
	APIKeyHeader = "API-Key"

	// APINonceParam is the parameter to send the nonce to Kraken in.
	APINonceParam = "nonce"

	// APIPublicNamespace is the name of the public Kraken API namespace.
	APIPublicNamespace = "public"

	// APIPrivateNamespace is the name of the private Kraken API namespace.
	APIPrivateNamespace = "private"

	// APISignHeader is the header to send the API signature to Kraken in.
	APISignHeader = "API-Sign"

	// APIVersion is the current version number of the Kraken API.
	APIVersion = 0

	// ClientVersion is the current version of this client.
	ClientVersion = "0.1.0"
)
View Source
const (
	// AddOrderResource is the API resource for adding orders.
	AddOrderResource = "AddOrder"

	// CancelOrderResource is the API resource for canceling open orders.
	CancelOrderResource = "CancelOrder"

	// ClosedOrdersResource is the API resource for closed orders.
	ClosedOrdersResource = "ClosedOrders"

	// QueryOrdersResource is the API resource for querying orders.
	QueryOrdersResource = "QueryOrders"

	// OrderCloseTimeOpen is the time an order opens.
	OrderCloseTimeOpen OrderCloseTime = "open"

	// OrderCloseTimeClose is the time an order closes.
	OrderCloseTimeClose OrderCloseTime = "close"

	// OrderCloseTimeBoth is the time an order opens and closes.
	OrderCloseTimeBoth OrderCloseTime = "both"

	// OpenOrdersResource is the API resource for open orders.
	OpenOrdersResource = "OpenOrders"

	// OrderFlagViqc is an order flag for volume in quote currency
	// (not available for leveraged orders).
	OrderFlagViqc OrderFlag = "viqc"

	// OrderFlagFcib is an order flag for prefer fee in base currency.
	OrderFlagFcib OrderFlag = "fcib"

	// OrderFlagFciq is an order flag for prefer fee in quote currency.
	OrderFlagFciq OrderFlag = "fciq"

	// OrderFlagNompp is an order flag for no market price protection.
	OrderFlagNompp OrderFlag = "nompp"

	// OrderFlagPost is an order flag for post only order
	// (available when ordertype // limit).
	OrderFlagPost OrderFlag = "post"

	// OrderTypeMarket is the market order type.
	OrderTypeMarket OrderType = "market"

	// OrderTypeLimit (price = limit price).
	OrderTypeLimit OrderType = "limit"

	// OrderTypeStopLoss (price = stop loss price).
	OrderTypeStopLoss OrderType = "stop-loss"

	// OrderTypeTakeProfit (price = take profit price).
	OrderTypeTakeProfit OrderType = "take-profit"

	// OrderTypeStopLossProfit (price = stop loss price, price2 = take profit price).
	OrderTypeStopLossProfit OrderType = "stop-loss-profit"

	// OrderTypeStopLossProfitLimit (price = stop loss price, price2 = take profit price).
	OrderTypeStopLossProfitLimit OrderType = "stop-loss-profit-limit"

	// OrderTypeStopLossLimit (price = stop loss trigger price, price2 = triggered limit price).
	OrderTypeStopLossLimit OrderType = "stop-loss-limit"

	// OrderTypeTakeProfitLimit (price = take profit trigger price, price2 = triggered limit price).
	OrderTypeTakeProfitLimit OrderType = "take-profit-limit"

	// OrderTypeTrailingStop (price = trailing stop offset).
	OrderTypeTrailingStop OrderType = "trailing-stop"

	// OrderTypeTrailingStopLimit (price = trailing stop offset, price2 = triggered limit offset).
	OrderTypeTrailingStopLimit OrderType = "trailing-stop-limit"

	// OrderTypeStopLossAndLimit (price = stop loss price, price2 = limit price).
	OrderTypeStopLossAndLimit OrderType = "stop-loss-and-limit"

	// OrderTypeSettlePosition is the order type for settle and position.
	OrderTypeSettlePosition OrderType = "settle-position"
)
View Source
const (
	// TradesResource is the API resource for Kraken API recent trades.
	TradesResource = "Trades"

	// TradesHistoryResource is the API resource for Kraken API trade history.
	TradesHistoryResource = "TradesHistory"

	// TradesInfoResource is the API resource for Kraken API trades info.
	TradesInfoResource = "TradesInfo"

	// TradeVolumeResource is the API resource for Kraken API trade volume.
	TradeVolumeResource = "TradeVolume"

	// TradeBuy indicates that a trade was a 'buy'.
	TradeBuy TradeBuySell = "buy"

	// TradeSell indicates that a trade was a 'sell'.
	TradeSell TradeBuySell = "sell"

	// TradeMarket indicates that a trade was 'market'.
	TradeMarket TradeMarketLimit = "market"

	// TradeLimit indicates that a trade was 'limit'.
	TradeLimit TradeMarketLimit = "limit"

	// TradeTypeAll indicates all trades.
	TradeTypeAll TradeType = "all"

	// TradeTypeAny indicates any position (opened or closed).
	TradeTypeAny TradeType = "any position"

	// TradeTypeClosed indicates positions that have closed.
	TradeTypeClosed TradeType = "closed position"

	// TradeTypeClosing indicates any trade closing all or part of a position.
	TradeTypeClosing TradeType = "closing position"

	// TradeTypeNoPosition indicates non-positional trades.
	TradeTypeNoPosition TradeType = "no position"
)
View Source
const (
	// WithdrawInfoResource is the API resource for withdrawal information.
	WithdrawInfoResource = "WithdrawInfo"

	// WithdrawResource is the API resource for withdrawing funds.
	WithdrawResource = "Withdraw"

	// WithdrawStatusResource is the API resource for getting the status of a
	// withdrawal.
	WithdrawStatusResource = "WithdrawStatus"

	// WithdrawCancelResource is the API resource for canceling a withdrawal.
	WithdrawCancelResource = "WithdrawCancel"
)
View Source
const DepthResource = "Depth"

DepthResource is the API resource for the Kraken API order book.

View Source
const OhlcResource = "OHLC"

OhlcResource is the API resource for the Kraken API ohlc.

View Source
const OpenPositionsResource = "OpenPositions"

OpenPositionsResource is the API resource for the Kraken API open positions.

View Source
const SpreadResource = "Spread"

SpreadResource is the API resource for the Kraken API spread data.

View Source
const TickerResource = "Ticker"

TickerResource is the API resource for the Kraken API ticker.

View Source
const TimeResource = "Time"

TimeResource is the API resource for the Kraken API server time.

Variables

View Source
var (
	// UserAgent is the user agent string applied to all requests.
	UserAgent = fmt.Sprintf("Go Kraken %s (github.com/danmrichards/gokraken)", ClientVersion)
)

Functions

This section is empty.

Types

type AddOrderResponse

type AddOrderResponse struct {
	Description OrderDescription `json:"descr"`
	TxIDs       []string         `json:"txid"`
}

AddOrderResponse represents the response from the AddOrder endpoint of the Kraken API.

type Asset

type Asset struct {
	AltName         string      `json:"altname"`          // Alternate name.
	AClass          AssetsClass `json:"aclass"`           // Asset class.
	Decimals        int         `json:"decimals"`         // Scaling decimal places for record keeping.
	DisplayDecimals int         `json:"display_decimals"` // Scaling decimal places for output display.
}

Asset represents a Kraken asset.

type AssetPairData

type AssetPairData struct {
	Altname           string      `json:"altname"`
	AclassBase        string      `json:"aclass_base"`
	Base              string      `json:"base"`
	AclassQuote       string      `json:"aclass_quote"`
	Quote             string      `json:"quote"`
	Lot               string      `json:"lot"`
	PairDecimals      int         `json:"pair_decimals"`
	LotDecimals       int         `json:"lot_decimals"`
	LotMultiplier     int         `json:"lot_multiplier"`
	LeverageBuy       []float64   `json:"leverage_buy"`
	LeverageSell      []float64   `json:"leverage_sell"`
	Fees              [][]float64 `json:"fees"`
	FeesMaker         [][]float64 `json:"fees_maker"`
	FeeVolumeCurrency string      `json:"fee_volume_currency"`
	MarginCall        int         `json:"margin_call"`
	MarginStop        int         `json:"margin_stop"`
}

AssetPairData contains data about a tradeable asset pair from Kraken.

type AssetPairsInfoLevel

type AssetPairsInfoLevel string

AssetPairsInfoLevel represents an info level for an asset pairs request.

const (
	// AssetPairsResource is the API resource for the Kraken API asset info.
	AssetPairsResource = "AssetPairs"

	// AssetPairsInfo is the info level for asset pairs.
	AssetPairsInfo AssetPairsInfoLevel = "info"

	// AssetPairsLeverage is the leverage level for asset pairs.
	AssetPairsLeverage AssetPairsInfoLevel = "leverage"

	// AssetPairsFees is the fees level for asset pairs.
	AssetPairsFees AssetPairsInfoLevel = "fees"

	// AssetPairsMargin is the margin level for asset pairs.
	AssetPairsMargin AssetPairsInfoLevel = "margin"
)

type AssetPairsResponse

type AssetPairsResponse map[pairs.AssetPair]AssetPairData

AssetPairsResponse represents an array of asset pairs and their info.

type AssetsClass

type AssetsClass string

AssetsClass represents an asset class for an asset request.

type AssetsInfoLevel

type AssetsInfoLevel string

AssetsInfoLevel represents an info level for an asset request.

type AssetsResponse

type AssetsResponse map[asset.Currency]Asset

AssetsResponse represents an array of asset names and their info.

type BalanceResponse

type BalanceResponse map[asset.Currency]float64

BalanceResponse represents the response from the Balance endpoint of the Kraken API.

type CancelOrderResponse

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

CancelOrderResponse represents the response from the CancelOrder endpoint of the Kraken API.

type ClosedOrdersRequest

type ClosedOrdersRequest struct {
	Trades    bool           // Whether or not to include trades in output.
	UserRef   int64          // Restrict results to given user reference id.
	Start     *time.Time     // Starting unix timestamp or order tx id of results.
	End       *time.Time     // Ending unix timestamp or order tx id of results (optional.  inclusive)
	Ofs       int            // Result offset.
	CloseTime OrderCloseTime // Which time to use.
}

ClosedOrdersRequest represents a request to get closed orders from Kraken.

type ClosedOrdersResponse

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

ClosedOrdersResponse represents the response from the ClosedOrders endpoint of the Kraken API.

type DepositAddress

type DepositAddress struct {
	Address    string `json:"address"`
	ExpireTime int64  `json:"expiretm"`
	New        bool   `json:"new"`
}

DepositAddress represents a Kraken deposit address.

type DepositAddressesResponse

type DepositAddressesResponse map[string]DepositAddress

DepositAddressesResponse represents the response from the DepositAddresses endpoint of the Kraken API.

type DepositMethod

type DepositMethod struct {
	Method          string  `json:"method"`
	Limit           float64 `json:"limit"`
	Fee             float64 `json:"fee"`
	AddressSetupFee bool    `json:"address-setup-fee"`
}

DepositMethod represents a Kraken deposit method.

type DepositMethodsResponse

type DepositMethodsResponse map[string]DepositMethod

DepositMethodsResponse represents the response from the DepositMethods endpoint of the Kraken API.

type DepositStatusProp

type DepositStatusProp struct {
	OnHold string `json:"onhold"`
}

DepositStatusProp represents additional status properties on a Kraken deposit status.

type DepositStatusResponse

type DepositStatusResponse struct {
	Method     string            `json:"method"`
	AClass     string            `json:"aclass"`
	Asset      string            `json:"asset"`
	RefID      string            `json:"refid"`
	TxID       string            `json:"txid"`
	Info       string            `json:"info"`
	Amount     float64           `json:"amount"`
	Fee        float64           `json:"fee"`
	Time       int64             `json:"time"`
	Status     string            `json:"status"`
	StatusProp DepositStatusProp `json:"status-prop"`
}

DepositStatusResponse represents the response from the DepositStatus endpoint of the Kraken API.

type Depth

type Depth struct {
	Asks []DepthItem `json:"asks"`
	Bids []DepthItem `json:"bids"`
}

Depth is an order book response for a given asset pair.

type DepthItem

type DepthItem struct {
	Price     float64
	Volume    float64
	Timestamp time.Time
}

DepthItem is either the asks or bids for an assert pair order book entry.

func (*DepthItem) UnmarshalJSON

func (d *DepthItem) UnmarshalJSON(data []byte) error

UnmarshalJSON parses the JSON-encoded data and stores the result in the value pointed to by d.

Due to the nature of the Kraken API response we create an auxiliary struct, and then a slice of pointers to the auxiliary struct fields. We unmarshal into this slice and finally apply any type conversions into the destination fields in the value pointed by d.

type DepthResponse

type DepthResponse map[pairs.AssetPair]Depth

DepthResponse represents the response from the Kraken order book endpoint.

type Fee

type Fee struct {
	Fee        string `json:"fee"`
	Maxfee     string `json:"maxfee"`
	Minfee     string `json:"minfee"`
	Nextfee    string `json:"nextfee"`
	Nextvolume string `json:"nextvolume"`
	Tiervolume string `json:"tiervolume"`
}

Fee represents a fee within the Kraken TradeVolume response.

type Funding

type Funding struct {
	Client *Kraken
}

Funding is responsible for communicating with all the private user funding endpoints on the Kraken API.

func (*Funding) DepositAddresses

func (f *Funding) DepositAddresses(ctx context.Context, aclass AssetsClass, asset asset.Currency, method string, new bool) (res DepositAddressesResponse, err error)

DepositAddresses gets a list of deposit addresses via the Kraken API. https://www.kraken.com/en-gb/help/api#deposit-methods

func (*Funding) DepositMethods

func (f *Funding) DepositMethods(ctx context.Context, aclass AssetsClass, asset asset.Currency) (res DepositMethodsResponse, err error)

DepositMethods gets a list of deposit methods via the Kraken API. https://www.kraken.com/en-gb/help/api#deposit-methods

func (*Funding) DepositStatus

func (f *Funding) DepositStatus(ctx context.Context, aclass AssetsClass, asset asset.Currency, method string) (res *DepositStatusResponse, err error)

DepositStatus gets the status of recent deposits via the Kraken api. https://www.kraken.com/en-gb/help/api#deposit-methods

func (*Funding) Withdraw

func (f *Funding) Withdraw(ctx context.Context, aclass AssetsClass, asset asset.Currency, key string, amount float64) (res *WithdrawResponse, err error)

Withdraw withdraws funds via the Kraken api. https://www.kraken.com/en-gb/help/api#withdraw-funds

func (*Funding) WithdrawCancel

func (f *Funding) WithdrawCancel(ctx context.Context, aclass AssetsClass, asset asset.Currency, refID string) (res bool, err error)

WithdrawCancel requests withdrawal cancellation via the Kraken api. https://www.kraken.com/en-gb/help/api#withdraw-cancel

func (*Funding) WithdrawInfo

func (f *Funding) WithdrawInfo(ctx context.Context, aclass AssetsClass, asset asset.Currency, key string, amount float64) (res *WithdrawInfoResponse, err error)

WithdrawInfo gets withdrawal information via the Kraken api. https://www.kraken.com/en-gb/help/api#get-withdrawal-info

func (*Funding) WithdrawStatus

func (f *Funding) WithdrawStatus(ctx context.Context, aclass AssetsClass, asset asset.Currency, method string) (res WithdrawStatusResponse, err error)

WithdrawStatus gets status of recent withdrawals via the Kraken api. https://www.kraken.com/en-gb/help/api#withdraw-status

type Kraken

type Kraken struct {
	APIKey     string
	BaseURL    string
	HTTPClient *http.Client
	Market     *Market
	UserData   *UserData
	Trading    *Trading
	Funding    *Funding
	PrivateKey string
}

Kraken is responsible for all communication with the Kraken API.

func New

func New() *Kraken

New returns a new Kraken object with a default HTTP client.

func NewWithAuth

func NewWithAuth(apiKey, privateKey string) *Kraken

NewWithAuth returns a new Kraken object with the authentication credentials required for private api endpoints.

func NewWithHTTPClient

func NewWithHTTPClient(httpClient *http.Client) *Kraken

NewWithHTTPClient returns a new Kraken object with a custom HTTP client.

func (*Kraken) Call

func (k *Kraken) Call(req *http.Request) (res *Response, err error)

Call performs a request against the Kraken API.

func (*Kraken) Dial

func (k *Kraken) Dial(ctx context.Context, method, resource string, body url.Values) (req *http.Request, err error)

Dial prepares a request to send to the Kraken API.

func (*Kraken) DialWithAuth

func (k *Kraken) DialWithAuth(ctx context.Context, method, resource string, body url.Values) (req *http.Request, err error)

DialWithAuth prepares an authenticated request to send to the Kraken API.

func (*Kraken) GetBaseURL

func (k *Kraken) GetBaseURL() string

GetBaseURL returns the base URI of the Kraken API. If the BaseURL value is not set on the Kraken struct the constant APIBaseURL will be returned instead.

func (*Kraken) ResourceURI

func (k *Kraken) ResourceURI(namespace, resource string) string

ResourceURI returns the URI path for the given api resource.

func (*Kraken) ResourceURL

func (k *Kraken) ResourceURL(namespace, resource string) string

ResourceURL returns a fully qualified URI for the given api resource.

type Ledger

type Ledger struct {
	Refid   string  `json:"refid"`
	Time    int64   `json:"time"`
	Type    string  `json:"type"`
	Aclass  string  `json:"aclass"`
	Asset   string  `json:"asset"`
	Amount  float64 `json:"amount"`
	Fee     float64 `json:"fee"`
	Balance float64 `json:"balance"`
}

Ledger represent a Kraken ledger entry.

type LedgerType

type LedgerType string

LedgerType is a type of kraken ledger.

const (
	// LedgersResource is the API resource for the Kraken API ledgers endpoint.
	LedgersResource = "Ledgers"

	// LedgerTypeAll is used to list all ledgers.
	LedgerTypeAll LedgerType = "all"

	// LedgerTypeDeposit is used to list deposit ledgers.
	LedgerTypeDeposit LedgerType = "deposit"

	// LedgerTypeWithdrawal is used to list withdrawal ledgers.
	LedgerTypeWithdrawal LedgerType = "withdrawal"

	// LedgerTypeTrade is used to list trade ledgers.
	LedgerTypeTrade LedgerType = "trade"

	// LedgerTypeMargin is used to list margin ledgers.
	LedgerTypeMargin LedgerType = "margin"

	// QueryLedgersResource is the API resource for the Kraken API query ledgers endpoint.
	QueryLedgersResource = "QueryLedgers"
)

type LedgersRequest

type LedgersRequest struct {
	Aclass AssetsClass      // Asset class.
	Assets []asset.Currency // List of assets to restrict output to.
	Type   LedgerType       // Type of ledger to retrieve.
	Start  *time.Time       // Starting timestamp.
	End    *time.Time       // Ending timestamp.
	Ofs    int              // Offset.
}

LedgersRequest represents a request to list ledger information from Kraken.

type LedgersResponse

type LedgersResponse map[string]Ledger

LedgersResponse represents the response from the OpenPositions endpoint of the Kraken API.

type Market

type Market struct {
	Client *Kraken
}

Market is responsible for communicating with all the public data market endpoints on the Kraken API.

func (*Market) AssetPairs

func (m *Market) AssetPairs(ctx context.Context, info AssetPairsInfoLevel, reqPairs ...pairs.AssetPair) (res AssetPairsResponse, err error)

AssetPairs returns tradable asset pairs from Kraken. https://www.kraken.com/en-gb/help/api#get-tradable-pairs

func (*Market) Assets

func (m *Market) Assets(ctx context.Context, info AssetsInfoLevel, aClass AssetsClass, assets ...asset.Currency) (res AssetsResponse, err error)

Assets returns asset information from Kraken. https://www.kraken.com/en-gb/help/api#get-asset-info

func (*Market) Depth

func (m *Market) Depth(ctx context.Context, pair pairs.AssetPair, count int) (res DepthResponse, err error)

Depth returns the order book from Kraken. https://www.kraken.com/en-gb/help/api#get-order-book

func (*Market) Ohlc

func (m *Market) Ohlc(ctx context.Context, ohlcReq OhlcRequest) (res *OhlcResponse, err error)

Ohlc returns ohlc information from Kraken. https://www.kraken.com/en-gb/help/api#get-ohlc-data

func (*Market) Spread

func (m *Market) Spread(ctx context.Context, spreadReq SpreadRequest) (res *SpreadResponse, err error)

Spread returns the spread data from Kraken. https://www.kraken.com/en-gb/help/api#get-recent-spread-data

func (*Market) Ticker

func (m *Market) Ticker(ctx context.Context, reqPairs ...pairs.AssetPair) (res TickerResponse, err error)

Ticker returns ticker information from Kraken. https://www.kraken.com/en-gb/help/api#get-ticker-info

func (*Market) Time

func (m *Market) Time(ctx context.Context) (res *TimeResponse, err error)

Time returns the current server time of Kraken. https://www.kraken.com/help/api#get-server-time

func (*Market) Trades

func (m *Market) Trades(ctx context.Context, tradeReq TradesRequest) (res *TradesResponse, err error)

Trades returns the recent trades from Kraken. https://www.kraken.com/en-gb/help/api#get-recent-trades

type OhlcData

type OhlcData struct {
	Timestamp time.Time
	Open      float64
	High      float64
	Low       float64
	Close     float64
	Vwap      float64
	Volume    float64
	Count     int
}

OhlcData represents a set of OHLC data from Kraken.

type OhlcRequest

type OhlcRequest struct {
	Pair     pairs.AssetPair
	Interval int
	Since    int64
}

OhlcRequest represents a request to list OHLC information from Kraken.

type OhlcResponse

type OhlcResponse struct {
	Data []OhlcData
	Last int64
}

OhlcResponse represents the response from the Kraken ohlc endpoint.

type OpenOrdersResponse

type OpenOrdersResponse struct {
	Open  map[string]Order `json:"open"`
	Count int              `json:"count"`
}

OpenOrdersResponse represents the response from the OpenOrders endpoint of the Kraken API.

type OpenPositionsResponse

type OpenPositionsResponse map[string]Position

OpenPositionsResponse represents the response from the OpenPositions endpoint of the Kraken API.

type Order

type Order struct {
	TransactionID  string           `json:"-"`
	ReferenceID    string           `json:"refid"`
	UserRef        int64            `json:"userref"`
	Status         string           `json:"status"`
	OpenTime       float64          `json:"opentm"`
	StartTime      float64          `json:"starttm"`
	ExpireTime     float64          `json:"expiretm"`
	Description    OrderDescription `json:"descr"`
	Volume         string           `json:"vol"`
	VolumeExecuted float64          `json:"vol_exec,string"`
	Cost           float64          `json:"cost,string"`
	Fee            float64          `json:"fee,string"`
	Price          float64          `json:"price,string"`
	StopPrice      float64          `json:"stopprice.string"`
	LimitPrice     float64          `json:"limitprice,string"`
	Misc           string           `json:"misc"`
	OrderFlags     string           `json:"oflags"`
	CloseTime      float64          `json:"closetm"`
	Reason         string           `json:"reason"`
}

Order represents a single order

type OrderCloseTime

type OrderCloseTime string

OrderCloseTime is the time to close an order.

type OrderDescription

type OrderDescription struct {
	AssetPair      pairs.AssetPair `json:"pair"`
	Close          string          `json:"close"`
	Leverage       string          `json:"leverage"`
	Order          string          `json:"order"`
	OrderType      OrderType       `json:"ordertype"`
	PrimaryPrice   string          `json:"price"`
	SecondaryPrice string          `json:"price2"`
	Type           string          `json:"type"`
}

OrderDescription describes the detail of an order including the assets pair involved, prices and the order type.

type OrderFlag

type OrderFlag string

OrderFlag is a flag to use when creating a Kraken order.

type OrderType

type OrderType string

OrderType is a type of Kraken order.

type Position

type Position struct {
	OrderTxid string  `json:"ordertxid"`  // Order responsible for execution of trade.
	Pair      string  `json:"pair"`       // Asset pair.
	Time      int64   `json:"time"`       // Unix timestamp of trade.
	Type      string  `json:"type"`       // Type of order used to open position (buy/sell).
	OrderType string  `json:"ordertype"`  // Order type used to open position.
	Cost      float64 `json:"cost"`       // Opening cost of position (quote currency unless viqc set in oflags).
	Fee       float64 `json:"fee"`        // Opening fee of position (quote currency).
	Vol       float64 `json:"vol"`        // Position volume (base currency unless viqc set in oflags).
	VolClosed float64 `json:"vol_closed"` // Position volume closed (base currency unless viqc set in oflags).
	Margin    float64 `json:"margin"`     // Initial margin (quote currency).
	Value     float64 `json:"value"`      // Current value of remaining position (if docalcs requested.  quote currency).
	Net       float64 `json:"net"`        // Unrealized profit/loss of remaining position (if docalcs requested.  quote currency, quote currency scale).
	Misc      string  `json:"misc"`       // Comma delimited list of miscellaneous info.
	OFlags    string  `json:"oflags"`     // Comma delimited list of order flags.
	Viqc      float64 `json:"viqc"`       // Volume in quote currency.
}

Position represents a Kraken open position.

type QueryOrdersResponse

type QueryOrdersResponse map[string]Order

QueryOrdersResponse represents the response from the QueryOrders endpoint of the Kraken API.

type QueryTradesResponse

type QueryTradesResponse map[string]UserTrade

QueryTradesResponse represents the response from the TradesInfo endpoint of the Kraken API.

type Response

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

Response represents a response from the Kraken API.

func (*Response) ExtractResult

func (r *Response) ExtractResult(dst interface{}) error

ExtractResult extracts the result from a Kraken API response into the destination parameter.

type Signature

type Signature struct {
	APISecret []byte
	Data      url.Values
	URI       string
}

Signature represents a cryptographic signature for signing private Kraken API requests.

func (*Signature) Generate

func (s *Signature) Generate() string

Generate returns a message signature for use on private Kraken API endpoints. https://www.kraken.com/en-gb/help/api#general-usage

type SpreadData

type SpreadData struct {
	Timestamp time.Time
	Bid       float64
	Ask       float64
}

SpreadData is the spread of data for trades.

type SpreadRequest

type SpreadRequest struct {
	Pair  pairs.AssetPair
	Since int64
}

SpreadRequest represents a request to get spread data from Kraken.

type SpreadResponse

type SpreadResponse struct {
	Data []SpreadData
	Last int64
}

SpreadResponse represents the response from the Kraken spread data endpoint.

type TickerInfo

type TickerInfo struct {
	A []string `json:"a"` // ask array(<price>, <whole lot volume>, <lot volume>).
	B []string `json:"b"` // bid array(<price>, <whole lot volume>, <lot volume>).
	C []string `json:"c"` // last trade closed array(<price>, <lot volume>).
	V []string `json:"v"` // volume array(<today>, <last 24 hours>).
	P []string `json:"p"` // volume weighted average price array(<today>, <last 24 hours>).
	T []int    `json:"t"` // number of trades array(<today>, <last 24 hours>).
	L []string `json:"l"` // low array(<today>, <last 24 hours>).
	H []string `json:"h"` // high array(<today>, <last 24 hours>).
	O string   `json:"o"` // today's opening price.
}

TickerInfo represents the TickerInfo for an asset pair.

type TickerResponse

type TickerResponse map[pairs.AssetPair]TickerInfo

TickerResponse represents the response from the Ticker endpoint of the Kraken API.

type TimeResponse

type TimeResponse struct {
	UnixTime int64  `json:"unixtime"`
	Rfc1123  string `json:"rfc1123"`
}

TimeResponse represents the response from the Time endpoint of the Kraken API.

type Trade

type Trade struct {
	Price         float64
	Volume        float64
	Timestamp     time.Time
	BuySell       TradeBuySell
	MarketLimit   TradeMarketLimit
	Miscellaneous string
}

Trade is a trade of asset.

type TradeBalanceResponse

type TradeBalanceResponse struct {
	EquivalentBalance float64 `json:"eb"`
	TradeBalance      float64 `json:"tb"`
	MarginAmount      float64 `json:"m"`
	UnrealizedNet     float64 `json:"n"`
	Cost              float64 `json:"c"`
	Valuation         float64 `json:"v"`
	Equity            float64 `json:"e"`
	FreeMargin        float64 `json:"mf"`
	MarginLevel       float64 `json:"ml"`
}

TradeBalanceResponse represents the response from the TradeBalance endpoint of the Kraken API.

type TradeBuySell

type TradeBuySell string

TradeBuySell indicates if a trade was a 'buy' or a 'sell'.

type TradeMarketLimit

type TradeMarketLimit string

TradeMarketLimit indicates if a trade was 'market' or 'limit'.

type TradeType

type TradeType string

TradeType indicates the type of trade.

type TradeVolumeResponse

type TradeVolumeResponse struct {
	Currency  string         `json:"currency"`
	Fees      map[string]Fee `json:"fees"`
	FeesMaker map[string]Fee `json:"fees_maker"`
	Volume    string         `json:"volume"`
}

TradeVolumeResponse represents the response from the TradeVolume endpoint of the Kraken API.

type TradesHistoryRequest

type TradesHistoryRequest struct {
	Type   TradeType  // The type of trade.
	Trades bool       // Whether or not to include trades in output.
	Start  *time.Time // Starting unix timestamp or order tx id of results.
	End    *time.Time // Ending unix timestamp or order tx id of results.
	Ofs    int        // Result offset.
}

TradesHistoryRequest represents a request to get a users trade history.

type TradesHistoryResponse

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

TradesHistoryResponse represents the response from the TradesHistory endpoint of the Kraken API.

type TradesRequest

type TradesRequest struct {
	Pair  pairs.AssetPair
	Since int64
}

TradesRequest represents a request to get recent trades from Kraken.

type TradesResponse

type TradesResponse struct {
	Trades []Trade
	Last   int64
}

TradesResponse represents the response from the Kraken recent trades endpoint.

type Trading

type Trading struct {
	Client *Kraken
}

Trading is responsible for communicating with all the private user trading endpoints on the Kraken API.

func (*Trading) AddOrder

func (t *Trading) AddOrder(ctx context.Context, order UserOrder) (res *AddOrderResponse, err error)

AddOrder adds a standard order via the Kraken API. https://www.kraken.com/en-gb/help/api#add-standard-order

func (*Trading) CancelOrder

func (t *Trading) CancelOrder(ctx context.Context, txid int64) (res *CancelOrderResponse, err error)

CancelOrder cancels an open order via the Kraken API. https://www.kraken.com/en-gb/help/api#cancel-open-order

type UserData

type UserData struct {
	Client *Kraken
}

UserData is responsible for communicating with all the private user data endpoints on the Kraken API.

func (*UserData) Balance

func (u *UserData) Balance(ctx context.Context) (res BalanceResponse, err error)

Balance returns an array of asset names and balance amount. https://www.kraken.com/en-gb/help/api#get-account-balance

func (*UserData) ClosedOrders

func (u *UserData) ClosedOrders(ctx context.Context, closedReq ClosedOrdersRequest) (res *ClosedOrdersResponse, err error)

ClosedOrders returns an order info array. https://www.kraken.com/en-gb/help/api#get-closed-orders

func (*UserData) Ledgers

func (u *UserData) Ledgers(ctx context.Context, ledgersReq LedgersRequest) (res LedgersResponse, err error)

Ledgers returns an associative array of ledgers info. https://www.kraken.com/en-gb/help/api#get-ledgers-info

func (*UserData) OpenOrders

func (u *UserData) OpenOrders(ctx context.Context, trades bool, userRef int64) (res *OpenOrdersResponse, err error)

OpenOrders returns an order info in open array with txid as the key. https://www.kraken.com/help/api#get-open-orders

func (*UserData) OpenPositions

func (u *UserData) OpenPositions(ctx context.Context, doCalcs bool, txids ...int64) (res OpenPositionsResponse, err error)

OpenPositions returns an associative array of open positions info. https://www.kraken.com/en-gb/help/api#get-open-positions

func (*UserData) QueryLedgers

func (u *UserData) QueryLedgers(ctx context.Context, ids ...int64) (res LedgersResponse, err error)

QueryLedgers returns an associative array of ledgers info. https://www.kraken.com/en-gb/help/api#query-ledgers

func (*UserData) QueryOrders

func (u *UserData) QueryOrders(ctx context.Context, trades bool, userRef int64, txids ...int64) (res *QueryOrdersResponse, err error)

QueryOrders returns an associative array of order info. https://www.kraken.com/en-gb/help/api#query-orders-info

func (*UserData) QueryTrades

func (u *UserData) QueryTrades(ctx context.Context, trades bool, txids ...int64) (res *QueryTradesResponse, err error)

QueryTrades returns an associative array of trade info. https://www.kraken.com/en-gb/help/api#query-trades-info

func (*UserData) TradeBalance

func (u *UserData) TradeBalance(ctx context.Context, assetClass AssetsClass, base asset.Currency) (res *TradeBalanceResponse, err error)

TradeBalance returns an array of trade balance information. https://www.kraken.com/en-gb/help/api#get-trade-balance

func (*UserData) TradeVolume

func (u *UserData) TradeVolume(ctx context.Context, feeInfo bool, pairs ...pairs.AssetPair) (res *TradeVolumeResponse, err error)

TradeVolume returns an associative array of trade volume. https://www.kraken.com/en-gb/help/api#get-trade-volume

func (*UserData) TradesHistory

func (u *UserData) TradesHistory(ctx context.Context, tradesReq TradesHistoryRequest) (res *TradesHistoryResponse, err error)

TradesHistory returns an array of trade info. https://www.kraken.com/en-gb/help/api#get-trades-history

type UserOrder

type UserOrder struct {
	Pair              pairs.AssetPair // Asset pair.
	Type              TradeBuySell    // Type of order (buy/sell).
	OrderType         OrderType       // Order type.
	Price             float64         // Price.
	Price2            float64         // Secondary price.
	Volume            float64         // Order volume in lots.
	Leverage          string          // Amount of leverage desired.
	OFlags            []OrderFlag     // List of order flags.
	StartTm           string          // Scheduled start time: 0 (now - default), +<n> (schedule start time <n> seconds from now) , <n> (unix timestamp of start time).
	ExpireTm          string          // expiration time 0 (no expiration - default), +<n> (expire <n> seconds from now) , <n> (unix timestamp of expiration time).
	UserRef           int             // User reference id.
	Validate          bool            // Validate inputs only.
	CloseOrderType    OrderType       // Type of closing order to add to system when order gets filled.
	ClosedOrderPrice  float64         // Price of closing order to add to system when order gets filled.
	ClosedOrderPrice2 float64         // Secondary price of closing order to add to system when order gets filled.
}

UserOrder represents a user request to add an order.

type UserTrade

type UserTrade struct {
	OrderTxid string       `json:"ordertxid"`
	Pair      string       `json:"pair"`
	Time      int64        `json:"time"`
	Type      TradeBuySell `json:"type"`
	OrderType OrderType    `json:"ordertype"`
	Price     float64      `json:"price"`
	Cost      float64      `json:"cost"`
	Fee       float64      `json:"fee"`
	Vol       float64      `json:"vol"`
	Margin    float64      `json:"margin"`
	Misc      string       `json:"misc"`
}

UserTrade represents a historical user trade.

type WithdrawInfoResponse

type WithdrawInfoResponse struct {
	Method string  `json:"method"`
	Limit  float64 `json:"limit"`
	Fee    float64 `json:"fee"`
}

WithdrawInfoResponse represents withdrawal information.

type WithdrawResponse

type WithdrawResponse struct {
	RefID string `json:"refid"`
}

WithdrawResponse represents the response to a withdraw funds request.

type WithdrawStatus

type WithdrawStatus struct {
	Method     string             `json:"method"`
	Aclass     string             `json:"aclass"`
	Asset      string             `json:"asset"`
	RefID      string             `json:"refid"`
	TxID       string             `json:"txid"`
	Info       string             `json:"info"`
	Amount     float64            `json:"float64"`
	Fee        float64            `json:"fee"`
	Time       int64              `json:"time"`
	Status     string             `json:"status"`
	StatusProp WithdrawStatusProp `json:"status-prop"`
}

WithdrawStatus represents the status of a withdrawal.

type WithdrawStatusProp

type WithdrawStatusProp struct {
	CancelPending bool `json:"cancel-pending"`
	Canceled      bool `json:"canceled"`
	CancelDenied  bool `json:"cancel-denied"`
	Return        bool `json:"return"`
	OnHold        bool `json:"onhold"`
}

WithdrawStatusProp contains additional status properties for a withdrawal.

type WithdrawStatusResponse

type WithdrawStatusResponse []WithdrawStatus

WithdrawStatusResponse represents a list of withdrawal statuses.

Directories

Path Synopsis
cmd
cmd

Jump to

Keyboard shortcuts

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