Code Monkey home page Code Monkey logo

kraken-go-api-client's Introduction

Kraken GO API Client

build status

A simple API Client for the Kraken Trading platform.

Example usage:

package main

import (
	"fmt"
	"log"

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

func main() {
	api := krakenapi.New("KEY", "SECRET")
	result, err := api.Query("Ticker", map[string]string{
		"pair": "XXBTZEUR",
	})

	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Result: %+v\n", result)

	// There are also some strongly typed methods available
	ticker, err := api.Ticker(krakenapi.XXBTZEUR)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(ticker.XXBTZEUR.OpeningPrice)
}

Contributors

  • Piega
  • Glavic
  • MarinX
  • bjorand
  • khezen

kraken-go-api-client's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kraken-go-api-client's Issues

Trade info totally broken

https://www.kraken.com/help/api#get-recent-trades
States in one ecample 'since' => '137589964200000000'));
Since is a 18 place string timestamp, not 10.
krakenapi.fo file has:
values.Set("since", strconv.FormatInt(since, 10))
Should be to 18, not 10.. or response has times offset by years.

Also beware kraken api docs state:
NOTE: the 'since' parameter is subject to change in the future: it's precision may be modified, and it may no longer be representative of a timestamp. The best practice is to base it on the 'last' value returned in the result set.

Could not execute request #5! (Response Content-Type is 'text/html', but should be 'application/json'.)

I am getting this result intermittently some times 6 times in a row with samples every 5 minutes:

Result: map[XXBTZEUR:map[h:[3200.00000 3228.90000] b:[3184.60000 1 1.000] c:[3188.50000 0.04743778] v:[106.82930320 6371.08316388] p:[3191.29123 3169.57439] t:[593 16441] a:[3188.20000 1 1.000] l:[3181.20000 3109.50000] o:3196.50000]]
2019/01/18 09:16:18 Could not execute request #5! (Response Content-Type is 'text/html', but should be 'application/json'.)

it will later work as many as 6 times before another failure.
I noticed it from a package that uses your client https://github.com/interstellar/kelp that is a trading bot for stellar.org trading platform. I put in a bug report there at kelp but was told it was not there code by the developers. I isolated the results coming from your code. I went and ran your main test and see the same results above.

I compiled your simple main test with go version go1.11.4 linux/amd64 running on Linux Mint

Sorry I'm not much of a go programmer so not sure I can be of much help to you. We are still making use of your client even in it's present state with just more samples and allowing up to 6 failures before we delete all offers.

Add function GetPairTickerInfo in type

Hello Beldur,
I saw that you were working on it again.

Can you create this function ? It's easier to use.

func (v *krakenapi.TickerResponse)GetPairTickerInfo(field string) (krakenapi.PairTickerInfo) {
r := reflect.ValueOf(v)
f := reflect.Indirect(r).FieldByName(field)
return f.Interface().(krakenapi.PairTickerInfo)
}

Kinds, regard

Change RefID to string

Hi, in types.go - the RefID for withdrawals was int but kraken returns a string. code should be:

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

([EGeneral:Bad data:User tier is missing]) Withdrawn Info

I'm just' trying to retrieve the withdrawn fee for some asset and coming across getting this error: ([EGeneral:Bad data:User tier is missing]). With the following code:

api := krakenapi.New(apiKey, apiSecret)

x := big.Float{}
x.SetPrec(3)
x.SetFloat64(0.725)
data, err := api.WithdrawInfo("XBT", "btc_testnet_with1", &x)
if err != nil {
log.Fatal(err)
}

fmt.Println(data)

Possible trade info improvements

Hi,

I think TradeResponse.Last shoud be a string and TradeInfo.Time should be a time.Time. Now both are typed as int64 and I think it's less than ideal.

For some time now Kraken trade response includes 4 digits of fractions to the trade time. This data gets lost when we convert it to int64.

Also, for me it seems Kraken intends the last value to be used as it is in the next request, so converting back and forth is unnecessary and possibly not very future proof. It will overflow in april of 2611, but Kraken can also change its content anytime, so I think it would be better not to presume that it can be represented as an int64.

If it makes sense, I'm more than happy to make the pull request fixing these issues.

Best regards,
Mate

Cannot get all data from TradesHistory and Ledgers

I can not retrieve all data when calling Query method. I only have 50 items although Kraken return 610 items (or 465 for other request) in count attribute.

params := map[string]string{
	"start": "1483449017",
}
result, err := api.Query("TradesHistory", params)

or

        params := map[string]string{"start": "1489151863"}
	result, err := api.Query("Ledgers", params)

Changing type of Order struct's numeric fields from float64 to string

I propose to update the Order struct

type Order struct {
as follow

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 string           `json:"vol_exec"`
	Cost           string           `json:"cost"`
	Fee            string           `json:"fee"`
	Price          string           `json:"price"`
	StopPrice      string           `json:"stopprice"`
	LimitPrice     string           `json:"limitprice"`
	Misc           string           `json:"misc"`
	OrderFlags     string           `json:"oflags"`
	CloseTime      float64          `json:"closetm"`
	Reason         string           `json:"reason"`
	TradesID       []string         `json:"trades"`
}

