Example #1
0
def get_instruments(exchange, sec_type=None, is_active=1):
    '''

    :param exchange:
    :param sec_type:
    :param is_active:
    :return:
    '''

    instrus = []
    if exchange == 'huobipro':
        res = hb.get_symbols()
        if res['status'] == 'ok':
            data = res['data']
            for each in data:
                instru = Instrument()
                instru.exchange = exchange
                instru.symbol = each['base-currency'] + each['quote-currency']
                instru.base_currency = each['base-currency']
                instru.quote_currency = each['quote-currency']
                instru.amount_precision = each['amount-precision']
                instru.price_precision = each['price-precision']
                instru.symbol_partition = each['symbol-partition']

                instrus = instrus + [instru]
        else:
            logger.warn('No instruments found')

    return instrus
Example #2
0
def get_positions(exchange):
    '''

    :param exchange:
    :return:
    '''

    positions = []
    if exchange == 'huobipro':

        account_id = get_accounts(exchange=exchange)

        # 先获取融资账户资金
        margin_account = account_id['margin']['id']
        res = hb.get_balance(acct_id=margin_account)
        if res['status'] == 'ok':
            balance = res['data']
            for each in balance:
                if each['trade'] > 0 or each['frozen'] > 0:
                    position = Position()
                    position.exchange = exchange
                    position.account_id = account_id
                    position.available = each['trade']
                    position.order_frozen = each['frozen']
                    position.volume = each['trade'] + each['frozen']
                    positions = positions + [position]
        else:
            logger.warn(res['err-code'] + ':' + res['err-msg'])

    return positions
Example #3
0
def get_last_ticks(exchange, symbol_list):
    '''

    :param exchange:
    :param symbol_list:
    :return:
    '''
    ticks = []
    if exchange == 'huobipro':
        for each in symbol_list:
            tick_res = hb.get_ticker(symbol=each)
            # depth_res = hb.get_depth(symbol=each, type='step5')
            if tick_res['status'] == 'ok':
                data = tick_res['tick']
                tick = Tick()
                tick.exchange = exchange
                tick.sec_id = each
                tick.utc_time = tick_res['ts']
                tick.strtime = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.localtime(tick_res['ts'] / 1000))
                tick.open = data['open']
                tick.high = data['high']
                tick.low = data['low']
                tick.last_price = data['close']
                tick.last_volume = data['vol']
                tick.last_amount = data['amount']
                tick.last_count = data['count']
                tick.asks = [tuple(data['ask'])]
                tick.bids = [tuple(data['bid'])]

                ticks = ticks + [tick]
            else:
                logger.warn('No data fechted!')

    return ticks
Example #4
0
def unlock():
    try:
        data = json.loads(flask.request.data)
        uuid = data.get("uuid", None)
        params = {"uuid": uuid}
        util.check_param(**params)

        token = flask.request.headers.get("token", None)
        if (token not in util.session) or \
                (not conductor.user.is_admin_user(util.session[token])):
            message = {
                "error": "limited authority",
                "code": 401,
                "tips": util.get_tips_dict(10006)
            }
            message = json.dumps(message)
            logger.debug("POST /user/v1/unlock - 401")
            logger.warn("unlock user %s WARNING: limited authority." % uuid)
            return message, 401

        conductor.user.unlock(uuid)
    except DuplicateException as e:
        message = {
            "success": e.error_message,
            "code": e.httpcode
        }
        message = json.dumps(message)
        logger.info(e.error_message)
        logger.debug("POST /user/v1/unlock - %s" % e.httpcode)
        return message, e.httpcode
    except STPHTTPException as e:
        message = {
            "error": e.error_message,
            "code": e.httpcode,
            "tips": e.tip
        }
        message = json.dumps(message)
        logger.debug("POST /user/v1/unlock - %s" % e.httpcode)
        logger.error("unlock user ERROR:\n %s" % traceback.format_exc())
        return message, e.httpcode
    except json.decoder.JSONDecodeError:
        logger.error("unlock user ERROR: JSON decode failed.\n %s" %
                     traceback.format_exc())
        logger.debug("POST /user/v1/unlock - 406")
        message = {
            "error": "invalid POST request: JSON decode failed.",
            "code": 406,
            "tips": util.get_tips_dict(10004)
        }
        message = json.dumps(message)
        return message, 406

    logger.info("unlock user %s success." % uuid)
    message = {
        "success": "unlock user %s success." % uuid,
        "code": 200
    }
    message = json.dumps(message)
    return message, 200
