开局不知道说什么, 韭就完事了
现在火币/大多数交易所的API都有两种. 一种是REST API, 类似于浏览网页, 由客户发起请求到服务器, 然后服务器发送相关数据; 另一种是基于socket的, 当用户建立与服务器的请求后, 由服务器不断连续将数据推送过来(当然中间用户需要发送一些数据来表明自己还在).
火币虽然高杠杆合约很坑(保证金比友商多一倍而且波动更大), 但对于低杠杆来说交易费用相对友好一些, 而且不需要科学上网, 作为练手很适合
restapi的使用与访问网页的过程是一致的 以下代码参考了火币官方api代码
import urllib #用于生成报文 import requests #用于投递/接受报文 params = {'symbol': 'ETH'} postdata = urllib.parse.urlencode(params) url = 'https://www.hbdm.com/api/v1/contract_index' # 并没有模拟浏览器的必要, headers为非必要参数 headers = {"Content-type": "application/x-www-form-urlencoded", 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'} response = requests.get(url, postdata, headers=headers, timeout=3) # 以下在实际应用时需要加入异常处理模块 if response.status_code == 200: result = response.json();print(result)以下是一个更让人喜欢的船新版本:
import requests url = 'https://www.hbdm.com/api/v1/contract_index' params = {'symbol': 'ETH'} response = requests.get(url=url, params=params, timeout=2) result = response.json() print(result)官方API目录 那么,哪些数据是最重要的? 1.实时k线, 决定决策 2.盘口数据, 决定make/take以及程度
host = "https://www.hbdm.com" # kline url = host + "/market/history/kline" params = {'symbol': 'ETH_CQ', 'period': '1', 'size':200} response = requests.get(url=url, params=params, timeout=2) assert response.status_code==200 result = response.json()野生的bug出现了:JSONDecodeError: Expecting value debug半天, 然后发现这个response.text与上面的不同, 上面是简单的两行数据, 这边的是html网页,这似乎需要借助一些爬虫知识来解决
再来试试盘口数据
host = "https://www.hbdm.com" # depth url = host + "/market/depth" params = {'symbol': 'ETH_CQ', 'type':'step5'} response = requests.get(url=url, params=params, timeout=2) assert response.status_code==200 print(response.text)依然是一个html页面 结合官方文档,推测就是下面两个页面(事实上不是) https://api.hbdm.com/market/history/kline?period=1min&size=200&symbol=ETH_CQ https://api.hbdm.com/market/depth?symbol=ETH_CQ&type=step5
以下是debug尝试
json.loads(response.text) #error response = requests.get(url='https://api.hbdm.com/market/depth?symbol=ETH_CQ&type=step5') depth = response.json() #good阿西吧可算是好了 对得到的数据进行可视化
import numpy as np import matplotlib.pyplot as plt asks = np.array(depth['tick']['asks']) bids = np.array(depth['tick']['bids']) plt.plot(asks[:,0],asks[:,1]) plt.plot(bids[:,0],bids[:,1])