GithubHelp home page GithubHelp logo

dominiktraxl / pykrakenapi Goto Github PK

View Code? Open in Web Editor NEW
224.0 13.0 53.0 179 KB

A python implementation of the Kraken API.

License: GNU Lesser General Public License v3.0

Python 100.00%
python finance kraken cryptocurrency exchange api-client

pykrakenapi's Introduction

Warning

This repository is not maintained actively at the moment.

pykrakenapi

Implements the Kraken API methods using the low-level krakenex python package. See

https://www.kraken.com/help/api

and

https://github.com/veox/python3-krakenex

Whenever convenient, methods return pandas.DataFrame objects. Also implements a call rate limiter based on your Kraken tier level, as well as automatic retries on HTTPErrors/Kraken API Errors.

Quick Start

pykrakenapi can be installed via pip from PyPI

$ pip install pykrakenapi

Then, import and get started with:

>>> from pykrakenapi import KrakenAPI
>>> help(KrakenAPI)

pykrakenapi requires Python >= 3.3, krakenex >= 2.0.0 and pandas. These requirements should be installed automatically via pip.

Example

import krakenex
from pykrakenapi import KrakenAPI
api = krakenex.API()
k = KrakenAPI(api)
ohlc, last = k.get_ohlc_data("BCHUSD")
print(ohlc)
                           time    open    high     low   close    vwap       volume  count
dtime
2017-11-19 18:31:00  1511116260  1175.0  1175.0  1175.0  1175.0     0.0   0.00000000      0
2017-11-19 18:30:00  1511116200  1175.0  1175.0  1175.0  1175.0     0.0   0.00000000      0
2017-11-19 18:29:00  1511116140  1175.0  1175.0  1175.0  1175.0  1175.0   0.30000000      1
2017-11-19 18:28:00  1511116080  1171.2  1175.0  1170.3  1170.3  1174.9  10.02137467      3
2017-11-19 18:27:00  1511116020  1166.4  1171.2  1166.4  1171.2  1171.2   0.20043000      1
...                         ...     ...     ...     ...     ...     ...          ...    ...
2017-11-19 06:36:00  1511073360  1217.5  1217.5  1217.5  1217.5     0.0   0.00000000      0
2017-11-19 06:35:00  1511073300  1219.7  1219.7  1217.5  1217.5  1218.8   2.60803000      5
2017-11-19 06:34:00  1511073240  1221.3  1221.3  1221.3  1221.3     0.0   0.00000000      0
2017-11-19 06:33:00  1511073180  1220.4  1221.3  1210.7  1221.3  1216.3  17.37500000     11
2017-11-19 06:32:00  1511073120  1222.0  1222.0  1222.0  1222.0     0.0   0.00000000      0

[713 rows x 8 columns]

Documentation

See the docstrings of the methods of the KrakenAPI class.

>>> from pykrakenapi import KrakenAPI
>>> help(KrakenAPI)

FAQ

  • Why is my order not executed? Why can't I see my order in Kraken?

Kraken's API "Add standard order" call enables a validate only feature that defaults to True here. In order to have your order executed, try with validate=False.

k.add_standard_order(pair="ATOMXBT", type="buy", ordertype="limit", volume="420.0", price="0.00042", validate=False)

Development

This package should be considered beta state, since some methods have not been properly tested yet. Contributions in any way, shape or form are welcome!

Bug Reports

To search for bugs or report them, please use the bug tracker: https://github.com/dominiktraxl/pykrakenapi/issues

Licence

Distributed with a GNU GPL:

Copyright (C) 2017 pykrakenapi Developers
Dominik Traxl <[email protected]>

pykrakenapi's People

Contributors

dknodel avatar dominiktraxl avatar eifinger avatar fedelaport avatar gonmator avatar hugodemenez avatar jdddog avatar jonnymaserati avatar mans17 avatar nartb avatar noamlerner avatar pastorjordi avatar r-stiller avatar rc0r avatar sstoefe avatar tim-vrhn avatar

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

pykrakenapi's Issues

Request help for: KrakenAPIError: ['EGeneral:Invalid arguments:ordertype']

Dominik,

 Hi, thanks for the awesome library, I was hoping you could help me understand why do I keep getting the Error: invalid arguments: 'ordertype' ?