Example #5
0
def get_positions(exchange):
    '''

    :param exchange:
    :return:
    '''

    positions = []
    if exchange == 'huobipro':

        accounts = get_accounts(exchange=exchange)

        # 先获取融资账户资金
        margin_account = accounts['margin']['id']
        res = hb.get_balance(acct_id=margin_account)
        if res['status'] == 'ok':
            account_info = res['data']
            account_id = account_info['id']
            account_type = account_info['type']
            account_status = account_info['state']
            account_balance = account_info['list']

            data_df = pd.DataFrame(data=account_balance)
            data_df.index = data_df['currency']
            data_new = pd.DataFrame(
                [],
                index=np.unique(data_df['currency']),
                columns=['trade', 'frozen', 'loan', 'interest'])
            data_new['trade'] = data_df[data_df['type'] == 'trade']['balance']
            data_new['frozen'] = data_df[data_df['type'] ==
                                         'frozen']['balance']
            data_new['loan'] = data_df[data_df['type'] == 'loan']['balance']
            data_new['interest'] = data_df[data_df['type'] ==
                                           'interest']['balance']
            data_new = data_new.astype('float')
            tmp = data_new.apply(lambda x: sum(np.abs(x)), axis=1)
            data_selected = data_new.loc[tmp[tmp > 0].index]

            for each in data_selected.index:
                position = Position()
                position.exchange = exchange
                position.account_id = account_id
                position.account_type = account_type
                position.account_status = account_status

                position.sec_id = each
                position.available = float(data_selected.loc[each]['trade'])
                position.order_frozen = float(
                    data_selected.loc[each]['frozen'])
                position.amount = position.available + position.order_frozen
                position.loan = data_selected.loc[each]['loan']
                position.interest = data_selected.loc[each]['interest']

                positions = positions + [position]
        else:
            logger.warn(res['err-code'] + ':' + res['err-msg'])

    return positions
Example #6
0
def cancel_order(exchange, cl_ord_id=None):
    '''
    取消订单
    :param exchange: 交易所
    :param order_id: 订单号
    :return:
    '''

    if exchange == 'huobipro':
        res = hb.cancel_order(order_id=cl_ord_id)
        if res['status'] == 'ok':
            return res['data']
        else:
            logger.warn(res['err-code'] + ':' + res['err-msg'])
            return None
Example #7
0
def update_station():
    try:
        data = json.loads(flask.request.data)
        token = flask.request.headers.get("token", None)
        if (token not in util.session) or \
                (not conductor.user.is_admin_user(util.session[token])):
            message = {
                "error": "limited authority",
                "code": 401,
                "tips": util.get_tips_dict(10006)
            }
            message = json.dumps(message)
            logger.warn("update subway station WARNING: limited authority.")
            logger.debug("PUT /station/v1/update - 401")
            return message, 401
    except json.decoder.JSONDecodeError:
        logger.error("update subway station ERROR: JSON decode failed.\n %s" %
                     traceback.format_exc())
        logger.debug("PUT /station/v1/update - 406")
        message = {
            "error": "invalid PUT request: JSON decode failed.",
            "code": 406,
            "tips": util.get_tips_dict(10004)
        }
        message = json.dumps(message)
        return message, 406

    uuid = data.get("uuid", None)
    new_name = data.get("name", None)
    try:
        params = {"uuid": uuid, "name": new_name}
        util.check_param(**params)
        conductor.station.update(uuid, new_name)
    except STPHTTPException as e:
        message = {"error": e.error_message, "code": e.httpcode, "tips": e.tip}
        message = json.dumps(message)
        logger.error("update subway station %s ERROR:\n%s" %
                     (uuid, traceback.format_exc()))
        logger.debug("PUT /station/v1/update - %s" % e.httpcode)
        return message, e.httpcode

    message = {
        "success": "update subway station %s success." % uuid,
        "code": 200
    }
    message = json.dumps(message)
    logger.debug("PUT /station/v1/update - 200")
    return message, 200
