krakenapi

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2023 License: MIT Imports: 16 Imported by: 0

README

Kraken GO API Client

A simple API Client for the Kraken Trading platform.

This is a fork of kraken-go-api-client which uses strings instead of typed symbol constants.

Example usage:

package main

import (
	"fmt"
	"log"

	"github.com/wthorp/kraken-go-api-client"
)

func main() {
	api := krakenapi.New("KEY", "SECRET")

	ticker, err := api.Ticker("STORJUSD")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Bid price: %s\n", (*ticker)["STORJUSD"].Bid[0])
}

Documentation

Index

Constants

View Source
const (
	// APIURL is the official Kraken API Endpoint
	APIURL = "https://api.kraken.com"
	// APIVersion is the official Kraken API Version Number
	APIVersion = "0"
	// APIUserAgent identifies this library with the Kraken API
	APIUserAgent = "Kraken GO API Agent (https://github.com/beldur/kraken-go-api-client)"
)
View Source
const (
	MinimumREP  = 0.3
	MinimumXBT  = 0.002
	MinimumBCH  = 0.002
	MinimumDASH = 0.03
	MinimumDOGE = 3000.0
	MinimumEOS  = 3.0
	MinimumETH  = 0.02
	MinimumETC  = 0.3
	MinimumGNO  = 0.03
	MinimumICN  = 2.0
	MinimumLTC  = 0.1
	MinimumMLN  = 0.1
	MinimumXMR  = 0.1
	MinimumXRP  = 30.0
	MinimumXLM  = 300.0
	MinimumZEC  = 0.02
	MinimumUSDT = 5.0
)

These represent the minimum order sizes for the respective coins Should be monitored through here: https://support.kraken.com/hc/en-us/articles/205893708-What-is-the-minimum-order-size-

View Source
const (
	BUY    = "b"
	SELL   = "s"
	MARKET = "m"
	LIMIT  = "l"
)

actions constants

View Source
const (
	OTMarket              = "market"
	OTLimit               = "limit"                  // (price = limit price)
	OTStopLoss            = "stop-loss"              // (price = stop loss price)
	OTTakeProfi           = "take-profit"            // (price = take profit price)
	OTStopLossProfit      = "stop-loss-profit"       // (price = stop loss price, price2 = take profit price)
	OTStopLossProfitLimit = "stop-loss-profit-limit" // (price = stop loss price, price2 = take profit price)
	OTStopLossLimit       = "stop-loss-limit"        // (price = stop loss trigger price, price2 = triggered limit price)
	OTTakeProfitLimit     = "take-profit-limit"      // (price = take profit trigger price, price2 = triggered limit price)
	OTTrailingStop        = "trailing-stop"          // (price = trailing stop offset)
	OTTrailingStopLimit   = "trailing-stop-limit"    // (price = trailing stop offset, price2 = triggered limit offset)
	OTStopLossAndLimit    = "stop-loss-and-limit"    // (price = stop loss price, price2 = limit price)
	OTSettlePosition      = "settle-position"
)

OrderTypes for AddOrder

Variables

This section is empty.

Functions

This section is empty.

Types

type AddOrderResponse

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

AddOrderResponse response when adding an order

type AssetInfo

type AssetInfo struct {
	// Alternate name
	Altname string
	// Asset class
	AssetClass string `json:"aclass"`
	// Scaling decimal places for record keeping
	Decimals int
	// Scaling decimal places for output display
	DisplayDecimals int `json:"display_decimals"`
}

AssetInfo represents an asset information

type AssetPairInfo

type AssetPairInfo struct {
	// Alternate pair name
	Altname string `json:"altname"`
	// Asset class of base component
	AssetClassBase string `json:"aclass_base"`
	// Asset id of base component
	Base string `json:"base"`
	// Asset class of quote component
	AssetClassQuote string `json:"aclass_quote"`
	// Asset id of quote component
	Quote string `json:"quote"`
	// Volume lot size
	Lot string `json:"lot"`
	// Scaling decimal places for pair
	PairDecimals int `json:"pair_decimals"`
	// Scaling decimal places for volume
	LotDecimals int `json:"lot_decimals"`
	// Amount to multiply lot volume by to get currency volume
	LotMultiplier int `json:"lot_multiplier"`
	// Array of leverage amounts available when buying
	LeverageBuy []float64 `json:"leverage_buy"`
	// Array of leverage amounts available when selling
	LeverageSell []float64 `json:"leverage_sell"`
	// Fee schedule array in [volume, percent fee] tuples
	Fees [][]float64 `json:"fees"`
	// // Maker fee schedule array in [volume, percent fee] tuples (if on maker/taker)
	FeesMaker [][]float64 `json:"fees_maker"`
	// // Volume discount currency
	FeeVolumeCurrency string `json:"fee_volume_currency"`
	// Margin call level
	MarginCall int `json:"margin_call"`
	// Stop-out/Liquidation margin level
	MarginStop int `json:"margin_stop"`
}

