pythonrestkraken.com

PyKrakenAPI KeyError on pd.DataFrame(res['result'][pair])


This problem exists in pykrakenapi version 0.1.8, but is fixed in 0.1.9

When using Kraken's REST API together with pykrakenapi, some trading pairs (such as the very popular XBTUSD) produce a KeyError, even though the pair exists in Kraken's Asset Pair endpoint.

For example, the following code

import krakenex
from pykrakenapi import KrakenAPI

timestamp = 1546300800000000000
pair = 'XBTUSD'

trades = k.get_recent_trades(pair=pair, since=timestamp, ascending=True)

results in the following error:

File "C:\Users\TimStack\PycharmProjects\Kraken\lib\site-packages\pykrakenapi\pykrakenapi.py", line 704, in get_recent_trades
trades = pd.DataFrame(res['result'][pair])
KeyError: 'XBTUSD'

The XBTUSD pair does show up in the AssetPairs endpoint, however: enter image description here


Solution

  • This issue is a result of Kraken using a different name for the trading pair. In the case of XBTUSD, this is XXBTZUSD. This can be illustrated as follows:

    >>> trades = api.query_public("Trades", {'pair': 'XBTUSD', 'since': 1546300800000000000, 'ascending': True})
    >>> print(trades)
    {'error': [], 'result': {'XXBTZUSD': [['3690.90000', '0.00400000', 1546300800.4732, 's', 'l', ''], ...
    

    The error is produced when a dataframe is constructed in the pykrakenapi.py function that is being called:

    def get_recent_trades(self, pair, since=None, ascending=False):
        ...
        ...
        # create dataframe
        trades = pd.DataFrame(res['result'][pair])
        ...
    

    This issue can be fixed by changing the value for pair to the correct key:

    def get_recent_trades(self, pair, since=None, ascending=False):
        ...
        ...
        # create dataframe
        pair = list(res['result'].keys())[0]
        trades = pd.DataFrame(res['result'][pair])
        ...
    

    Where list(res['result'].keys())[0] equals the first key of the dictionary under the result key.