Example #8
0
def delete():
    try:
        data = json.loads(flask.request.data)
    except json.decoder.JSONDecodeError:
        logger.error("delete subway line ERROR: JSON decode failed.\n %s" %
                     traceback.format_exc())
        logger.debug("DELETE /line/v1/delete - %s" % http_code.NotAcceptable)
        message = {
            "error": "invalid DELETE request: JSON decode failed.",
            "code": http_code.NotAcceptable,
            "tips": util.get_tips_dict(10004)
        }
        message = json.dumps(message)
        return message, http_code.NotAcceptable

    token = flask.request.headers.get("token", None)
    if (token not in util.session) or \
            (not conductor.user.is_admin_user(util.session[token])):
        message = {
            "error": "limited authority",
            "code": http_code.Unauthorized,
            "tips": util.get_tips_dict(10006)
        }
        message = json.dumps(message)
        logger.warn("delete subway line WARNING: limited authority.")
        logger.debug("DELETE /line/v1/delete - %s" % http_code.Unauthorized)
        return message, http_code.Unauthorized

    uuid = data.get("uuid", None)
    logger.info("Begin to delete subway line %s." % uuid)
    try:
        kwargs = {"uuid": uuid}
        util.check_param(**kwargs)
        conductor.line.delete_subway_line(uuid)
    except STPHTTPException as e:
        message = {"error": e.error_message, "code": e.httpcode, "tips": e.tip}
        message = json.dumps(message)
        logger.error("delete subway line %s ERROR:\n%s" %
                     (uuid, traceback.format_exc()))
        logger.debug("DELETE /line/v1/delete - %s" % e.httpcode)
        return message, e.httpcode

    message = {
        "success": "delete subway line %s success." % uuid,
        "code": http_code.OK
    }
    message = json.dumps(message)
    return message, http_code.OK
Example #9
0
def add():
    try:
        data = json.loads(flask.request.data)
    except json.decoder.JSONDecodeError:
        logger.error("add subway line ERROR: JSON decode failed.\n %s" %
                     traceback.format_exc())
        logger.debug("POST /line/v1/add - 406")
        message = {
            "error": "invalid POST request: JSON decode failed.",
            "code": http_code.NotAcceptable,
            "tips": util.get_tips_dict(10004)
        }
        message = json.dumps(message)
        return message, http_code.NotAcceptable

    token = flask.request.headers.get("token", None)
    if (token not in util.session) or \
            (not conductor.user.is_admin_user(util.session[token])):
        message = {
            "error": "limited authority",
            "code": http_code.Unauthorized,
            "tips": util.get_tips_dict(10006)
        }
        message = json.dumps(message)
        logger.warn("add subway line WARNING: limited authority.")
        logger.debug("POST /line/v1/add - 401")
        return message, http_code.Unauthorized

    name = data.get("name", None)
    try:
        logger.info("Begin to add subway line %s." % name)
        util.check_param(name=name)
        conductor.line.add_subway_line(name)
    except STPHTTPException as e:
        message = {"error": e.error_message, "code": e.httpcode, "tips": e.tip}
        message = json.dumps(message)
        logger.error("add subway line %s ERROR:\n%s" %
                     (name, traceback.format_exc()))
        logger.debug("POST /line/v1/add - %s" % e.httpcode)
        return message, e.httpcode

    message = {
        "success": "add subway line %s success." % name,
        "code": http_code.OK
    }
    message = json.dumps(message)
    return message, http_code.OK
Example #10
0
def get_bars(exchange,
             symbol_list,
             bar_type,
             begin_time='',
             end_time='',
             size=0):
    '''
    提取指定时间段的历史Bar数据,支持单个代码提取或多个代码组合提取。
    :param symbol_list: 证券代码, 带交易所代码以确保唯一,如SHSE.600000,同时支持多只代码
    :param bar_type: bar周期,1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
    :param begin_time: 开始时间, 如2015-10-30 09:30:00
    :param end_time: 结束时间, 如2015-10-30 15:00:00
    :param size: 取数数量,[1,2000]
    :return:
    '''

    bars = []
    for each_sec in symbol_list:

        res = hb.get_kline(symbol=each_sec, period=bar_type, size=size)
        if res['status'] == 'ok':
            data = res['data']
            for each_bar in data:
                bar = Bar()
                bar.exchange = exchange
                bar.sec_id = each_sec
                bar.volume = each_bar['vol']
                bar.amount = each_bar['amount']
                bar.open = each_bar['open']
                bar.high = each_bar['high']
                bar.low = each_bar['low']
                bar.close = each_bar['close']
                bar.bar_type = bar_type
                bar.utc_time = each_bar['id']
                bar.strtime = time.strftime("%Y-%m-%d %H:%M:%S",
                                            time.localtime(each_bar['id']))

                bars = bars + [bar]
        else:
            logger.warn(res['err-code'] + ":" + res['error-msg'])

    return bars