AssetPairInfo represents asset pair information

type AssetPairsResponse

type AssetPairsResponse map[string]AssetPairInfo

AssetPairsResponse includes asset pair informations

type AssetsResponse

type AssetsResponse map[string]AssetInfo

AssetsResponse includes asset informations

type BalanceResponse

type BalanceResponse map[string]float64

BalanceResponse represents the account's balances (list of currencies)

type CancelOrderResponse

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

CancelOrderResponse response when cancelling and order

type ClosedOrdersResponse

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

ClosedOrdersResponse represents a list of closed orders, indexed by id

type DepositAddressesResponse

type DepositAddressesResponse []struct {
	Address  string `json:"address"`
	Expiretm string `json:"expiretm"`
	New      bool   `json:"new,omitempty"`
}

DepositAddressesResponse is the response type of a DepositAddresses query to the Kraken API.

type DepthResponse

type DepthResponse map[string]OrderBook

DepthResponse is a response from kraken to Depth request.

type FeeInfo

type FeeInfo struct {
	Fee        float64 `json:"fee,string"`
	MinFee     float64 `json:"minfee,string"`
	MaxFee     float64 `json:"maxfee,string"`
	NextFee    float64 `json:"nextfee,string"`
	NextVolume float64 `json:"nextvolume,string"`
	TierVolume float64 `json:"tiervolume,string"`
}

FeeInfo represents a fee information

type Fees

type Fees map[string]FeeInfo

Fees includes fees information for different currencies

type KrakenAPI

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

KrakenAPI represents a Kraken API Client connection

func New

func New(key, secret string) *KrakenAPI

New creates a new Kraken API client

func NewWithClient

func NewWithClient(key, secret string, httpClient *http.Client) *KrakenAPI

NewWithClient creates a new Kraken API client with custom http client

func (*KrakenAPI) AddOrder

func (api *KrakenAPI) AddOrder(pair string, direction string, orderType string, volume string, args map[string]string) (*AddOrderResponse, error)

AddOrder adds new order

func (*KrakenAPI) AssetPairs

func (api *KrakenAPI) AssetPairs() (*AssetPairsResponse, error)

AssetPairs returns the servers available asset pairs

func (*KrakenAPI) Assets

func (api *KrakenAPI) Assets() (*AssetsResponse, error)

Assets returns the servers available assets

func (*KrakenAPI) Balance

func (api *KrakenAPI) Balance() (*BalanceResponse, error)

Balance returns all account asset balances

func (*KrakenAPI) CancelOrder

func (api *KrakenAPI) CancelOrder(txid string) (*CancelOrderResponse, error)

CancelOrder cancels order

func (*KrakenAPI) ClosedOrders

func (api *KrakenAPI) ClosedOrders(args map[string]string) (*ClosedOrdersResponse, error)

ClosedOrders returns all closed orders

func (*KrakenAPI) DepositAddresses

func (api *KrakenAPI) DepositAddresses(asset string, method string) (*DepositAddressesResponse, error)

DepositAddresses returns deposit addresses

func (*KrakenAPI) Depth

func (api *KrakenAPI) Depth(pair string, count int) (*OrderBook, error)

Depth returns the order book for given pair and orders count.

func (*KrakenAPI) Ledgers

func (api *KrakenAPI) Ledgers(args map[string]string) (*LedgersResponse, error)

Ledgers returns ledgers informations

func (*KrakenAPI) OHLC

func (api *KrakenAPI) OHLC(pair string) (*OHLCResponse, error)

OHLC returns a OHLCResponse struct based on the given pair

func (*KrakenAPI) OpenOrders

func (api *KrakenAPI) OpenOrders(args map[string]string) (*OpenOrdersResponse, error)

OpenOrders returns all open orders

func (*KrakenAPI) Query

func (api *KrakenAPI) Query(method string, data map[string]string) (interface{}, error)

