import pymysql
from apscheduler.schedulers.background import BackgroundScheduler
import requests
import datetime
import time
logging.basicConfig(filename = 'tstw.log',format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
db = pymysql.connect(host = "localhost",user = "root",password = "root",database = "dogeusdt",charset = 'utf8' )
global cursor
cursor = db.cursor()
global sql
global last_datetime
last_datetime = None
sql1 = "CREATE TABLE IF NOT EXISTS `1min` ( `datetime` date,`open` float,`high` float,`low` float,`close` float)"
cursor.execute(sql1)
sql = 'insert into 1min(datetime,open,high,low,close) values(%(datetime)s,%(open)s,%(high)s,%(low)s,%(close)s);'
def get_kbar_and_save():
for i in range(3):
try:
r1 = requests.get("https://api.huobi.pro/market/history/kline?period=1min&size=1&symbol=btcusdt").json()
r1_data = r1['data'][0]
if (r1['status']=='ok') and (last_datetime - datetime.datetime.fromtimestamp(r1_d['id'])== datetime.timedelta(seconds=60)):
r1_data['datetime'] = datetime.datetime.fromtimestamp(r1_d['id'])
try:
cursor.execute(sql,r1_data )
db.commit()
last_datetime = r1_data ['datetime']
return logging.info('已写入数据库')
except:
logging.warning('数据库写入错误')
r1_data['datetime'] = datetime.datetime.now()
r1_data['open'] = 0
r1_data['high'] = 0
r1_data['low'] = 0
r1_data['close'] = 0
else:
time.sleep(10)
except:
time.sleep(10)
sche_00 = BackgroundScheduler()
sche_00.add_job(get_kbar_and_save, 'cron', hour='*',minute='*', second='0', id='task0')
sche_00.start()```
觉得自己太菜了想放弃的时候该怎么心理建设。。。
1
yagamil 2021-06-24 17:33:43 +08:00 1
1. 代码最好模块化,便于后续修改复用
2. ``` last_datetime - datetime.datetime.fromtimestamp(r1_d['id'])== datetime.timedelta(seconds=60) ``` 这里不建议直接用等号,如果时间稍微有些抖动,就无法执行。可换成区间范围。 |
2
yellowtail OP @yagamil 感谢回复,很实用的建议,不过这里的时间是交易所返回的标准时间,都是 XX:XX:00 这样的,顺便问一下数字货币 15 秒级别的行情该怎么获取,虽然考虑过用 tick,但担心用 tick 的话会导致最高点和最低点的数据不真实,因为最高点可能不在获取 tick 的时刻。。。
|
3
yagamil 2021-06-25 21:19:28 +08:00
@yellowtail 取 15 秒的 high 和 low 就可以的了。前提得有这两个字段。本身 15 秒的 tick 是从 1 秒合并而成的,并不是只靠没 15 秒采样
|