Example #11
0
def user_list():
    token = flask.request.headers.get("token", None)
    if (token not in util.session) or \
            (not conductor.user.is_admin_user(util.session[token])):
        message = {
            "users": [],
            "error": "limited authority",
            "code": 401,
            "tips": util.get_tips_dict(10006)
        }
        message = json.dumps(message)
        logger.debug("GET /user/v1/users - 401")
        logger.warn("Can not get user list info: limited authority.")
        return message, 401

    users = conductor.user.users()
    message = {"users": users, "code": 200}
    message = json.dumps(message)
    logger.debug("GET /user/v1/users - 200")
    return message, 200
Example #12
0
def get_last_bars(exchange, symbol_list, bar_type):
    '''

    :param symbol_list:
    :param bar_type: {1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
    :return:
    '''

    bars = []
    if exchange == 'huobipro':

        for each in symbol_list:
            bar_res = hb.get_kline(symbol=each, period=bar_type, size=1)
            if bar_res['status'] == 'ok':
                data = bar_res['data'][0]
                bar = Bar()
                bar.exchange = exchange
                bar.sec_id = each
                bar.bar_type = bar_type
                bar.utc_time = data['id']
                bar.utc_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                             time.localtime(data['id']))
                bar.open = data['open']
                bar.high = data['high']
                bar.low = data['low']
                bar.close = data['close']
                bar.volume = data['vol']
                bar.amount = data['amount']
                bar.count = data['count']
                bar.utc_endtime = bar_res['ts']
                bar.strendtime = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.localtime(bar_res['ts'] / 1000))

                bars = bars + [bar]
            else:
                logger.warn('No bar data fetched!')

    return bars
Example #13
0
def get_order(exchange, cl_ord_id):
    '''
    获取历史订单信息
    :param cl_ord_id:
    :return:
    '''

    if exchange == 'huobipro':
        res = hb.order_info(cl_ord_id)
        if res['status'] == 'ok':
            data = res['data']
            order = Order()
            order.exchange = exchange
            order.account_id = data['account-id']
            order.cl_ord_id = cl_ord_id
            order.order_id = data['id']
            order.order_src = data['source']
            order.status = data['state']
            order.sec_id = data['symbol']
            order.order_type = data['type']
            order.side = data['type']
            order.position_effect = data['type']
            order.sending_time = data['created-at']
            order.transact_time = data['finished-at']
            order.volume = float(data['amount'])
            order.price = float(data['price'])
            order.filled_amount = float(data['field-cash-amount'])
            order.filled_fee = float(data['field-fees'])
            order.filled_volume = float(data['field-amount'])
            if (order.filled_volume > 0):
                order.filled_vwap = round(order.filled_amount /
                                          order.filled_volume, 4)  ## 已成交均价

            return order
        else:
            logger.warn(res['err-code'] + ":" + res['err-msg'])
            return None
Example #14
0
def update(context):
    try:
        data = json.loads(flask.request.data)
    except json.decoder.JSONDecodeError:
        logger.error("modify subway line ERROR: JSON decode failed.\n %s" %
                     traceback.format_exc())
        logger.debug("PUT /line/v1/modify/%s - 406" % context)
        message = {
            "error": "invalid PUT request: JSON decode failed.",
            "code": http_code.NotAcceptable,
            "tips": util.get_tips_dict(10004)
        }
        message = json.dumps(message)
        return message, http_code.NotAcceptable

    token = flask.request.headers.get("token", None)
    if (token not in util.session) or \
            (not conductor.user.is_admin_user(util.session[token])):
        message = {
            "error": "limited authority",
            "code": http_code.Unauthorized,
            "tips": util.get_tips_dict(10006)
        }
        message = json.dumps(message)
        logger.warn("update subway line WARNING: limited authority.")
        logger.debug("PUT /line/v1/modify/%s - 401" % context)
        return message, http_code.Unauthorized

    if context == "name":
        uuid = data.get("uuid", None)
        new_name = data.get("name", None)
        try:
            param = {"uuid": uuid, "name": new_name}
            util.check_param(**param)
            conductor.line.update_line(**param)
        except STPHTTPException as e:
            message = {
                "error": e.error_message,
                "code": e.httpcode,
                "tips": e.tip
            }
            message = json.dumps(message)
            logger.error("update subway line %s name ERROR:\n%s" %
                         (uuid, traceback.format_exc()))
            logger.debug("PUT /line/v1/modify/name - %s" % e.httpcode)
            return message, e.httpcode

        message = {
            "success": "update subway line %s success." % uuid,
            "code": http_code.OK
        }
        message = json.dumps(message)
        return message, http_code.OK
    else:
        message = {
            "error": "unknown modify request - '%s'" % context,
            "code": http_code.NotFound,
            "tips": util.get_tips_dict(10007)
        }
        message = json.dumps(message)
        return message, http_code.NotFound
