hadrianl / huobi

火币的行情交易的python实现
MIT License
154 stars 64 forks source link
coinbase-api huobi pypi python rest-api trading-systems websocket-api websockets

火币API的Python版

QQ Group

Notice

Lastest

PyPI GitHub forks GitHub stars build license PyPI - Python Version

1. Installation

pip install huobitrade

2. Usage

2.1 huobitrade CLI Tool

2.2.1 WebSocket API

from huobitrade.service import HBWebsocket

hb = HBWebsocket()  # 可以填入url参数,默认是api.huobi.br.com
@hb.after_open  # 使用装饰器注册函数,当ws连接之后会调用函数,可以实现订阅之类的
def sub_depth():
    hb.sub_depth('ethbtc')

hb.run()  # 开启websocket进程

# --------------------------------------------
hb.sub_kline('ethbtc', '1min')  # 订阅数据
@hb.register_handle_func('market.ethbtc.kline.1min')  # 注册一个处理函数,最好的处理方法应该是实现一个handler
def handle(msg):
    print('handle:', msg)

hb.unregister_handle_func(handle, 'market.ethbtc.kline.1min')  # 释放处理函数

# --------------------------------------------
# websocket请求数据是异步请求回调,所以先注册一个回调处理函数,再请求
@hb.register_onRsp('market.btcusdt.kline.1min')
def OnRsp_print(msg):
    print(msg)

hb.req_kline('btcusdt', '1min')
hb.unregister_onRsp('market.btcusdt.kline.1min')  # 注销某topic的请求回调处理

2.2.2 Auth WebSocket API

from huobitrade import setKey
from huobitrade.service import HBWebsocket
setKey('your acess_key', 'you secret_key')
hb = HBWebsocket(auth=True)  # 可以填入url参数,默认是api.huobi.br.com
@hb.after_auth  # 会再鉴权成功通过之后自动调用
def sub_accounts():
    hb.sub_accounts()

hb.run()  # 开启websocket进程

@hb.register_handle_func('accounts')  # 注册一个处理函数,最好的处理方法应该是实现一个handler
def auth_handle(msg):
    print('auth_handle:', msg)

2.3 Restful API

from huobitrade.service import HBRestAPI
from huobitrade import setKey
# setUrl('', '')
setKey('your acess_key', 'you secret_key')  # setKey很重要,最好在引入其他模块之前先setKey,鉴权ws和restapi的部分函数是基于密钥
api = HBRestAPI(get_acc=True)  # get_acc参数默认为False,初始化不会取得账户ID,需要ID的函数无法使用.也可用api.set_acc_id('you_account_id')
print(api.get_timestamp())

api = HBRestAPI(get_acc=True) # 异步请求
klines = api.get_kline('omgeth', '1min', _async=True)
symbols = api.get_symbols(_async=True)
results = api.async_request([klines, symbols])
for r in results:
    print(r)

2.4 Message Handler

from huobitrade.handler import BaseHandler
from huobitrade.utils import handler_profiler
from huobitrade import setKey
from huobitrade.service import HBWebsocket
setKey('your acess_key', 'you secret_key')
hb = HBWebsocket(auth=True)  # 可以填入url参数,默认是api.huobi.br.com

class MyHandler(BaseHandler):
    def __init__(self, topic, *args, **kwargs):
        BaseHandler.__init__(self, 'just Thread name', topic)

    @handler_profiler('profiler.csv')  #  可以加上这个装饰器来测试handle函数的执行性能,加参数会输出到单独文件
    def handle(self, topic, msg):  # 实现handle来处理websocket推送的msg
        print(topic, msg)

handler = MyHandler('market.ethbtc.kline.1min')  # topic为str或者list
handler.add_topic('market.ethbtc.kline.5min')  # 为handler增加处理topic(remove_topic来删除)
hb.register_handler(handler)  # 通过register来把handler注册到相应的topic
from huobitrade.handler import DBHandler
from huobitrade import setKey
from huobitrade.service import HBWebsocket
setKey('your acess_key', 'you secret_key')
hb = HBWebsocket(auth=True)  # 可以填入url参数,默认是api.huobi.br.com
handler = DBHandler()  # topic为空的话,会对所有topic的msg做处理
hb.register_handler(handler)

2.5 Latest Message Handler

2.6 HBData

from huobitrade import setKey
setKey('acess_key', 'secret_key')
from huobitrade.datatype import HBMarket, HBAccount, HBMargin

data = HBMarket()  # 行情接口类
account = HBAccount()  # 交易接口类
margin = HBMargin()  # 借贷接口类

data.omgeth
 # <Symbol:omgeth-{'base-currency': 'omg', 'quote-currency': 'eth', 'price-precision': 6, 'amount-precision': 4, 'symbol-partition': 'main'}>
data.omgeth.kline
 # <<class 'huobitrade.datatype.HBKline'> for omgeth>
data.omgeth.depth
 # <<class 'huobitrade.datatype.HBDepth'> for omgeth>
data.omgeth.ticker
 # <<class 'huobitrade.datatype.HBTicker'> for omgeth>
data.omgeth.kline._1min_200  # period前面加'_', 后面加数量最大值为2000
data.omgeth.kline.last
data.omgeth.kline.last_24_hour
data.omgeth.depth.step0  # step0,1,2,3,4,5
data.omgeth.ticker.last  # 最新的一条tick
data.omgeth.ticker.last_20  # last_1至last_2000
data.all_24h_kline  # 当前所有交易对的ticker
account.Detail  # 所有账户明细
account.balance_XXXX  # XXXX为account_id,某账户的结余, 引用结余信息会自动更新
account.order  # 账户的订单类
account.order['order_id']  # 查询某order明细,或者用get方法
account.order.send('account_id', 1, 'omgeth', 'buy-limit', 0.001666)  # 发送订单
account.order.batchcancel(['order_id1', 'order_id2'])
account.order + [1, 'omgeth', 'buy-limit', 0.001666] # 发送订单
account.order + {'acc_id': 'your_account_id', 'amount': 1, 'symbol': 'omgeth', 'type': 'buy-limit', 'price': 0.001666}
account.order - 'order_id'  # 取消订单
account.order - ['order_id1', 'order_id2'] # 批量取消订单
account.trade.get_by_id('order_id')  # 某账户的成交类(即火币的matchresults),也可以直接索引
margin.transferIn('ethusdt', 'eth', 1)
ethusdt_margin_info = margin['ethusdt']  # 或者用getBalance
ethusdt_margin_info.balance  # ethusdt交易对的保证金结余信息

3. Extra