my args for k.add_standard_order() would be:
('xbtusd', 'buy', 'limit', '.002', price='8900', leverage='5', validate=True, trading_agreement='agree')
Is there a way for me to validate my function call without testing using live execution?
Thanks in advance,
Xavier

`get_ohloc_data` method and the `since` argument

I am trying to pull OHLC data beyond the 720-period limit for a backtesting engine. The Kraken API explains that this can be done by setting the since argument to the earliest datetime and using the last parameter that is returned to make subsequent calls to the REST API. However, the current behavior returns the most recent 720 periods *regardless of what unixtime value I call. Is this a known issue with the Kraken Rest API itself or an issue here with the get_ohlc_data method? Thanks for the help!

Documentation Links:
https://docs.kraken.com/rest/#operation/getOHLCData
https://support.kraken.com/hc/en-us/articles/218198197-How-to-retrieve-historical-time-and-sales-trading-history-using-the-REST-API-Trades-endpoint-

Unclosed socket error

Hi,
after execution of a Python script that tests pykrakenapi together with some other Web3.py code I get an error:
sys:1: ResourceWarning: unclosed <socket.socket fd=7, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('192.168.1.64', 54209), raddr=('104.16.211.191', 443)>
What should be done to avoid it? Thanks.

return a dict for get_trade_volume()

First, great wrapper for the kraken API, thank you!

This is a suggestion, not an issue... I think it'd be nicer to return a dict from the get_trade_volume method since the result would then not require referencing the API or the docstring to figure out what the values are. I get that you're converting the fees to a DataFrame (although for a single row this seems a bit overkill?) but I don't get the logic of returning the results as a list that needs indexing?

So instead maybe:

return {
    'currency': currency,
    'volume': volume,
    `fees`: fees,
    'fees_maker': fees_maker
}

I think I'd actually be okay with just returning res['result'], although converting the fees data to float is nice.

'consolidation' input for get_open_positions() is not inlcuded

First off, great work! I find this library extremely helpful in navigating Kraken's API, especially where their documentation may be lacking a little.

The get_open_positions() function does not have the input 'consolidation' included. While I am not entirely sure what Kraken's intent on this is by reading the docs, I can only assume it means it consolidates all your open positions to one average position based on a 'market' supplied as the input definition. I.e.- if you had two open XETHZUSD positions, it would consolidate those to one average XETHZUSD position.

Perhaps this is something that Kraken recently added to their API, but I was curious if there were plans to add it to pykrakenapi anytime soon? Playing around with it myself I can't seem to make head or tails of it, so maybe it is more of an upstream issue, but I can't tell.

Error classes - should I need to declare them?

Hello Dominik, first thanks for the work you have done!

I am new to Python so apologize if this is obvious. I have some try-except blocks in my code, however, noticed I was getting an error saying HTTPError, KrakenAPIError and CallRateLimitError are not defined when the except block was run.

I have had to import HTTPError and declare the others manually in my script for them to function correctly, is this normal behaviour?

Thanks.

getting KrakenAPIError: ['EAPI:Invalid nonce'] w/ get_account_balance() and get_trade_volume()

api = krakenex.API()
api.load_key(KeyPath)
k   = KrakenAPI(api)

Balance = k.get_account_balance()
TradeVol = k.get_trade_volume()

Both functions are returning:
KrakenAPIError: ['EAPI:Invalid nonce']

Other functions like get_tradable_asset_pairs() and get_ohlc_data('XBTUSD') are working just fine.

As far as I know, get_account_balance() worked for me a few days ago.

Thank you for the help

Add standart order not openning orders

Hi,

I 've no problem with using other private endpoints (get_account_balance, get_closed_orders)
So I'm sure API keys are valid. However I couldn't open any single order with using add_standard_order. I tried both market and limit executions. I don't receive any error message but I don't get txid also.
api=krakenex.API(key=data_set["key"], secret=data_set["secret"]) k=KrakenAPI(api) result_order_limit=k.add_standard_order(pair="XETHXXBT", type="sell", ordertype="limit", price="0.02100",volume="0.02") print(result_order_limit)

{'descr': {'order': 'sell 0.02000000 ETHXBT @ limit 0.02100'}}

I also checked my api keys on kraken api page they valid and have permission to open position.

query_orders_info throws exception ("cannot convert float NaN to integer")

