由于 Poloniex 不提供代码历史记录,您必须定期请求代码,然后将结果存储在文件、json 或数据库中。然后读取您的文件、本地 json 或数据库以返回一组过去的股票代码。
您可以使用类似的东西(文件版本):
import requests
import time
import shutil
import os
import json
#this func is use to give you the ticker history
def do_job_with_ticker_history(ticker_history_directory="tickers_hist"):
sorted_ticker_history = sorted(os.listdir(ticker_history_directory))
ticker_array=[]
#iterate over all ticker file
for ticker_filename in sorted_ticker_history:
#get the filepath
ticker_path = ticker_history_directory+os.sep+ ticker_filename
#read the ticker
with open(ticker_path,'r') as f:
#add the ticker data to the array
ticker_array.append(json.loads(f.read()))
#############
#do your job here (first element is the older ticker, and last element is the last ticker)
print "\ndo the job with history (here we show the ",len(sorted_ticker_history),"last price)"
for ticker in ticker_array:
print ticker['BTC_ETH']['last']
#############
#this func is use to grab the ticker
def grab_ticker_periodically(period_in_s=5,ticker_history_directory="tickers_hist",max_history_size=3):
#delete directory
try:
shutil.rmtree(ticker_history_directory)
except:
pass
#create directory
try:
os.mkdir(ticker_history_directory)
except:
pass
ticker_path_name_list=[]
while 1:
print "\nWe get new ticker"
#get timestamp
timestamp = str(time.time())
#generate a filename using timestamp
ticker_path = ticker_history_directory+os.sep+timestamp+".json"
#write ticker data to filename
with open(ticker_path,"w") as f:
f.write(requests.get('https://poloniex.com/public?command=returnTicker').text)
#add new file to list
ticker_path_name_list.append( ticker_path )
#check we not reach the max size
if len(ticker_path_name_list)>max_history_size:
os.remove(ticker_path_name_list[0])
ticker_path_name_list.pop(0)
do_job_with_ticker_history()
#sleep until next grab
time.sleep(period_in_s)
grab_ticker_periodically()
那么你可以:
- 更改
period_in_s=5
为period_in_s=60
每隔一分钟抓取一次股票行情
max_history_size=x
以满足您的历史记录大小要求。
- 把你的代码放在
#do your job here section
哪个给你:
We get new ticker
do the job with history (here we show the 1 last price)
0.03102500
We get new ticker
do the job with history (here we show the 2 last price)
0.03102500
0.03102500
We get new ticker
do the job with history (here we show the 3 last price)
0.03102500
0.03102500
0.03102500
We get new ticker
do the job with history (here we show the 3 last price)
0.03102500
0.03102500
0.03102500
[...]