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. Oracle:使用nginx做为代理访问

    nginx 必须启用 启用 --with-stream 模块. 可下载源码编译. nginx.conf的配置: worker_processes ; events { worker_connectio ...

  2. linux:rsync + inotifywait 实现【准实时】同步

    直接上脚本 #!/bin/bash export PATH=./sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:$PATH src=/tmp1 #dest=ro ...

  3. [Model] ResNet

    ResNet引入了残差网络结构(residual network),通过残差网络,可以把网络层弄的很深,据说现在达到了1000多层,最终的网络分类的效果也是非常好 Ref: http://blog.c ...

  4. H5 拖拽读取文件和文件夹

    1)拖拽方面的重点是:ondragover 事件 和 ondrop 事件 ondragover 是必须的,ondragover 事件里禁用掉 html 的默认事件,否则 ondrop 事件将无效(直接 ...

  5. linux下git怎么保存账号密码

    我是用 shell 命令来执行 git 操作的,所以就决定在 --global 配置一下用户名和密码,不用每次手动输入了. 设置步骤 1. 首先需要 ftp 连接到你的 Linux 服务器,在根目录( ...

  6. day_6.26 反射

    #utf-8 #2018-6-26 17:58:36 #反射,, 应用:从类里面获取字符串 #在python中万物皆对象 class Teacher: dic = {"查看学生信息" ...

  7. 免费的SSL证书(LINUX)

    贫穷限制了我的SSL. 说起来也简单,免费的SSL证书授权机构,我使用的是Certbot 选择服务器开启的服务,像我php之流,无非apache和nginx,然后选择使用的服务器类型.嗯,补充一句,这 ...

  8. 不偏移的天地图地图服务-SuperMap版

    在<不偏移的天地图地图服务-ArcGIS版>中,提供了相应的服务地址:而SuperMap中,则是将纠偏的方法集成到程序中,只需要修改一个配置参数,则可以实现天地图的纠偏. 打开Web型数据 ...

  9. 如何去除Launcher默认的google search bar?

    JB2/JB3/JB5/JB9版本: 1. 请修改 Launcher2/res/layout/qsb_bar.xml,如下:<include android:id="@+id/qsb_ ...

  10. Flask web开发之路五

    Jinjia2模板 紧接着上篇博客,接下去写if条件判断和for循环遍历以及过滤器 if条件判断 主app文件代码: from flask import Flask,render_template a ...