REST API 简介

  火币为用户提供了一套全新的API,可以帮用户快速接入火币PRO站及HADAX站的交易系统,实现程序化交易。

访问地址 适用站点 适用功能 适用交易对
https://api.huobipro.com/market 火币PRO 行情 所有Pro站交易中的交易对
https://api.huobipro.com/v1 火币PRO 交易 同上
https://api.hadax.com/market HADAX hadax.com 行情 所有HADAX站交易中的交易对
https://api.hadax.com/v1 HADAX hadax.com 交易 同上

  通过API可以实现以下功能:

  • 市场行情信息查询(K线、深度、实时成交、24小时行情)
  • 账户资产信息查询
  • 下单、撤单操作
  • 订单信息查询 所有请求基于 HTTPS 协议。

请求说明

  1. 访问地址

    Pro 站: 行情: https://api.huobipro.com/market 交易: https://api.huobipro.com/v1

    HADAX 站: 行情: https://api.hadax.com/market 交易: https://api.hadax.com/v1

  1. POST请求头信息中必须声明 Content-Type:application/json;GET请求头信息中必须声明 Content-Type:application/x-www-form-urlencoded。(汉语用户建议设置 Accept-Language:zh-cn)
  2. 所有请求参数请按照 API 说明进行参数封装。
  3. 将封装好参数的 API 请求通过 POST 或 GET 的方式提交到服务器。
  4. 火币网处理请求,并返回相应的 JSON 格式结果。
  5. 请使用 https 请求。
  6. 限制频率(每个接口,只针对交易api,行情api不限制)为10秒100次。
  7. 查询资产详情方法调用顺序:查询当前用户的所有账户->查询指定账户的余额
  8. 支持所有Pro站上交易中的交易对,上新币保持与网站同步。

相关知识点链接:

示例代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*- import base64
import datetime
import hashlib
import hmac
import json
import urllib
import urllib.parse
import urllib.request
import requests # 此处填写APIKEY ACCESS_KEY = " "
SECRET_KEY = " " # API 请求地址
MARKET_URL = "https://api.huobi.pro"
TRADE_URL = "https://api.huobi.pro" # 首次运行可通过get_accounts()获取acct_id,然后直接赋值,减少重复获取。
ACCOUNT_ID = None #'Timestamp': '2017-06-02T06:13:49' def http_get_request(url, params, add_to_headers=None):
headers = {
"Content-type": "application/x-www-form-urlencoded",
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
}
if add_to_headers:
headers.update(add_to_headers)
postdata = urllib.parse.urlencode(params)
response = requests.get(url, postdata, headers=headers, timeout=5)
try: if response.status_code == 200:
return response.json()
else:
return
except BaseException as e:
print("httpGet failed, detail is:%s,%s" %(response.text,e))
return def http_post_request(url, params, add_to_headers=None):
headers = {
"Accept": "application/json",
'Content-Type': 'application/json'
}
if add_to_headers:
headers.update(add_to_headers)
postdata = json.dumps(params)
response = requests.post(url, postdata, headers=headers, timeout=10)
try: if response.status_code == 200:
return response.json()
else:
return
except BaseException as e:
print("httpPost failed, detail is:%s,%s" %(response.text,e))
return def api_key_get(params, request_path):
method = 'GET'
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
params.update({'AccessKeyId': ACCESS_KEY,
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '',
'Timestamp': timestamp}) host_url = TRADE_URL
host_name = urllib.parse.urlparse(host_url).hostname
host_name = host_name.lower()
params['Signature'] = createSign(params, method, host_name, request_path, SECRET_KEY) url = host_url + request_path
return http_get_request(url, params) def api_key_post(params, request_path):
method = 'POST'
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
params_to_sign = {'AccessKeyId': ACCESS_KEY,
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '',
'Timestamp': timestamp} host_url = TRADE_URL
host_name = urllib.parse.urlparse(host_url).hostname
host_name = host_name.lower()
params_to_sign['Signature'] = createSign(params_to_sign, method, host_name, request_path, SECRET_KEY)
url = host_url + request_path + '?' + urllib.parse.urlencode(params_to_sign)
return http_post_request(url, params) def createSign(pParams, method, host_url, request_path, secret_key):
sorted_params = sorted(pParams.items(), key=lambda d: d[0], reverse=False)
encode_params = urllib.parse.urlencode(sorted_params)
payload = [method, host_url, request_path, encode_params]
payload = '\n'.join(payload)
payload = payload.encode(encoding='UTF8')
secret_key = secret_key.encode(encoding='UTF8') digest = hmac.new(secret_key, payload, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest)
signature = signature.decode()
return signature

