Exemplo n.º 1
0
def test_connection(access_key, secret_key):
    """通过查询账户信息测试密钥是否可用"""
    setKey(access_key, secret_key)
    from huobitrade import HBRestAPI
    api = HBRestAPI()
    try:
        account = api.get_accounts()
        if account['status'] == 'ok':
            click.secho('连接成功!', fg='blue')
            click.echo(account['data'])
        else:
            click.secho('连接失败!', fg='red')
            click.secho(account['err-msg'], fg='red')
    except Exception as e:
        click.echo(traceback.format_exc())
Exemplo n.º 2
0
# -*- coding:utf-8 -*-
"""
@author  : MG
@Time    : 2018/6/12 15:01
@File    : md.py
@contact : [email protected]
@desc    : 
"""
import logging
from huobitrade.service import HBWebsocket
from huobitrade.handler import baseHandler
from huobitrade import setKey
from config import Config
import time
logger = logging.getLogger()
setKey(Config.EXCHANGE_ACCESS_KEY, Config.EXCHANGE_SECRET_KEY)


class SimpleHandler(baseHandler):
    def handle(self, msg):
        logger.debug(msg)


hb = HBWebsocket()
hb.sub_dict['ethbtc'] = {'id': '', 'topic': 'market.ethbtc.kline.1min'}
handler = SimpleHandler('simple handler')
hb.register_handler(handler)
hb.run()

time.sleep(3)  # run之后连接需要一丢丢时间,sleep一下再订阅
# hb.sub_kline('ethbtc', '1min')
from huobitrade import setKey
from config import Config
from huobifeeder.backend import engine_md
from huobifeeder.utils.db_utils import with_db_session
from huobifeeder.utils.fh_utils import try_n_times
from huobifeeder.backend.orm import SymbolPair
from huobifeeder.backend.check import check_redis
import time
from threading import Thread
from huobifeeder.backend.orm import MDTick, MDMin1, MDMin1Temp, MDMin60, MDMin60Temp, MDMinDaily, MDMinDailyTemp
from huobifeeder.backend.handler import DBHandler, PublishHandler, HeartBeatHandler
from sqlalchemy import func

logger = logging.getLogger()
# 设置秘钥
setKey(Config.EXCHANGE_ACCESS_KEY, Config.EXCHANGE_SECRET_KEY)


class MDFeeder(Thread):
    """接受订阅数据想redis发送数据"""
    def __init__(self, init_symbols=False, do_fill_history=False):
        super().__init__(name='huobi websocket', daemon=True)
        self.hb = HBWebsocket()
        self.api = HBRestAPI()
        self.init_symbols = init_symbols
        self.logger = logging.getLogger(self.__class__.__name__)
        self.do_fill_history = do_fill_history
        self.heart_beat = HeartBeatHandler()

        # 加载数据库表模型(已经废弃,因为需要支持多周期到不同的数据库表)
        # self.table_name = MDMin1Temp.__tablename__
Exemplo n.º 4
0
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gevent.monkey
gevent.monkey.patch_all()

from flask import Flask, render_template, g, session
from flask_socketio import SocketIO
import json
from huobitrade import HBRestAPI, setKey, HBWebsocket, logger
import json
setKey('', '')

app = Flask(__name__)
socketio = SocketIO(app)
# logger.setLevel('DEBUG')

@app.route('/')
def backtest():
    return render_template('index.html')

@app.route('/data/get_symbols')
def get_symbols():
    api = HBRestAPI()
    symbols = api.get_symbols()['data']
    return json.dumps(symbols)
Exemplo n.º 5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/25 0025 12:39
# @Author  : Hadrianl
# @File    : auth_test.py
# @Contact   : [email protected]
"""
该例子仅限于用来测试鉴权接口是否能鉴权成功
"""

from huobitrade.service import HBWebsocket
from huobitrade import setKey, logger
logger.setLevel('DEBUG')
setKey('access_key', 'secret_key')

auhb = HBWebsocket(auth=True)

auhb.after_auth(auhb.sub_accounts)


@auhb.after_auth
def init_sub():
    auhb.sub_accounts()
    auhb.sub_orders()


