Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python OHLC数据的Kraken API仅附加最新条目_Python_Kraken.com - Fatal编程技术网

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

Python OHLC数据的Kraken API仅附加最新条目,python,kraken.com,Python,Kraken.com,因此,我在Kraken API上运行代码,并以718行8列的OHLC数据的形式获取所需的数据。我想对这些数据进行实时更新,所以我想我会使用线程每隔5秒定期运行代码,但所做的只是一次又一次地打印整个数据块 如何仅附加上一个输出中不存在的数据。即每五秒钟更新一次 我的代码如下: import krakenex from pykrakenapi import KrakenAPI import threading api = krakenex.API() api.load_key('/path/kra

因此,我在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()
设计了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数据,您必须根据使用获取的交易数据自行构建该数据

导入时间
进口krakenex
作为pd进口熊猫
将numpy作为np导入
从pykrakenapi导入KrakenAPI
从日期时间导入时间增量
def将_转换为_ohlc(df,粒度):
#确定数据的时间范围
因为=df['time'].iloc[0]*100000000
to=df['time'].iloc[-1]*100000000
#创建一个初始数据表,其中包含从开始到结束时间的条目,步骤为5秒
时间戳=pd.date\u范围(自、至、频率=str(粒度)+“s”)
#初始化输出数据帧
输出=pd.DataFrame(索引=时间戳,列=['open'、'high'、'low'、'close'])
#以5秒的步长逐步浏览数据
df['dtime']=df.index
df=df.set_索引(“时间”)
对于范围(0,len(output.index))中的i:
#为此步骤选择相关数据点
相关行=df[
(df['dtime']>=output.index[i])&
(df['dtime']<(output.index[i]+
时间增量(秒=粒度)
]
#将时间范围内的数据转换为OHLC数据
如果len(相关_行)>0且不相关_行为空:
#打开
output.loc[output.index[i],'open']=相关行['price'].iloc[0]
#高
output.loc[output.index[i],'high']=np.max(相关行['price'])
#低
output.loc[output.index[i],'low']=np.min(相关行['price'])
#接近
output.loc[output.index[i],'close']=相关行['price'].iloc[-1]
其他:
对于output.keys()中的列:
output.loc[output.index[i],str(col)]=np.nan
返回输出
api=krakenex.api()
k=KrakenAPI(api)
#获取交易数据
df,last=k.获取最近交易(“BCHUSD”,升序=True)
#将数据转换为OHLC数据,步骤为5秒
df=将_转换为_ohlc(df,5)
#附加OHLC数据的无限循环
尽管如此:
#等待60秒,等待新的交易发生
时间。睡眠(60)
#获取新交易数据
数据,last=k.获取最近的交易(“XBTUSD”,自=last,升序=True)
#将数据转换为OHLC数据,步骤为5秒
如果不是data.empty:
数据=转换为ohlc(数据,5)
df=pd.concat([df,data])
打印(f'{len(data.index)}新数据点{s“if len(data.index)>1 else”“}下载。总计:{len(df.index)}数据点。'))
其他:
打印(“无法找到新交易。正在重试…”)

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

我的回答对您有帮助吗?很高兴我能提供帮助!
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...")