huobi API使用经验整理

开局不知道说什么, 韭就完事了

基础知识

现在火币/大多数交易所的API都有两种. 一种是REST API, 类似于浏览网页, 由客户发起请求到服务器, 然后服务器发送相关数据; 另一种是基于socket的, 当用户建立与服务器的请求后, 由服务器不断连续将数据推送过来(当然中间用户需要发送一些数据来表明自己还在).

火币虽然高杠杆合约很坑(保证金比友商多一倍而且波动更大), 但对于低杠杆来说交易费用相对友好一些, 而且不需要科学上网, 作为练手很适合

REST API实例

1.start

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)

2.更多数据

官方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])
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值