auhb.run()
Exemplo n.º 6
0
def run(file, access_key, secret_key, **kwargs):
    """命令行运行huobitrade"""
    if file:
        import sys
        file_path, file_name = os.path.split(file)
        sys.path.append(file_path)
        strategy_module = importlib.import_module(
            os.path.splitext(file_name)[0])
        init = getattr(strategy_module, 'init', None)
        handle_func = getattr(strategy_module, 'handle_func', None)
        schedule = getattr(strategy_module, 'schedule', None)
    else:
        init, handle_func, scedule = [None] * 3

    setKey(access_key, secret_key)
    url = kwargs.get('url')
    hostname = 'api.huobi.br.com'
    if url:
        hostname = urlparse(url).hostname
        setUrl('https://' + hostname, 'https://' + hostname)

    reconn = kwargs.get('reconn', -1)
    from huobitrade import HBWebsocket, HBRestAPI
    from huobitrade.datatype import HBMarket, HBAccount, HBMargin
    restapi = HBRestAPI(get_acc=True)
    ws = HBWebsocket(host=hostname, reconn=reconn)
    auth_ws = HBWebsocket(host=hostname, auth=True, reconn=reconn)
    data = HBMarket()
    account = HBAccount()
    margin = HBMargin()
    ws_open = False
    ws_auth = False

    @ws.after_open
    def _open():
        nonlocal ws_open
        click.echo('行情接口连接成功')
        ws_open = True

    @auth_ws.after_auth
    def _auth():
        nonlocal ws_auth
        click.echo('鉴权接口鉴权成功')
        ws_auth = True

    ws.run()
    auth_ws.run()

    for i in range(10):
        time.sleep(3)
        click.echo(f'连接:第{i+1}次连接')
        if ws_open & ws_auth:
            break
    else:
        ws.stop()
        auth_ws.stop()
        raise Exception('连接失败')
    if init:
        init(restapi, ws, auth_ws)

    if handle_func:
        for k, v in handle_func.items():
            if k.split('.')[0].lower() == 'market':
                ws.register_handle_func(k)(v)
            else:
                auth_ws.register_handle_func(k)(v)

    if schedule:
        print('testing')
        from huobitrade.handler import TimeHandler
        interval = scedule.__kwdefaults__['interval']
        timerhandler = TimeHandler('scheduler', interval)
        timerhandler.handle = lambda msg: schedule(restapi, ws, auth_ws)
        timerhandler.start()

    while True:
        try:
            code = click.prompt('huobitrade>>')
            if code == 'exit':
                if click.confirm('是否要退出huobitrade'):
                    break
                else:
                    continue
            else:
                result = eval(code)
                click.echo(result)
        except Exception as e:
            click.echo(traceback.format_exc())

    ws.stop()
    auth_ws.stop()
Exemplo n.º 7
0
"""
该demo是用于模拟较为复杂的交易策略,
同时用上了普通行情websocket,鉴权websocket与restfulapi,
包括展示如何初始化订阅,以及如果注册handler等

"""


from huobitrade.service import HBWebsocket, HBRestAPI
from huobitrade.handler import BaseHandler
from huobitrade import setKey, logger
from functools import partial
import time
# logger.setLevel('DEBUG')
setKey('access_key', 'secret_key')

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

    def handle(self, topic, msg):  # 实现handle来处理websocket推送的msg
        print(topic)

# 初始化restapi
restapi = HBRestAPI(get_acc=True)
print(restapi.get_accounts())  # 请求账户

# 构造异步请求
rep1 = restapi.get_timestamp(_async=True)
rep2 = restapi.get_all_last_24h_kline(_async=True)
Exemplo n.º 8
0
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gevent.monkey
gevent.monkey.patch_all()

from flask import Flask, render_template, g, session
from flask_socketio import SocketIO
import json
from huobitrade import HBRestAPI, setKey, HBWebsocket, logger
import json
setKey('', '')

app = Flask(__name__)
socketio = SocketIO(app)
# logger.setLevel('DEBUG')


@app.route('/')
def backtest():
    return render_template('index.html')


@app.route('/data/get_symbols')
def get_symbols():
    api = HBRestAPI()
    symbols = api.get_symbols()['data']