Example #15
0
def close_short(exchange, sec_id, price, volume):
    '''
    平空仓,平空仓的流程是,买入数字货币,然后还贷
    :param exchange: string	交易所代码,如火币网:huobipro,OKCoin: okcoin
    :param sec_id: string   证券代码,如btcusdt
    :param price: float     委托价,如果price=0,为市价单,否则为限价单
    :param volume: float	委托量
    :return: 委托下单生成的Order对象
    '''

    myorder = Order()
    myorder.exchange = exchange
    myorder.sec_id = sec_id
    myorder.price = price  ## 委托价
    myorder.volume = volume  ## 委托量
    myorder.cl_ord_id = ''

    myorder.position_effect = 1  ## 开平标志,1:开仓,2:平仓
    myorder.side = 2  ## 买卖方向,1:多方向,2:空方向
    myorder.order_type = 0  ## 订单类型
    myorder.order_src = 0  ## 订单来源

    if exchange == 'huobipro':  # 火币网接口
        if price == 0.0:
            mtype = 'buy-market'
        else:
            mtype = 'buy-limit'

        # 买入数字货币,用来偿还借贷
        myorder.sending_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime(time.time()))
        result = hb.send_margin_order(amount=volume,
                                      source='margin-api',
                                      symbol=sec_id,
                                      _type=mtype,
                                      price=price)

        if result['status'] == 'ok':
            myorder.ex_ord_id = result['data']

            # 归还借贷资产
            data_df = get_margin_orders()
            loan_order = data_df[(data_df['currency'] == 'btc')
                                 & (data_df['loan-amount'] > 0)].iloc[-1]

            loan_order_id = loan_order.id
            reapy_amount = loan_order['loan-amount'] + loan_order[
                'interest-amount']

            hb.repay_margin(loan_order_id, reapy_amount)

            time.sleep(2)  # 等待2 秒后查询订单
            # 查询订单信息
            order_info = hb.order_info(myorder.ex_ord_id)
            myorder.account_id = order_info['data']['account-id']
            myorder.status = order_info['data']['state']
            myorder.sending_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['created-at'] / 1000))
            myorder.filled_volume = float(
                order_info['data']['field-amount'])  ## 已成交量
            myorder.filled_amount = float(
                order_info['data']['field-cash-amount'])  ## 已成交额
            if (myorder.filled_volume > 0):
                myorder.filled_vwap = round(myorder.filled_amount /
                                            myorder.filled_volume, 4)  ## 已成交均价
            myorder.filled_fee = float(
                order_info['data']['field-fees'])  ## 手续费
            myorder.transact_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['finished-at'] /
                               1000))  ## 最新一次成交时间

            logger.info('%s 订单号 %s:%s 平空仓,成交量 = %f,成交均价 = %f,总成交额 = %f,手续费 = %f。' % \
                        (myorder.exchange, myorder.ex_ord_id, myorder.sec_id, myorder.filled_volume, myorder.filled_vwap, myorder.filled_amount, myorder.filled_fee))

        elif result['status'] == 'error':
            myorder.status = result['status']
            myorder.ord_rej_reason = result['err-code']  ## 订单拒绝原因
            myorder.ord_rej_reason_detail = result['err-msg']  ## 订单拒绝原因描述
            logger.warn('%s 订单:%s 开空仓 %f 失败,失败编码:%s,具体原因:%s。' % \
                        (myorder.exchange, myorder.sec_id, myorder.volume, myorder.ord_rej_reason, myorder.ord_rej_reason_detail))

        return myorder
