Kraken OHLC 端点设计用于 9 个不同的时间间隔(1、5、15、30、60、240、1440、10080 和 21600 分钟),其中 1 分钟是默认间隔。这样做的一个问题是,您将无法使用此端点每 5 秒获取一次新数据,尽管每分钟都可以。
在这种情况下,您可以使用since
OHLC 端点的参数(如下所示)来获取您之前找到的最后一个实例之后的所有实例。
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 最近交易端点获得的交易数据构建此数据。
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 数据可能没有什么意义,尤其是在只进行一笔交易的情况下。