Query sends a query to Kraken api for given method and parameters

func (*KrakenAPI) QueryOrders

func (api *KrakenAPI) QueryOrders(txids string, args map[string]string) (*QueryOrdersResponse, error)

QueryOrders shows order

func (*KrakenAPI) Ticker

func (api *KrakenAPI) Ticker(pairs ...string) (*TickerResponse, error)

Ticker returns the ticker for given comma separated pairs

func (*KrakenAPI) Time

func (api *KrakenAPI) Time() (*TimeResponse, error)

Time returns the server's time

func (*KrakenAPI) TradeBalance

func (api *KrakenAPI) TradeBalance(args map[string]string) (*TradeBalanceResponse, error)

TradeBalance returns trade balance info

func (*KrakenAPI) TradeVolume

func (api *KrakenAPI) TradeVolume(args map[string]string) (*TradeVolumeResponse, error)

TradeVolume returns trade volume info

func (*KrakenAPI) Trades

func (api *KrakenAPI) Trades(pair string, since int64) (*TradesResponse, error)

Trades returns the recent trades for given pair

func (*KrakenAPI) TradesHistory

func (api *KrakenAPI) TradesHistory(start int64, end int64, args map[string]string) (*TradesHistoryResponse, error)

TradesHistory returns the Trades History within a specified time frame (start to end).

func (*KrakenAPI) WithClient

func (api *KrakenAPI) WithClient(httpClient *http.Client) *KrakenAPI

WithClient adds an HTTP client into the KrakenAPI

func (*KrakenAPI) Withdraw

func (api *KrakenAPI) Withdraw(asset string, key string, amount *big.Float) (*WithdrawResponse, error)

Withdraw executes a withdrawal, returning a reference ID

func (*KrakenAPI) WithdrawInfo

func (api *KrakenAPI) WithdrawInfo(asset string, key string, amount *big.Float) (*WithdrawInfoResponse, error)

WithdrawInfo returns withdrawal information

type KrakenApi

type KrakenApi = KrakenAPI

KrakenApi represents a Kraken API Client connection

type KrakenResponse

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

KrakenResponse wraps the Kraken API JSON response

type LedgerInfo

type LedgerInfo struct {
	RefID   string    `json:"refid"`
	Time    float64   `json:"time"`
	Type    string    `json:"type"`
	Aclass  string    `json:"aclass"`
	Asset   string    `json:"asset"`
	Amount  big.Float `json:"amount"`
	Fee     big.Float `json:"fee"`
	Balance big.Float `json:"balance"`
}

LedgerInfo Represents the ledger informations

type LedgersResponse

type LedgersResponse struct {
	Ledger map[string]LedgerInfo `json:"ledger"`
}

LedgersResponse represents an associative array of ledgers infos

type OHLC

type OHLC struct {
	Time   time.Time `json:"time"`
	Open   float64   `json:"open"`
	High   float64   `json:"high"`
	Low    float64   `json:"low"`
	Close  float64   `json:"close"`
	Vwap   float64   `json:"vwap"`
	Volume float64   `json:"volume"`
	Count  int       `json:"count"`
}

OHLC represents the "Open-high-low-close chart"

func NewOHLC

func NewOHLC(input []interface{}) (*OHLC, error)

NewOHLC constructor for OHLC

type OHLCResponse

type OHLCResponse struct {
	Pair string  `json:"pair"`
	OHLC []*OHLC `json:"OHLC"`
	Last float64 `json:"last"`
}

OHLCResponse represents the OHLC's response

type OpenOrdersResponse

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

OpenOrdersResponse response when opening an order

type Order

