是否有一种使用来自交易所的实时股票信息来构建Kline交易数据的方法' API?
我已经构建了一个Python现货交易机器人,并打算将其与KuCoin交易所一起使用。该机器人需要每个硬币的过去 50 个数据点的历史 OHLCV 数据,间隔 5m。我的目的是尽快检索每个代币(交易所上约 1000 个代币)的 K 线(烛台)数据,最好在 5 分钟窗口内进行充分交易。
API 提供了一个用于检索 K 线数据的客户端方法,这是我当前的实现,但它严重限制了此请求的频率。将睡眠时间设置为 2 秒仍会产生频率违规。此外,文档中有一条注释如下:
Klines 不应频繁轮询。如果您需要实时 信息,使用交易和预订端点以及 websocket 饲料。
下面的代码是我当前的实现:
#Import Modules
import os
import pickle
import datetime as dt
import time
import threading
import random
from kucoin.client import Market
def get_symbols():
"""
This function retrieves all tradable symbols from
the exchange.
Parameters:
-----------
None
Returns:
-----------
symbols: list(str)
list of trading symbols
"""
#Get list of possible symbols
all_symbols = client.get_symbol_list()
#For all tickers
symbols = []
for ticker in all_symbols:
#Pull data
symbol = ticker["symbol"]
trading = ticker["enableTrading"]
#keep if trading allowed
if trading:
symbols.append(symbol)
return symbols
def update_kline(symbol,source_dict):
#Points to pull
DATA_PTS = 50
#Get kline data
klines = client.get_kline(symbol,'5min')
klines = klines[:DATA_PTS]
#Get the lastest epoch time from kline dataset
latest_time = int(klines[0][0])
#If kline data is not recent (info is bugged), skip
if abs(end-latest_time) > 5*60:
return
#Make sure data has 50 full datapoints
if len(klines) == DATA_PTS:
source_dict[symbol] = klines
def update_klines(source_dict,symbols):
"""
This function continously updates kline data
for all given symbols to a destination dictionary
"source_dict".
Parameters:
-----------
source_dict: dict
where keys are symbol names and value is
kline 2D array/list data
symbols: list(str)
symbols to pull data from
Returns:
-----------
None
"""
#Forever
while True:
#For each symbol
for i,symbol in enumerate(symbols):
#Update dictionary with kline data for symbol
update_kline(symbol,source_dict)
#Sleep for some time to avoid IP freeze
time.sleep(random.uniform(2,3))
def main():
"""
Main function to run bot.
Parameters:
-----------
None
Returns:
-----------
None
"""
#Initialize client
client = Market(url='https://api.kucoin.com')
#Get symbols
symbols = get_symbols()
#Source dict which will hold kline data
source_dict = {}
#Set thread to continuously update kline data
t = threading.Thread(target = update_klines,args=(source_dict,symbols))
t.start()
#Run main function in script
if __name__ == "__main__":
main()
上面的执行最终将产生一个返回错误代码,表明请求太多。我能想到的第一个可行的解决方案是使用不同的方法手动构建 k 线数据。 API 提到使用带有 websockets 的图书和交易端点(不熟悉 websockets)。但是,我不熟悉如何使用此类数据组装 K 线数据框。
我能想到的第二个潜在解决方案是使用替代交易所的 API,例如 Binance,甚至是 yfinance 库中的数据,这些库的 K 线频率限制可能不太严格。然而,我认为 K 线数据将与我打算交易的交易所(KuCoin)有所不同,因此会出现问题。不过,我正在使用历史 K 线数据来预测买入候选者。因此,该解决方案将涉及使用不同的 API/库来获取频繁的 K 线数据,一旦找到购买机会的可行候选者,就向 KuCoin 请求感兴趣的符号的单个 K 线数据以确认其候选资格。正如您可以想象的那样,这将具有准确性和延迟的缺点。
KuCoin官方API参考: https://docs.kucoin.com/#market-data
KuCoin Python API参考: https://github.com/Kucoin/kucoin-python-sdk
I have built a Python spot trading bot and intend to use it with KuCoin exchange. The bot requires historical OHLCV data for each coin on a 5m interval for the last 50 datapoints. My intention is retrieve this kline (candlestick) data for each coin (~1000 coins on the exchange) as fast as possible and preferably within a 5 minute window for adequate trading.
The API provides a client method for retrieving kline data, my current implementation, however it heavily restricts the frequency of this request. Setting a sleep time of 2 seconds will still yield a frequency violation. Furthermore, there is a note within the documentation that reads as follows:
Klines should not be polled frequently. If you need real-time
information, use the trade and book endpoints along with the websocket
feed.
The code below is my current implementation:
#Import Modules
import os
import pickle
import datetime as dt
import time
import threading
import random
from kucoin.client import Market
def get_symbols():
"""
This function retrieves all tradable symbols from
the exchange.
Parameters:
-----------
None
Returns:
-----------
symbols: list(str)
list of trading symbols
"""
#Get list of possible symbols
all_symbols = client.get_symbol_list()
#For all tickers
symbols = []
for ticker in all_symbols:
#Pull data
symbol = ticker["symbol"]
trading = ticker["enableTrading"]
#keep if trading allowed
if trading:
symbols.append(symbol)
return symbols
def update_kline(symbol,source_dict):
#Points to pull
DATA_PTS = 50
#Get kline data
klines = client.get_kline(symbol,'5min')
klines = klines[:DATA_PTS]
#Get the lastest epoch time from kline dataset
latest_time = int(klines[0][0])
#If kline data is not recent (info is bugged), skip
if abs(end-latest_time) > 5*60:
return
#Make sure data has 50 full datapoints
if len(klines) == DATA_PTS:
source_dict[symbol] = klines
def update_klines(source_dict,symbols):
"""
This function continously updates kline data
for all given symbols to a destination dictionary
"source_dict".
Parameters:
-----------
source_dict: dict
where keys are symbol names and value is
kline 2D array/list data
symbols: list(str)
symbols to pull data from
Returns:
-----------
None
"""
#Forever
while True:
#For each symbol
for i,symbol in enumerate(symbols):
#Update dictionary with kline data for symbol
update_kline(symbol,source_dict)
#Sleep for some time to avoid IP freeze
time.sleep(random.uniform(2,3))
def main():
"""
Main function to run bot.
Parameters:
-----------
None
Returns:
-----------
None
"""
#Initialize client
client = Market(url='https://api.kucoin.com')
#Get symbols
symbols = get_symbols()
#Source dict which will hold kline data
source_dict = {}
#Set thread to continuously update kline data
t = threading.Thread(target = update_klines,args=(source_dict,symbols))
t.start()
#Run main function in script
if __name__ == "__main__":
main()
The above execution will eventually yield a return error code indicating there are too many requests. The first viable solution I can think of is to manually build the kline data using a different method. The API mentions using book and trade endpoints with websockets (not familiar with websockets). However, I am not familiar with how a kline data frame could be assembled using such data.
The second potential solution I can think of is to use an alternate exchange's API, such as Binance or even data from the yfinance library which could have less stringent kline frequency limitations. However I imagine the kline data will be somewhat different than the exchange I intend to trade on (KuCoin) and thus be problematic. However I am using the historical kline data to predict buy-in candidates. Therefore, this solution would involve using a different API/library to acquire frequent kline data and once a viable candidate is found for a buy-opportunity, request the single kline data for the symbol of interest from KuCoin to confirm its candidacy. This, as you can imagine, will have accuracy and delay drawbacks.
KuCoin Official API Reference:
https://docs.kucoin.com/#market-data
KuCoin Python API Reference:
https://github.com/Kucoin/kucoin-python-sdk
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论