I have the problem that calling query_orders_info() with the txid of an transaction that has not been closed yet results in an ValueError: cannot convert float NaN to integer. This is caused by the code in pykrakenapi/pykrakenapi.py beginning in line 1203:

            for col in ['closetm', 'expiretm', 'opentm', 'starttm']:
                if col in orders:
                    orders.loc[:, col] = orders[col].astype(int)

The astype(int)-method obviously does not expect NaN values which are returned from the request. My suggested quick fix would be to treat these columns as float, not int. (Which, in my case is fine, because my code does not depend on these columns being integer values.)

add_standard_order : Post Only

I am trying to add a post only setting for limit orders and seem to be having trouble finding the right syntax. Thee is no example in the code and kraken's api docs don't show anything either.

The post only setting should be in the form of a comma-delimited list in the oflags parameter. I can not seem to get that to work. Any thoughts?

Conditional close not working when placing order

Hi,
I have found an issue with add_standard_order()
The Kraken API accepts ugly parameters as "close[ordertype]" and "close[price]".
Since you cant use [] in python arguments, the function add_standard_order() takes close_ordertype=None, close_price=None, as arguments.
The function parses parameters as this:
data = {arg: value for arg, value in locals().items() if arg != 'self' and value is not None}
So the API is receiving "close_ordertype" instead of "close[ordertype]".
I am wrong??? I will try to fix it.
maybe some simple hardcoding like:
data["close[ordertype]"] = data["close_ordertype"]

Public call rate limiter consider first call is too fast

Hi,

Like the title says, I think the last change causes pykrakenapi to consider that the first public call is too fast, even if it's the first one.

In a second thought, is it possible to keep the call rate limiter, public or private, but silence it so it doesn't "spam" the console ?

Pandas requirement

Hi there,

Tried to run the help:
from pykrakenapi import KrakenAPI
help(KrakenAPI)

But this gave an error ImportError: No module named 'pandas'

Easily resolved this by installing pandas: pip install pandas, but maybe an idea to add this to the package requirements itself or mention in the README that it is required to be present?

EGeneral:Invalid arguments:ordertype

I'm trying to place an order with:

response = k.add_standard_order(pair='ETHUSD', type='buy', ordertype ='stop-loss-profit', volume='0.03116', price='3007.3', price2='3337.3', leverage ='2', validate=True) print(response)

Output

Error placing order: ['EGeneral:Invalid arguments:ordertype']

Please help me out stop-loss-profit is not working

Call rate limiter incomprehension

Hi !

I noticed something with the call rate limiter.
If I put "None" for the tier, when I create the API, I got this error if I make too much calls :
attempt: 000 | ['EAPI:Rate limit exceeded']
But if I put "Intermediate" or even "Starter" I have the exact same error.
The error also happens with "Pro".

My account is "Intermediate"

What's happening ?