Utils.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- from Utils import * '''
Market data API
''' # 获取KLine
def get_kline(symbol, period, size=150):
"""
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return:
"""
params = {'symbol': symbol,
'period': period,
'size': size} url = MARKET_URL + '/market/history/kline'
return http_get_request(url, params) # 获取marketdepth
def get_depth(symbol, type):
"""
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return:
"""
params = {'symbol': symbol,
'type': type} url = MARKET_URL + '/market/depth'
return http_get_request(url, params) # 获取tradedetail
def get_trade(symbol):
"""
:param symbol
:return:
"""
params = {'symbol': symbol} url = MARKET_URL + '/market/trade'
return http_get_request(url, params) # 获取merge ticker
def get_ticker(symbol):
"""
:param symbol:
:return:
"""
params = {'symbol': symbol} url = MARKET_URL + '/market/detail/merged'
return http_get_request(url, params) # 获取 Market Detail 24小时成交量数据
def get_detail(symbol):
"""
:param symbol
:return:
"""
params = {'symbol': symbol} url = MARKET_URL + '/market/detail'
return http_get_request(url, params) # 获取 支持的交易对
def get_symbols(long_polling=None):
"""
"""
params = {}
if long_polling:
params['long-polling'] = long_polling
path = '/v1/common/symbols'
return api_key_get(params, path) '''
Trade/Account API
''' def get_accounts():
"""
:return:
"""
path = "/v1/account/accounts"
params = {}
return api_key_get(params, path) ACCOUNT_ID = 0
# 获取当前账户资产
def get_balance(acct_id=None):
"""
:param acct_id
:return:
"""
global ACCOUNT_ID if not acct_id:
accounts = get_accounts()
acct_id = accounts['data'][0]['id']; url = "/v1/account/accounts/{0}/balance".format(acct_id)
params = {"account-id": acct_id}
return api_key_get(params, url) # 下单 # 创建并执行订单
def send_order(amount, source, symbol, _type, price=0):
"""
:param amount:
:param source: 如果使用借贷资产交易,请在下单接口,请求参数source中填写'margin-api'
:param symbol:
:param _type: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param price:
:return:
"""
try:
accounts = get_accounts()
acct_id = accounts['data'][0]['id']
except BaseException as e:
print ('get acct_id error.%s' % e)
acct_id = ACCOUNT_ID params = {"account-id": acct_id,
"amount": amount,
"symbol": symbol,
"type": _type,
"source": source}
if price:
params["price"] = price url = '/v1/order/orders/place'
return api_key_post(params, url) # 撤销订单
def cancel_order(order_id):
""" :param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}/submitcancel".format(order_id)
return api_key_post(params, url) # 查询某个订单
def order_info(order_id):
""" :param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}".format(order_id)
return api_key_get(params, url) # 查询某个订单的成交明细
def order_matchresults(order_id):
""" :param order_id:
:return:
"""
params = {}
url = "/v1/order/orders/{0}/matchresults".format(order_id)
return api_key_get(params, url) # 查询当前委托、历史委托
def orders_list(symbol, states, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
""" :param symbol:
:param states: 可选值 {pre-submitted 准备提交, submitted 已提交, partial-filled 部分成交, partial-canceled 部分成交撤销, filled 完全成交, canceled 已撤销}
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前,next 向后}
:param size:
:return:
"""
params = {'symbol': symbol,
'states': states} if types:
params[types] = types
if start_date:
params['start-date'] = start_date
if end_date:
params['end-date'] = end_date
if _from:
params['from'] = _from
if direct:
params['direct'] = direct
if size:
params['size'] = size
url = '/v1/order/orders'
return api_key_get(params, url) # 查询当前成交、历史成交
def orders_matchresults(symbol, types=None, start_date=None, end_date=None, _from=None, direct=None, size=None):
""" :param symbol:
:param types: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param start_date:
:param end_date:
:param _from:
:param direct: 可选值{prev 向前,next 向后}
:param size:
:return:
"""
params = {'symbol': symbol} if types:
params[types] = types
if start_date:
params['start-date'] = start_date
if end_date:
params['end-date'] = end_date
if _from:
params['from'] = _from
if direct:
params['direct'] = direct
if size:
params['size'] = size
url = '/v1/order/matchresults'
return api_key_get(params, url) # 申请提现虚拟币
def withdraw(address, amount, currency, fee=0, addr_tag=""):
"""
:param address_id:
:param amount:
:param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种)
:param fee:
:param addr-tag:
:return: {
"status": "ok",
"data": 700
}
"""
params = {'address': address,
'amount': amount,
"currency": currency,
"fee": fee,
"addr-tag": addr_tag}
url = '/v1/dw/withdraw/api/create' return api_key_post(params, url) # 申请取消提现虚拟币
def cancel_withdraw(address_id):
"""
:param address_id:
:return: {
"status": "ok",
"data": 700
}
"""
params = {}
url = '/v1/dw/withdraw-virtual/{0}/cancel'.format(address_id) return api_key_post(params, url) '''
借贷API
''' # 创建并执行借贷订单 def send_margin_order(amount, source, symbol, _type, price=0):
"""
:param amount:
:param source: 'margin-api'
:param symbol:
:param _type: 可选值 {buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖}
:param price:
:return:
"""
try:
accounts = get_accounts()
acct_id = accounts['data'][0]['id']
except BaseException as e:
print ('get acct_id error.%s' % e)
acct_id = ACCOUNT_ID params = {"account-id": acct_id,
"amount": amount,
"symbol": symbol,
"type": _type,
"source": 'margin-api'}
if price:
params["price"] = price url = '/v1/order/orders/place'
return api_key_post(params, url) # 现货账户划入至借贷账户 def exchange_to_margin(symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount} url = "/v1/dw/transfer-in/margin"
return api_key_post(params, url) # 借贷账户划出至现货账户 def margin_to_exchange(symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount} url = "/v1/dw/transfer-out/margin"
return api_key_post(params, url) # 申请借贷
def get_margin(symbol, currency, amount):
"""
:param amount:
:param currency:
:param symbol:
:return:
"""
params = {"symbol": symbol,
"currency": currency,
"amount": amount}
url = "/v1/margin/orders"
return api_key_post(params, url) # 归还借贷
def repay_margin(order_id, amount):
"""
:param order_id:
:param amount:
:return:
"""
params = {"order-id": order_id,
"amount": amount}
url = "/v1/margin/orders/{0}/repay".format(order_id)
return api_key_post(params, url) # 借贷订单
def loan_orders(symbol, currency, start_date="", end_date="", start="", direct="", size=""):
"""
:param symbol:
:param currency:
:param direct: prev 向前,next 向后
:return:
"""
params = {"symbol": symbol,
"currency": currency}
if start_date:
params["start-date"] = start_date
if end_date:
params["end-date"] = end_date
if start:
params["from"] = start
if direct and direct in ["prev", "next"]:
params["direct"] = direct
if size:
params["size"] = size
url = "/v1/margin/loan-orders"
return api_key_get(params, url) # 借贷账户详情,支持查询单个币种
def margin_balance(symbol):
"""
:param symbol:
:return:
"""
params = {}
url = "/v1/margin/accounts/balance"
if symbol:
params['symbol'] = symbol return api_key_get(params, url) if __name__ == '__main__':
print (get_symbols())

HuobiServices.py

火币网API文档——REST 行情、交易API简介的更多相关文章

  1. [API]使用Blueprint来高雅的编写接口文档 前后端api文档,移动端api文档

    网址:http://apiary.io/ 介绍:一款非常强大的前后端交互api设计编辑工具(编辑器采用Markdown类似的描述标记,非常高效),高颜值的api文档,还能生成多种语言的测试代码. 中文 ...

  2. Api文档生成工具与Api文档的传播(pdf)

    点击查看apidoc生成文档demo 1 环境和工具 win10 apidoc:注释生成api文档 wkhtmltopdf:apidoc生成的是html,不适合传播,于是通过wkhtmltopdf将h ...

  3. 使用swagger实现在线api文档自动生成 在线测试api接口

    使用vs nuget包管理工具搜索Swashbuckle 然后安装便可 注释依赖于vs生成的xml注释文件

  4. 在ASP.NET Core Web API上使用Swagger提供API文档

    我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...

  5. Core Web API上使用Swagger提供API文档

    在ASP.NET Core Web API上使用Swagger提供API文档   我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的AP ...

  6. JDK8 API文档(下载)

    DK API文档 java SE 8 API文档: http://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downl ...

  7. Android Studio API 文档_下载与使用

    如何下载API 说明: 时间: 2016/7/9 根据百度经验步骤改编(百度经验), 但是比它更好, 亲测可用 1.1 下载API文档: 1.1.1 SDK Manager 1.1.2 1.1.3 ( ...

  8. SpringBoot系列: 使用 Swagger 生成 API 文档

    SpringBoot非常适合开发 Restful API程序, 我们都知道为API文档非常重要, 但要维护好难度也很大, 原因有: 1. API文档如何能被方便地找到? 以文件的形式编写API文档都有 ...

  9. 如何使用Wisdom RESTClient定制满足您个性化需求的API文档?

    Wisdom RESTClient 支持自动化测试RESTful API,输出精美的测试报告,生成精美的RESTful API文档. 这里介绍一下如何定制个性化的RESTful API文档. 定制个性 ...

随机推荐

  1. 重定向android log

    android里面的log输出以往都是在eclipse里面看,如果通过USB连接电脑,可以输出到PC上. try { //adb logcat -v threadtime > logcat.tx ...

  2. MapReduce处理HBase出错:XXX.jar is not a valid DFS filename

    原因:Hadoop文件系统没有检查路径时没有区分是本地windows系统还是Hadoop集群文件系统 解决:  只需将Map和Reduce的init方法最后一个参数(boolean addDepend ...

  3. C#实现如何判断一个数组中是否有重复的元素

    如何判断一个数组中是否有重复的元素 实现判断数组中是否包含有重复的元素方法 这里用C#代码给出实例 方法一:可以新建一个hashtable利用hashtable的Contains方法进行查找 /// ...

  4. ubuntu安装图形界面

    命令行模式的Ubuntu16.04安装图形界面 apt-get update sudo apt-get install xinit sudo apt-get install gdm sudo apt- ...

  5. 搞懂MapReduce

    MapReduce的主要思想就是将计算任务分发至多台计算机(slave),然后master综合计算机结果.所以就涉及到多台计算机通信和同步的问题,这个应该由hadoop完成,把环境配置好后就像单机操作 ...

  6. css学习_css复合选择器

    css复合选择器 a.交集选择器  (即...又...:选择器之间不能有空格) p.one{color:red;] b.并集选择器(中间由逗号隔开) p,div{color:red;} c.后代选择器 ...

  7. 23. 合并K个排序链表

    一种方法是分治  类似快排的例子. 第二种使用堆,比较好理解.  堆中保存一个元素是一个链表的头部. /** * Definition for singly-linked list. * public ...

  8. HDU 1506 & 1505 - Largest Rectangle in a Histogram & City Game

    Largest Rectangle in a Histogram Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 ...

  9. vsftpd上传文件出现553 Could not create file错误解决方法

    1.确定目录权限 2.关闭selinux

  10. linux系统操作笔记

    tar  cvf  test.tar  /etc gzip  test.tar bzep2 test.tar 归档压缩 tar czf  test.tar.gz  /etc vi  /etc/test ...