Example #16
0
def open_short(exchange, sec_id, price, volume):
    '''
    开空仓,开空仓的流程是先利用本金加杠杆借入btc,然后把btc卖掉,直到平空仓时,再买回来还贷
    :param exchange: string	交易所代码,如火币网:huobipro,OKCoin: okcoin
    :param sec_id: string   证券代码,如btcusdt
    :param price: float     委托价,如果price=0,为市价单,否则为限价单
    :param volume: float	委托量
    :return: 委托下单生成的Order对象
    '''

    myorder = Order()
    myorder.exchange = exchange
    myorder.sec_id = sec_id
    myorder.price = price  ## 委托价
    myorder.volume = volume  ## 委托量
    myorder.cl_ord_id = ''

    myorder.position_effect = 1  ## 开平标志,1:开仓,2:平仓
    myorder.side = 2  ## 买卖方向,1:多方向,2:空方向
    myorder.order_src = 0  ## 订单来源

    if exchange == 'huobipro':  # 火币网接口
        if price == 0.0:
            mtype = 'sell-market'
        else:
            mtype = 'sell-limit'

        myorder.order_type = mtype  ## 订单类型

        # 先借入数字货币
        margin_res = hb.get_margin(symbol=sec_id,
                                   currency='btc',
                                   amount=volume)
        if margin_res['status'] == 'error':
            logger.warn(margin_res['err-code'] + ":" + margin_res['err-msg'])
            return None

        # 然后通过 Margin 账户交易
        myorder.sending_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime(time.time()))
        result = hb.send_margin_order(amount=volume,
                                      source='margin-api',
                                      symbol=sec_id,
                                      _type=mtype,
                                      price=price)
        if result['status'] == 'ok':
            myorder.ex_ord_id = result['data']

            time.sleep(2)  # 等待2 秒后查询订单
            # 查询订单信息
            order_info = hb.order_info(myorder.ex_ord_id)
            myorder.account_id = order_info['data']['account-id']
            myorder.status = order_info['data']['state']
            myorder.sending_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['created-at'] / 1000))
            myorder.filled_volume = float(
                order_info['data']['field-amount'])  ## 已成交量
            myorder.filled_amount = float(
                order_info['data']['field-cash-amount'])  ## 已成交额
            if (myorder.filled_volume > 0):
                myorder.filled_vwap = round(myorder.filled_amount /
                                            myorder.filled_volume, 4)  ## 已成交均价
            myorder.filled_fee = float(
                order_info['data']['field-fees'])  ## 手续费
            myorder.transact_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['finished-at'] /
                               1000))  ## 最新一次成交时间

            logger.info('%s 订单号 %s:%s 开空仓,成交量 = %f,成交均价 = %f,总成交额 = %f,手续费 = %f。' % \
                        (myorder.exchange, myorder.ex_ord_id, myorder.sec_id, myorder.filled_volume, myorder.filled_vwap, myorder.filled_amount, myorder.filled_fee))

        elif result['status'] == 'error':
            myorder.status = result['status']
            myorder.ord_rej_reason = result['err-code']  ## 订单拒绝原因
            myorder.ord_rej_reason_detail = result['err-msg']  ## 订单拒绝原因描述
            logger.warn('%s 订单号 %s:%s 开空仓 %f 失败,失败编码:%s,具体原因:%s。' % \
                        (myorder.exchange, myorder.ex_ord_id, myorder.sec_id, myorder.volume, myorder.ord_rej_reason, myorder.ord_rej_reason_detail))

        return myorder