Edit : I saw here that the Counter Decrease per second is 0.5. Would that be because of that ? (That doesn't explain the same error in "Starter" though). This implementation uses the Rest API, right ?

Edit : I found that ['EAPI:Rate limit exceeded'] is an error coming from the API itself. I thought it was coming from your implementation. That means that the implementation + my code are too fast for the API (as I also have a counter implemented in my side) ?

Edit : Alright. I found that the errors come from public calls and not private ones. So it means that my implementation of a public counter stinks. I don't know if your implementation have one so I'll work on it on my side. I think we can close this issue.

Add support for 2-Factor Auth

Currently, it looks like a lot of functions accept the argument otp, but this argument is never used in the underlying logic. This means that these API calls fail if a user has 2FA enabled for the API. Turning off 2FA fixes the issue, but it's a security risk!

I think that fixing this would be easy. Everytime we call self.api.query_private, we could pass in the otp in the data argument (the calls currently leave this out because it defaults to None). This fits in with the API documentation from Kraken, take a look at the POST data box. If you look at the underlying krakenex library, you'll see they do keep the nonce in the data object as described in the API docs. So if we pass the otp in there as well, it would store the data perfectly for signing.

However, this would also require a change on the krakenex side. If you take a look at the _sign method here, they only use the nonce to sign. It would be very simple to also add the otp to sign it, pretty sure it would just be a string concat.

Let me know what you think. I haven't mentioned this to the krakenex community, but I can test it locally if you would like.

add_standard_order() is not working

Here's the code:

buy = k.add_standard_order("XXBTZUSD", "buy", "market", 0.002)

print(buy)

And when run, it prints {'descr': {'order': 'buy 0.00200000 XBTUSD @ market'}}

However, my account never reflects that I'm submitting an order at all. My API key has all permissions.

Is there something I'm doing wrong?

EOrder:Invalid position

actualTradeID = str(['SOME-REF-ID'])
actualTrade = k.get_open_positions(actualTradeID)

actualTradeID is of str type and it was previously of type list. If I put actualTradeID in get_open_positions while keeping its list type, it returns me the same error.

['SOME-REF-ID'] is the exact ID of an open position.

Invalid API Key

Versions

OS: w10  
Python: 3.6  
krakenex: 2.1.0
pykrakenapi: 0.1.5

What are you trying to achieve?

Getting balance of an asset with pykrakenapi

# code sample
import krakenex
from pykrakenapi import KrakenAPI

api = krakenex.API()
api.load_key('key.key')

k = KrakenAPI(api)

print(k.get_account_balance(data['base']))

What do you expect to happen?

It prints a number

What happens instead?

I get the error that my API Key is invalid

# error message
attempt: 000 | ['EAPI:Invalid key']
attempt: 001 | ['EAPI:Invalid key']
attempt: 002 | ['EAPI:Invalid key']

etc.
It's a completely new API Key 2FA for it is disabled

'EGeneral:Invalid arguments:ordertype' error with some order types

Versions
OS: Windows 10
Python: 3
krakenex:
I am able to achieve market and limit orders with code:
myorder = k.add_standard_order(pair = tradepair,type = 'sell',ordertype = 'market',volume = buylots, price = myprice)

But when I try to put a stop loss or trailing stop order with equivalent code:
myorder = k.add_standard_order(pair = tradepair,type = 'sell',ordertype = 'trailing-stop',volume = buylots, price = myprice)

I get an error "KrakenAPIError: ['EGeneral:Invalid arguments:ordertype']"
Please help.

Key error in get_recent_trades.

trades = pd.DataFrame(res['result'][pair]) KeyError: 'USDTUSD'
The key actually is USDTZUSD. So the approach to get this working is adding '-' between base and quote.
So the pair should be 'USDT-USD' then the function queries the API using the string replace with '-' by '' and the key to dictionary would be the replace of '-' with 'Z'

Weird issue, no attribute 'factor'

It's not linked to this package, as the same working is not throwing any error on different oses. But I'm searching where I can in case someone has an idea.

When testing my code on Archlinux, I got AttributeError: 'KrakenAPI' object has no attribute 'factor'. It's impossible, as I tested the same code on three other oses (Manjaro, which is Arch based, Windows 7 and Windows 10) AND I reviewed the code and self.factor is initialized in the same class as the function where it's used.

In addition, the function throwing the error (get_recent_trades()) was used in an ancient version of the code and worked flawlessly on Arch.

So it seems I made a modification on Arch that broke something (I don't know what as the error makes no sense at all)

Also, the code is REALLY slow on Arch.

I'll update this issue as soon as I find something.

EDIT : I tried running my code on the LTS kernel, same issue. It's not coming from Arch, I'm pretty sure. It surely comes from a modification I made but I can't imagine what could cause something that weird.

EDIT : I did solve my problem by creating a virtual environment on the USB stick that carries my stick.

The venv and the packages installed in it works as they should on Manjaro and on Arch.

It appears my python installation was messed up (and for good reason, I installed packages with pip (probably sudoed pip) globally and it surely collided with the packages installed by Arch).

So the solution is either making a clean install of python and the packages or making a virtual environment with only the packages you want (I suggest option 2).

EAPI:Invalid key

Hello !

I'm trying to make real trades but I get this error.
I tried remaking a key, it didn't work.
I have valide="False" in my code.
I don't kow what to do now. I'll ask Kraken support, to see if it's on their side or on the implementation of the API (or if it's my fault, which I suppose it is but I don't understand it)
If someone as an idea here, can you share it please ?

EDIT (23/10/2019) : I reinstalled everything and made a little script :

import krakenex
from pykrakenapi import KrakenAPI
from pykrakenapi.pykrakenapi import KrakenAPIError

krakenkey = "kraken.key"
api = krakenex.API()
api.load_key(krakenkey)
k = KrakenAPI(api)
res = k.get_account_balance()
print("res :", res)
res = k.add_standard_order("XXBTZEUR", 'buy', 'market', "0.002", price=None, price2=None, leverage=2,
                           oflags=['viqc', 'fciq'], starttm=0, expiretm=0, userref=None, validate=False,
                           close_ordertype='stop-loss', close_price='-' + "0.5" + '%', close_price2=None)
print("res :", res)

Here's the output :

res :              vol
ZEUR   a number
XXBT   a number
XXRP    a number
XLTC    a number
XETH    a number
XETC    a number
BCH     a number
Traceback (most recent call last):
  File "F:\Mega\testApiKraken\test.py", line 11, in <module>
    res = k.add_standard_order("XXBTZEUR", 'buy', 'market', "0.002", price=None, price2=None, leverage=2,
  File "C:\Users\MyName\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pykrakenapi\pykrakenapi.py", line 1897, in add_standard_order
    raise KrakenAPIError(res['error'])
pykrakenapi.pykrakenapi.KrakenAPIError: ['EAPI:Invalid key']

So it seem that only adding an order is raising an error.
I probably did something wrong, but I can't see what.

['EAPI:Invalid signature']

Hi,

I suppose this issue is linked to #22 but as I don't really know, I post a new issue.

So, using krakenex works well for the signature but as I pass the API to pykrakenapi, the signature becomes invalid.

My code is really simple, so the issue should be raising for anyone. If not, just tell me and I will check what's not working with my PC.

Thank you for your work !

get_ticker_information

Hi. Thanks for the great work on this.
There might be a little problem with the get_ticker_information function - it's taking a list of tickers as an input, but only seems to return a single row in the output dataframe.
Sorry in advance if I missed/misunderstood anything

get_ohlc_data: 0 volume on a particular date

Hi!

I just noticed an error when fetching OHLC values from Kraken. The volume is 0 on the 24th July 2021, and O, H, L, and C values are the same.

pykraken_api.get_ohlc_data("ADAEUR", interval="1440", ascending=True, since=1558044000)

I also tried removing the 'since' param, but no luck:

pykraken_api.get_ohlc_data("ADAEUR", interval="1440", ascending=True)

Please see the attached screenshot:

ohlc_error

Is there anything I could do to get the correct values?

Thank you!

fetching order book or order history?

Hello,

Have been searching for a simple Kraken API library and have come across yours and ccxt, but ccxt seems to be missing some functionality that I need.

I just need to be able to fetch my orders (open or closed) or fetch order history along with being able to place orders.

Is there an example of your API doing this?
Thanks in advance

OHLC prices aren't the real ones

Hi !

When I get a OHLC data frame, the prices aren't the same as showed on kraken, or on tradingview (which seems to be the same on both).

api = krakenex.API()
krakenkey = "kraken.key"
api.load_key(krakenkey)
k = KrakenAPI(api)
ohlc, last = k.get_ohlc_data("BCHUSD", 15)
print("ohlc :", ohlc)

If I compare the prices, they aren't the same.

Orders not beeing executed

Hi,

I'm trying to execute an order, with add_standard_order.

I know, it's written that it is untested, that's also why I test it =), here are my results :
when used with validate=True, it works (when Kraken is online ^^)

And when I put validate=False, I expect the order to be created, but it never seems to happen : I get the exact same result when validate is set to True. No order is created on Kraken, and I get the same output from the API (when I should expect something like a TXID ?)

here is the code :

res =  k.add_standard_order(pair=string_pair, type="buy", ordertype="limit", volume=string_vol, price=string_price, userref=42, validate=False)
print (res)

Output :

{'descr': {'order': 'buy 300.00000000 XLMXBT @ limit 0.00001021'}}

Looking at your code, you seem :

  • not to want to "hammer" orders with "@callratelimiter" that is a good idea to avoid having several orders put at once =)
  • not to force my input to validate=True, that was my first idea since the result is quite the same.

=> from what I see, I have to "blame" Kraken on this issue. Did I miss something ?

Adding Order via add_standard_order

Hi,

I just played around a little bit with the API. I could get price information and account balance.

Then I tried to add an order with "add_standard_order", which didn't work for me. As return value I get a description of my order, but in my Kraken Account nothing happens. Also, because I have no funds at all I would have expected an error message , e.g. insufficient funds.

Is there anything I have to pay attention to in order for it to work to place orders via the API?

Thank you!

Typo error with get_order_book

What are you trying to achieve?

Call the get_order_book function.

# code sample

api = krakenex.API(APIPublic, APIPrivate)
k = KrakenAPI(api)
k.get_order_book('XETHZEUR','10','True')


The relevant function is:


    def get_order_book(self, pair, count=100, ascending=False):
        """Get order book (market depth).

        Return a ``pd.DataFrame`` for both asks and bids for a given pair.

        Parameters
        ----------
        pair : str
            Asset pair to get market depth for.

        count : int, optional (default=100)
            Maximum number of asks/bids. Per default, get the latest 100
            bids and asks.

        ascending : bool, optional (default=False)
            If set to True, the data frame will be sorted with the most recent
            date in the last position. When set to False, the most recent date
            is in the first position.

        Returns
        -------
        asks : pd.DataFrame
            The ask side table.
            index = datetime
            price
            volume
            time (unixtime)

        bids : pd.DataFrame
            The bid side table.
            index = datetime
            price
            volume
            time (unixtime)

        Raises
        ------
        HTTPError
            An HTTP error occurred.

        KrakenAPIError
            A kraken.com API error occurred.

        CallRateLimitError
            The call rate limiter blocked the query.

        """

        # create data dictionary
        data = {arg: value for arg, value in locals().items() if
                arg != 'self' and value is not None}

        # query
        res = self.api.query_public('Depth', data=data)

        # check for error
        if len(res['error']) > 0:
            raise KrakenAPIError(res['error'])

        # create dataframe
        asks = pd.DataFrame(res['result'][pair]['asks'])
        bids = pd.DataFrame(res['result'][pair]['bids'])

        # column names
        cols = ['price', 'volume', 'time']

        if not asks.empty:
            asks.columns = cols
            asks['dtime'] = pd.to_datetime(asks.time, unit='s')
            asks.sort_values('dtime', ascending=ascending, inplace=True)
            asks.set_index('dtime', inplace=True)

     
    **if not bids.emtpy:**
            bids.columns = cols
            bids['dtime'] = pd.to_datetime(bids.time, unit='s')
            bids.sort_values('dtime', ascending=ascending, inplace=True)
            bids.set_index('dtime', inplace=True)

        return asks, bids

What do you expect to happen?

I expect 2 DataFrames to returned for Asks and Bids.

At least some other functions from the same library DO work.

What happens instead?

An error results. From my understanding, the API exchange happens successfully, because giving an invalid trading pair name gives an API error from their server. The 'asks' dataframe is filled successfully, but there is then a problem with the 'bids' dataframe as the line

if not bids.emtpy:

causes an error.

# error message

if not bids.emtpy:
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'emtpy'

valueError (timeframe) when using get_ohlc_data()

Hello, when running the basic test code shown on the main page of the distro:

api = krakenex.API()
k = KrakenAPI(api)
ohlc, last = k.get_ohlc_data("BCHUSD")
print(ohlc)

The following error is raised.

Traceback (most recent call last):
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 893, in _validate_frequency
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "fatFingerKraken.py", line 101, in <module>
    ohlc, last = k.get_ohlc_data("BCHUSD")
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pykrakenapi/pykrakenapi.py", line 53, in wrapper
    result = func(*args, **kwargs)
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pykrakenapi/pykrakenapi.py", line 100, in wrapper
    result = func(*args, **kwargs)
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pykrakenapi/pykrakenapi.py", line 602, in get_ohlc_data
    ohlc.index.freq = str(interval) + 'T'
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/datetimelike.py", line 100, in freq
    self._data.freq = value
  File "/Users/brian/opt/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 831, in freq
    self._validate_frequency(self, value)
  File "/Users/gg/opt/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 907, in _validate_frequency
    infer=inferred, passed=freq.freqstr
ValueError: Inferred frequency -1T from passed values does not conform to passed frequency T

Any help poss on how to fix this? Cheers

User Staking

Any plans to add the User Staking endpoints?

Seems this would be simple enough to add?

Lib doesn't handle properly a request for which the result dataframe is empty

Just an example that made me notice the problem: I tried to get all the withdrawal entries from the ledger of my account. But there is no such entry. The lib crashes by trying to access some attribute of the dataframe that doesn't exist. It would be nice if the lib just return None in this case.

I guess the problem is the same for all the requests.

query_private() got an unexpected keyword argument 'data'

I'm trying to get account balance like so:

import krakenex
from pykrakenapi import KrakenAPI
api = krakenex.API()
krakenkey = "kraken.key"
api.load_key(krakenkey)
k = KrakenAPI(api)
balance = k.get_account_balance()
print(balance)

and get the following:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-c65beab1b420> in <module>
----> 1 k.get_account_balance()

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pykrakenapi/pykrakenapi.py in wrapper(*args, **kwargs)
     51         while True:
     52             try:
---> 53                 result = func(*args, **kwargs)
     54                 return result
     55             except CallRateLimitError as err:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pykrakenapi/pykrakenapi.py in wrapper(*args, **kwargs)
    131                         try:
    132                             self.api_counter += incr
--> 133                             result = func(*args, **kwargs)
    134                             return result
    135                         except (HTTPError, KrakenAPIError) as err:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pykrakenapi/pykrakenapi.py in get_account_balance(self, otp)
    855 
    856         # query
--> 857         res = self.api.query_private('Balance', data=data)
    858 
    859         # check for error

TypeError: query_private() got an unexpected keyword argument 'data'

but when I use Kraken's api I can get a balance although with an error:
balance = api.query_private('Balance') gives the following {'error': [], 'result': {'ZUSD': 'My very large balance bc I am not poor', 'XXBT': 'touche'}}

I thought it might be my kraken.key but I put the key and secret on their own lines??

Thanks for all your hard work!

get_account_balance() error

get_account_balance() is returning a result

pi\pykrakenapi.py", line 825, in get_account_balance
balance = pd.DataFrame(index=['vol'], data=res['result']).T
KeyError: 'result'

Unable to add buy limit order

Hi there,

Thanks for building this package!

I'm finding that I can't submit an order using:
kraken_client.add_standard_order(pair='XXBTZCAD',type='buy',ordertype='limit',volume=1,price=100)

output = {'descr': {'order': 'sell 0.01000000 XBTCAD @ limit 100000.0'}}

Any ideas why this may be? I have checked the permissions on my API keys and the other functions in the package seem to work fine for me.

Thank you.

add_standard_order

I am trying to test out the order functionality and I am not able to get an order to generate. There are no errors that come up, and the response is only the 'descr' dictionary of the order details.

I tried typing in the incorrect symbol and I got an error back
I tired typing an incorrect order type and I got an error back
I tried typing an incorrect side (buy/sell) and got an error back
I tried using a volume value smaller than the threshold and got an error back
I tried to test cancel an order, and that worked.

for whatever reason, if I put a very large value for volume, I do NOT get an error back.

I have tried all sorts of combinations to get this to work and think I have run out of ideas. Any help would be appreciated.

the exact code used:
order = k.add_standard_order(pair='ETHUSD', type='sell', ordertype='limit', volume=".02", price='1400.00')

Public calls and private calls should be counted separately

According to
https://support.kraken.com/hc/en-us/articles/206548367-What-is-the-API-call-rate-limit-
there are two different counters. One works for public calls and is IP based, and basically you cannot make more than one request a second. A second counter is for private calls and is a more complicated function explained there. At least this was my understanding. I have actually wrote a bot that had two threads, one that would ping kraken once per second to get the public values. And then in another thread I would be threading. So I am quite confident that I am correct.

This is important because this is sensibly more than if you count public calls and private calls within the same limit. It also makes sense, as couinting them together would mean that a better programmer would simply call the public calls from a different IP and have an edge over more normal programmers.

All this to say that we should not count together public and private calls.

Add standard order

Having issues placing an order on Kraken.

My code:
`buyOrder = k.add_standard_order(pair="XXRPXXBT", type="buy", ordertype="market", volume="31", price = "0.00009160")
print(buyOrder)

orders = k.get_open_orders()
print(orders)`

There's no orders getting placed, and no errors messages.

average market price for a given volume

I find it a bit weird that there's no call to return the current market price (average price) for a volume trade (at least I can't find anything) in the API, so I've written one for a class I'm writing. I'm happy to pass this on if you want to modify it to fit into your code, else I can create a branch and insert it via an pull request?

Maybe this is out of scope for an API wrapper, but let me know...

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.