MasonTep
MasonTep

Reputation: 21

Accessing trades history using krakenex in Python

I am trying to load in trades history for Ethereum-GBP trading using krakenex in Python 3.6.9. I currently load in some recent trades as follows:

# Load in my private key
k = krakenex.API()
k.load_key('mykraken.key')

# Trade pair
tradePair = 'XETHZGBP'

# Get a list of the most recent trades
recentTrades = k.query_public('Trades',{'pair':tradePair})


# Cast to numeric
recentTrades[0] = pd.to_numeric(recentTrades[0], errors='coerce')
recentTrades[1] = pd.to_numeric(recentTrades[1], errors='coerce')
recentTrades[2] = pd.to_numeric(recentTrades[2], errors='coerce')

This seems to give me the last 1000 transactions in a table of columns for price, volume and datestamp. But how can I get more than 1000? Whatever I do, I can't seem to get this working and I'm not sure the krakenex behaviour fully matches the kraken API documentation.

Upvotes: 2

Views: 1328

Answers (2)

Tim Stack
Tim Stack

Reputation: 3248

As mentioned before, the Kraken API limits the getRecentTrades endpoint to 1000 trades. To go around this limit, you can loop through a certain timeframe until all orders are retrieved. Note that the following code does not implement error checking and handling.

Using the pykrakenapi package, the output is a Pandas DataFrame in descending order.

import time
import krakenex
from pykrakenapi import KrakenAPI
from datetime import datetime, timezone, timedelta


def nano_after_epoch(t):
    """Converts DateTime object to int nanoseconds after epoch"""
    return int(t.replace(tzinfo=timezone.utc).timestamp() * 1000000000)


# Connect to the kraken API
api = krakenex.API(key=<<key>>,
                   secret=<<optional>>)
api = KrakenAPI(api)

"""Specify requirements"""
# Start and end time for which period to retrieve data
start_time = nano_after_epoch(datetime(2021, 10, 12))
end_time = nano_after_epoch(datetime.utcnow())
leeway = 180 * 1000000000 # Seconds * nanoseconds converter
pair = 'XETHZGBP'

# Loop until the last retrieved date is within X seconds of the desired end date to account
# for a lack of recent trades. If set too strictly, loop will continue until a new trade has been made
df = None
while start_time < end_time - leeway:
    print(f"Retrieving data from {datetime.fromtimestamp(start_time // 1000000000)}...")
    qry = api.get_recent_trades(since=start_time, pair=pair)
    # Append new data to dataframe
    df = qry[0] if df is None else qry[0].append(df)

    # Determine last retrieved date
    start_time = df.index[0]

    # New 'retrieve from' date is latest_time + 1 nanosecond
    start_time = nano_after_epoch(start_time) + 1

    # Sleep to avoid being rate limited
    time.sleep(1.8)

print(df)

Output:

Retrieving data from 2021-10-12 02:00:00...
Retrieving data from 2021-10-12 17:53:38...
Retrieving data from 2021-10-13 16:31:48...
                                 price    volume  ...  market_limit misc
dtime                                             ...                   
2021-10-13 19:15:17.854300022  2580.07  0.004000  ...         limit     
2021-10-13 19:13:12.930500031  2580.07  1.380691  ...         limit     
2021-10-13 19:08:06.569099903  2578.75  0.016780  ...         limit     
2021-10-13 19:04:16.453200102  2575.33  0.190738  ...        market     
2021-10-13 19:04:16.452300072  2575.70  0.001800  ...        market     
...                                ...       ...  ...           ...  ...
2021-10-12 00:03:43.447799921  2593.58  0.084000  ...         limit     
2021-10-12 00:03:05.378900051  2591.09  0.004732  ...         limit     
2021-10-12 00:03:03.912699938  2593.58  0.084077  ...         limit     
2021-10-12 00:02:38.695899963  2603.86  1.120000  ...         limit     
2021-10-12 00:00:20.313299894  2604.47  0.014493  ...         limit     

[2286 rows x 6 columns]

Upvotes: 2

lok
lok

Reputation: 33

The kraken.com API serves only the last 1000 trades by default. You need to specify the since query paremeter to receive older data.
Source: The kraken.com API documentation https://docs.kraken.com/rest/#operation/getRecentTrades

The krakenex package does not seem to support this parameter.

Upvotes: 1

Related Questions