type Order struct {
	TransactionID  string           `json:"-"`
	ReferenceID    string           `json:"refid"`
	UserRef        int              `json:"userref"`
	Status         string           `json:"status"`
	OpenTime       float64          `json:"opentm"`
	StartTime      float64          `json:"starttm"`
	ExpireTime     float64          `json:"expiretm"`
	Description    OrderDescription `json:"descr"`
	Volume         string           `json:"vol"`
	VolumeExecuted 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 OrderBook

type OrderBook struct {
	Asks []OrderBookItem
	Bids []OrderBookItem
}

OrderBook contains top asks and bids.

type OrderBookItem

type OrderBookItem struct {
	Price  float64
	Amount float64
	Ts     int64
}

OrderBookItem is a piece of information about an order.

func (*OrderBookItem) UnmarshalJSON

func (o *OrderBookItem) UnmarshalJSON(data []byte) error

UnmarshalJSON takes a json array from kraken and converts it into an OrderBookItem.

type OrderDescription

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

OrderDescription represents an orders description

type PairTickerInfo

type PairTickerInfo struct {
	// Ask array(<price>, <whole lot volume>, <lot volume>)
	Ask []string `json:"a"`
	// Bid array(<price>, <whole lot volume>, <lot volume>)
	Bid []string `json:"b"`
	// Last trade closed array(<price>, <lot volume>)
	Close []string `json:"c"`
	// Volume array(<today>, <last 24 hours>)
	Volume []string `json:"v"`
	// Volume weighted average price array(<today>, <last 24 hours>)
	VolumeAveragePrice []string `json:"p"`
	// Number of trades array(<today>, <last 24 hours>)
	Trades []int `json:"t"`
	// Low array(<today>, <last 24 hours>)
	Low []string `json:"l"`
	// High array(<today>, <last 24 hours>)
	High []string `json:"h"`
	// Today's opening price
	OpeningPrice float64 `json:"o,string"`
}

PairTickerInfo represents ticker information for a pair

type QueryOrdersResponse

type QueryOrdersResponse map[string]Order

QueryOrdersResponse response when checking all orders

type TickerResponse

type TickerResponse map[string]PairTickerInfo

TickerResponse includes the requested ticker pairs

func (*TickerResponse) GetPairTickerInfo

func (v *TickerResponse) GetPairTickerInfo(pair string) PairTickerInfo

GetPairTickerInfo is a helper method that returns given `pair`'s `PairTickerInfo`

type TimeResponse

type TimeResponse struct {
	// Unix timestamp
	Unixtime int64
	// RFC 1123 time format
	Rfc1123 string
}

TimeResponse represents the server's time

type TradeBalanceResponse

type TradeBalanceResponse struct {
	EquivalentBalance         float64 `json:"eb,string"`
	TradeBalance              float64 `json:"tb,string"`
	MarginOP                  float64 `json:"m,string"`
	UnrealizedNetProfitLossOP float64 `json:"n,string"`
	CostBasisOP               float64 `json:"c,string"`
	CurrentValuationOP        float64 `json:"v,string"`
	Equity                    float64 `json:"e,string"`
	FreeMargin                float64 `json:"mf,string"`
	MarginLevel               float64 `json:"ml,string"`
}

TradeBalanceResponse struct used as the response for the TradeBalance method

type TradeHistoryInfo

type TradeHistoryInfo struct {
	TransactionID string  `json:"ordertxid"`
	PostxID       string  `json:"postxid"`
	AssetPair     string  `json:"pair"`
	Time          float64 `json:"time"`
	Type          string  `json:"type"`
	OrderType     string  `json:"ordertype"`
	Price         float64 `json:"price,string"`
	Cost          float64 `json:"cost,string"`
	Fee           float64 `json:"fee,string"`
	Volume        float64 `json:"vol,string"`
	Margin        float64 `json:"margin,string"`
	Misc          string  `json:"misc"`
}

TradeHistoryInfo represents a transaction

type TradeInfo

type TradeInfo struct {
	Price         string
	PriceFloat    float64
	Volume        string
	VolumeFloat   float64
	Time          int64
	Buy           bool
	Sell          bool
	Market        bool
	Limit         bool
	Miscellaneous string
}

TradeInfo represents a trades information

type TradeVolumeResponse

type TradeVolumeResponse struct {
	Volume    float64 `json:"volume,string"`
	Currency  string  `json:"currency"`
	Fees      Fees    `json:"fees"`
	FeesMaker Fees    `json:"fees_maker"`
}

TradeVolumeResponse represents the response for trade volume

type TradesHistoryResponse

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

TradesHistoryResponse represents a list of executed trade

type TradesResponse

type TradesResponse struct {
	Last   int64
	Trades []TradeInfo
}

TradesResponse represents a list of the last trades

type WithdrawInfoResponse

type WithdrawInfoResponse struct {
	Method string    `json:"method"`
	Limit  big.Float `json:"limit"`
	Amount big.Float `json:"amount"`
	Fee    big.Float `json:"fee"`
}

WithdrawInfoResponse is the response type showing withdrawal information for a selected withdrawal method.

type WithdrawResponse

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

WithdrawResponse is the response type of a Withdraw query to the Kraken API.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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