OHLC数据的Kraken API仅附加最新条目

2024-06-28 15:05:50 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我在Kraken API上运行代码,并以718行8列的OHLC数据的形式获取所需的数据。我想对这些数据进行实时更新,所以我想我会使用线程每隔5秒定期运行代码,但所做的只是一次又一次地打印整个数据块

如何仅附加上一个输出中不存在的数据。即每五秒钟更新一次

我的代码如下:

import krakenex
from pykrakenapi import KrakenAPI
import threading

api = krakenex.API()
api.load_key('/path/kraken.txt')
k = KrakenAPI(api)

ohlc, last = k.get_ohlc_data("BCHUSD")

def printit():
    threading.Timer(5.0,printit).start()
    print(ohlc)

printit()

Tags: 数据代码importapi线程形式threading我会
1条回答
网友
1楼 · 发布于 2024-06-28 15:05:50

{a1}设计用于9个不同的时间间隔(1、5、15、30、60、240、1440、10080和21600分钟),其中1分钟是默认时间间隔。这样做的一个问题是,您将无法使用此端点每5秒获取一次新数据,尽管每分钟都可以。
在这种情况下,您可以使用OHLC端点的since参数,如下所示,以获取前面找到的最后一个实例之后的所有实例

import time
import krakenex
import pandas as pd
from pykrakenapi import KrakenAPI

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

# Initial OHLC dataframe
df, last = k.get_ohlc_data("BCHUSD", ascending=True)

# Infinite loop for additional OHLC data
while True:
    # Wait 60 seconds
    time.sleep(60)

    # Get data and append to existing pandas dataframe
    ohlc, last = k.get_ohlc_data("BCHUSD", since=last + 60000, ascending=True)
    df = pd.concat([df, ohlc])

    print(f'1 new data point downloaded. Total: {len(df.index)} data points.')

如果您确实希望以5秒的间隔获取OHLC数据,那么您必须根据使用Kraken Recent Trades endpoint获得的交易数据自己构建该数据

import time
import krakenex
import pandas as pd
import numpy as np
from pykrakenapi import KrakenAPI
from datetime import timedelta


def convert_to_ohlc(df, granularity):
    # Determine time frame of data
    since = df['time'].iloc[0] * 1000000000
    to =  df['time'].iloc[-1] * 1000000000

    # Create an initial data table with entries from start till end time, with steps of 5 seconds
    timestamps = pd.date_range(since, to, freq=str(granularity) + 's')

    # Initialise output dataframe
    output = pd.DataFrame(index=timestamps, columns=['open', 'high', 'low', 'close'])

    # Step through data in steps of 5 seconds
    df['dtime'] = df.index
    df = df.set_index('time')
    for i in range(0, len(output.index)):
        # Select the relevant datapoints for this step
        relevant_rows = df[
            (df['dtime'] >= output.index[i]) &
            (df['dtime'] < (output.index[i] +
                              timedelta(seconds=granularity)))
            ]

        # Convert data in time frame to OHLC data
        if len(relevant_rows) > 0 and not relevant_rows.empty:
            # open
            output.loc[output.index[i], 'open'] = relevant_rows['price'].iloc[0]
            # high
            output.loc[output.index[i], 'high'] = np.max(relevant_rows['price'])
            # low
            output.loc[output.index[i], 'low'] = np.min(relevant_rows['price'])
            # close
            output.loc[output.index[i], 'close'] = relevant_rows['price'].iloc[-1]
        else:
            for col in output.keys():
                output.loc[output.index[i], str(col)] = np.nan

    return output

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

# Get trades data
df, last = k.get_recent_trades("BCHUSD", ascending=True)

# Convert data to OHLC data, steps of 5 seconds
df = convert_to_ohlc(df, 5)

# Infinite loop for additional OHLC data
while True:
    # Wait 60 seconds for new trades to happen
    time.sleep(60)

    # Get new trades data
    data, last = k.get_recent_trades("XBTUSD", since=last, ascending=True)

    # Convert data to OHLC data, steps of 5 seconds
    if not data.empty:
        data = convert_to_ohlc(data, 5)
        df = pd.concat([df, data])

        print(f'{len(data.index)} new data point{"s" if len(data.index) > 1 else ""} downloaded. Total: {len(df.index)} data points.')
    else:
        print("Could not find new trades. Retrying...")

您应该意识到,OHLC数据是特定时间范围内交易的汇总。在5秒内,通常不会进行交易,这意味着不会生成OHLC数据。可解释性是另一个问题,因为极少数交易的OHLC数据可能没有什么意义,特别是当只进行了一次交易时

相关问题 更多 >