import requests
import traceback
import logging
import hmac
import json
import hashlib
import base64
import datetime
from urllib import parse
class HuobiApi(object):
def __init__(self):
self.host = 'https://api.huobi.pro'
self.timeout = 10
self.ACCESS_KEY = '你自己的'
self.SECRET_KEY = '你自己的'
self.main_account_id = '你自己的'
def create_signature(self, method, url, builder):
try:
ret = {
"code": 0,
"message": ""
}
timestamp = self.utc_now()
builder.put_url("AccessKeyId", self.ACCESS_KEY)
builder.put_url("SignatureVersion", "2")
builder.put_url("SignatureMethod", "HmacSHA256")
builder.put_url("Timestamp", timestamp)
# builder.put_url("order-id", self.main_account_id)
host = parse.urlparse(url=url).hostname
path = parse.urlparse(url=url).path
print(f'path - {path}')
# 对参数进行排序:
keys = sorted(builder.param_map.keys())
# 加入&
qs0 = '&'.join(
['%s=%s' % (key, parse.quote(builder.param_map[key], safe=''))
for key
in keys])
print(f'qs0 -> {qs0}')
# 请求方法,域名,路径,参数 后加入`\n`
payload0 = '%s\n%s\n%s\n%s' % (method, host, path, qs0)
print(f'\n\n\n{payload0}\n\n\n')
dig = hmac.new(self.SECRET_KEY.encode('utf-8'),
msg=payload0.encode('utf-8'),
digestmod=hashlib.sha256).digest()
# 进行base64编码
s = base64.b64encode(dig).decode()
builder.put_url("Signature", s)
print(f'ret -> {ret}')
return ret
except:
print(traceback.format_exc())
def depth(self, symbol, depth=5, type='step0'):
try:
url = f'https://api.huobi.pro/market/depth?depth={depth}&symbol={symbol}&type={type}'
res = self.call(method='GET', url=url, header={})
return res
except Exception:
print(traceback.format_exc())
def create_order(self, symbol, type, amount, price):
try:
method, req_url = 'POST', '/v1/order/orders/place'
header = {"Content-Type": "application/json"}
post_body = {'account-id': self.main_account_id, 'amount': amount,
'price': price, 'symbol': symbol,
'type': type, 'source': 'api'}
# 17388210005
builder = UrlParamsBuilder()
print(f'初始时的builder - {builder}')
self.create_signature(method=method,
url='https://api.huobi.pro/v1/order/orders/place',
builder=builder)
# sign后
url = 'https://api.huobi.pro/v1/order/orders/place' + builder.build_url()
res = self.call(method=method, url=url, header=header,
post_body=post_body)
print(f'res - {res}')
return res
except Exception:
print(traceback.format_exc())
def order_detail(self, order_id):
try:
method = 'GET'
host_path = f'https://api.huobi.pro/v1/order/orders/{order_id}'
builder = UrlParamsBuilder()
self.create_signature(method=method, url=host_path, builder=builder)
url = host_path + builder.build_url()
res = self.call(method=method, url=url, header={})
return res
except Exception:
print(traceback.format_exc())
def cancel_order(self, order_id):
try:
header = {"Content-Type": "application/json"}
builder = UrlParamsBuilder()
host_path = f'https://api.huobi.pro/v1/order/orders/{order_id}/submitcancel'
self.create_signature(method='POST',
url=host_path,
builder=builder)
url = host_path + builder.build_url()
print(f'url -> {url}')
res = self.call(method='POST', url=url, header=header, post_body={})
print(f'res - {res}')
return res
except Exception:
print(traceback.format_exc())
def call(self, method, url, header, post_body=None):
try:
if method == "GET":
# print("call_sync url : " , request.host + request.url)
response = requests.get(url=url,
headers=header, timeout=self.timeout)
# print("receive data : " + response.text)
if response.status_code == 200 and response.content:
return response.json()
else:
return {'code': 1, 'message': ''}
elif method == "POST":
print(url)
print(json.dumps(post_body))
print(header)
response = requests.post(url,
data=json.dumps(post_body),
headers=header, timeout=self.timeout)
if response.status_code == 200 and response.content:
return response.json()
else:
return {'code': 1, 'message': ''}
except:
print(traceback.format_exc())
def utc_now(self):
return datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
class UrlParamsBuilder(object):
def __init__(self):
self.param_map = dict()
self.post_map = dict()
def put_url(self, name, value):
if value is not None:
if isinstance(value, list):
self.param_map[name] = value
else:
self.param_map[name] = str(value)
def put_post(self, name, value):
if value is not None:
if isinstance(value, list):
self.post_map[name] = value
else:
self.post_map[name] = str(value)
def build_url(self):
if len(self.param_map) == 0:
return ""
print(f'self.param_map -> {self.param_map}')
encoded_param = parse.urlencode(self.param_map)
return "?" + encoded_param
def build_url_to_json(self):
return json.dumps(self.param_map)
if __name__ == '__main__':
__test_case = HuobiApi()
# res = __test_case.create_order("eoseth", 'buy-limit', amount='11',
# price='0.01162')
# res = __test_case.cancel_order(order_id='82538811013')
# res = __test_case.depth('btcusdt')
res = __test_case.order_detail('82538811013')
print(res)
# {'status': 'ok', 'data': '82538811013'}
python 我改写的火币api
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...