Example #17
0
def close_long(exchange, sec_id, price, volume):
    '''
    异步平多仓,
    :param exchange: string	交易所代码,如火币网:huobipro,OKCoin: okcoin
    :param sec_id: string   证券代码,如
    :param price: float     委托价,如果price=0,为市价单,否则为限价单
    :param volume: float	委托量
    :return: 委托下单生成的Order对象
    '''

    myorder = Order()
    myorder.exchange = exchange
    myorder.sec_id = sec_id
    myorder.price = price  ## 委托价
    myorder.volume = volume  ## 委托量
    myorder.cl_ord_id = ''

    myorder.position_effect = 2  ## 开平标志,1:开仓,2:平仓
    myorder.side = 1  ## 买卖方向,1:多方向,2:空方向
    myorder.order_type = 0  ## 订单类型
    myorder.order_src = 0  ## 订单来源

    if exchange == 'huobipro':  # 火币网接口

        if price == 0.0:
            mtype = 'sell-market'
        else:
            mtype = 'sell-limit'

        myorder.sending_time = time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime(time.time()))
        result = hb.send_order(amount=volume,
                               source='api',
                               symbol=sec_id,
                               _type=mtype,
                               price=price)
        if result['status'] == 'ok':
            myorder.ex_ord_id = result['data']

            time.sleep(2)  # 等待3 秒后查询订单
            # 查询订单信息
            order_info = hb.order_info(myorder.ex_ord_id)
            myorder.status = order_info['data']['state']
            myorder.account_id = order_info['data']['account-id']
            myorder.sending_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['created-at'] / 1000))
            myorder.filled_volume = float(
                order_info['data']['field-amount'])  ## 已成交量
            myorder.filled_amount = float(
                order_info['data']['field-cash-amount'])  ## 已成交额
            if (myorder.filled_volume > 0):
                myorder.filled_vwap = round(myorder.filled_amount /
                                            myorder.filled_volume, 4)  ## 已成交均价
            myorder.filled_fee = float(
                order_info['data']['field-fees'])  ## 已成交额
            myorder.transact_time = time.strftime(
                "%Y-%m-%d %H:%M:%S",
                time.localtime(order_info['data']['finished-at'] /
                               1000))  ## 最新一次成交时间
            logger.info('%s 订单号 %s:%s 平多仓,成交量 = %f,成交均价 = %f,总成交额 = %f,手续费 = %f。' % \
                        (myorder.exchange, myorder.ex_ord_id, myorder.sec_id, myorder.filled_volume, myorder.filled_vwap, myorder.filled_amount, myorder.filled_fee))

        elif result['status'] == 'error':
            myorder.status = result['status']
            myorder.ord_rej_reason = result['err-code']  ## 订单拒绝原因
            myorder.ord_rej_reason_detail = result['err-msg']  ## 订单拒绝原因描述
            logger.warn('%s 订单号 %s:%s 平多仓 %f 失败,失败编码:%s,具体原因:%s。' % \
                        (myorder.exchange, myorder.ex_ord_id, myorder.sec_id, myorder.volume, myorder.ord_rej_reason, myorder.ord_rej_reason_detail))

        return myorder
Example #18
0
def get_orders_by_symbol(exchange,
                         sec_id,
                         start_time,
                         end_time,
                         states='filled',
                         types=None):
    '''

    :param exchange:
    :param sec_id:
    :param states: 查询的订单状态组合,使用','分割。pre-submitted 准备提交, submitted 已提交, partial-filled 部分成交, partial-canceled 部分成交撤销, filled 完全成交, canceled 已撤销
    :param types:  查询的订单类型组合,使用','分割。buy-market:市价买, sell-market:市价卖, buy-limit:限价买, sell-limit:限价卖
    :param start_time:
    :param end_time:
    :return:
    '''
    if states == 'all':
        states = 'pre-submitted,submitted,partial-filled,partial-canceled,filled,canceled'
    if types == 'all':
        types = 'buy-market,sell-market,buy-limit,sell-limit'

    orders = []
    if exchange == 'huobipro':

        start_date = time.strftime(
            '%Y-%m-%d', time.strptime(start_time, '%Y-%m-%d %H:%M:%S'))
        end_date = time.strftime('%Y-%m-%d',
                                 time.strptime(end_time, '%Y-%m-%d %H:%M:%S'))
        res = hb.orders_list(symbol=sec_id,
                             states=states,
                             types=types,
                             start_date=start_date,
                             end_date=end_date)
        if res['status'] == 'ok':
            data = res['data']

            for each in data:
                order = Order()
                order.exchange = exchange
                order.status = each['state']
                order.order_src = each['source']
                order.account_id = each['account-id']
                order.order_id = each['id']
                order.transact_time = each['finished-at']
                order.sending_time = each['created-at']
                order.order_type = each['type']
                order.sec_id = each['symbol']
                order.price = each['price']
                order.volume = each['amount']
                order.filled_volume = float(each['field-amount'])
                order.filled_amount = float(each['field-cash-amount'])
                order.filled_fee = float(each['field-fees'])
                if order.filled_volume > 0:
                    order.filled_vwap = round(order.filled_amount /
                                              order.filled_volume, 4)  ## 已成交均价

                orders = orders + [order]
        else:
            logger.warn(res['err-code'] + ':' + res['err-msg'])

    return orders