so we do not lose precision casting numeric values (eg Cost, Fee, Price, etc)

as a reminder a ClosedOrders response looks like this

{
    "error": [],
    "result": {
        "closed": {
            "AAAAAA-BBBBB-CCCCCC": {
                "refid": null,
                "userref": 1234567890,
                "status": "closed",
                "reason": null,
                "opentm": 1234567890.1234,
                "closetm": 1234567890.5678,
                "starttm": 0,
                "expiretm": 1234567890,
                "descr": {
                    "pair": "ETHEUR",
                    "type": "buy",
                    "ordertype": "market",
                    "price": "0",
                    "price2": "0",
                    "leverage": "none",
                    "order": "buy 1.13147800 ETHEUR @ market",
                    "close": ""
                },
                "vol": "1.13147800",
                "vol_exec": "1.13147800",
                "cost": "249.96",
                "fee": "0.64",
                "price": "220.92",
                "stopprice": "0.00000",
                "limitprice": "0.00000",
                "misc": "",
                "oflags": "fciq",
                "trades": [
                    "EEEEEE-FFFFF-GGGGGG"
                ]
            }
        },
        "count": 1
    }
}

TradesID is addressed in my current PR #47

Allow for custom return structs

As the API of kraken evolves (new crypto-currencies , response structure etc ... )
It would be helpful for users to be able to define their own response structs.
Currently these are "hidden".
For example in Balance call

// Balance returns all account asset balances
func (api *KrakenAPI) Balance() (*BalanceResponse, error) {
	resp, err := api.queryPrivate("Balance", url.Values{}, &BalanceResponse{})
	if err != nil {
		return nil, err
	}

	return resp.(*BalanceResponse), nil
}

Someone cannot get the balance for 'LINK' for example, because the BalanceResponse struct does not parse this field from the json response.

This method could be more generic, in order to accommodate current (i.e. for LINK) and future needs, without the need for the client to define ALL currencies upfront.

An possible adjustment could be the following :

// Balance returns all account asset balances
func (api *KrakenAPI) Balance(response interface{}) error {
	response, err := api.queryPrivate("Balance", url.Values{}, response)
	if err != nil {
		return err
	}
	return nil
}

I 've made some tests, and it seems to work nicely for the this example of client user code.

type BalanceResponse struct {
	ZEUR  float64 `json:"ZEUR,string"`
	LINK  float64 `json:"LINK,string"`
}

func (api *Remote) Balance() (*BalanceResponse, error) {
	resp := &BalanceResponse{}
	err := api.privateApi.Balance(resp)
	return resp, err
}

and its used as ...

balance, err := client.Api.Balance()

	if err == nil {
		println(fmt.Sprintf("balance = %v", balance.ZEUR))
		println(fmt.Sprintf("balance = %v", balance.LINK))
	}

Would this be an interesting enhancement ? I could look into refactoring corresponding methods in that direction.
And we could always leave the current struct for default use-cases.
What do you think ?

nill response from Trades

Sometimes lately, when making a Trades request i am getting the following error

panic: interface conversion: interface {} is nil, not []interface {}

goroutine 56 [running]:
github.com/beldur/kraken-go-api-client.(*KrakenAPI).Trades(0xc00007dda0, 0x9a6067, 0x6, 0x1663c1ef0f0ae825, 0x0, 0x0, 0x0)
	/home/ec2-user/Projects/free-coin/vendor/github.com/beldur/kraken-go-api-client/krakenapi.go:251 +0xa30

It seems it would be better to do a nil check, before casting the response ...

if v[pair] == nil {
    return nil, err
}
trades := v[pair].([]interface{})

Would it make sense to create a PR for this fix ?

Did anyone else encounter this one ?

Error `Could not execute request! (invalid character '<' looking for beginning of value)` is giving me a trouble

Hi,
I sometimes get error Could not execute request! (invalid character '<' looking for beginning of value).

This error is coming from function doRequest(): https://github.com/beldur/kraken-go-api-client/blob/master/krakenapi.go#L354

Problem that I have witnessed is that request was made successfully (AddOrder() was successfully), and lib returned this error. My script is retrying to make an AddOrder() call if error is returned from doRequest(), so you see my frustration when multiple AddOrder() return error, but they were succesfull :(

Feature: Add support for interval parameter to OHLC function

Hi, at the moment the OHLC function https://github.com/beldur/kraken-go-api-client/blob/master/krakenapi.go#L169 does not allow passing an interval to it, so is only possible to use the default value of "1" which limits the returned data quite a bit.

I did open #59 but then closed it because it would force everyone to specify an interval even when they actually want to use the default

I am not sure what the right way to handle this use case is

  • Using an args map[string]string make no sense, since the only other param supported is interval itself
  • Create a separate OHLCWithInterval function to handle all the current code in OHLC and have that one just call the new one with itnerval hardcoded to 1 - something like #60
  • Just add the new parameter as in my previous PR

I would be curious to know what you think

thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.