Example #1
0
 def __persistence_okex_spot_account(self, databank, access_key, secret_key,
                                     passphrase):
     spot_dict = {}
     okex_spot = _okspot(access_key, secret_key, passphrase)
     spot_accounts_info = okex_spot.get_account_info()
     for item in spot_accounts_info:
         if float(item['balance']) > 0:
             if databank == "mysql":
                 storage.mysql_save_okex_spot_accounts(
                     "okex账户", "现货", item['currency'], item['balance'],
                     item['hold'], item['available'])
             elif databank == "mongodb":
                 self.spot = True
                 spot_dict[item['currency']] = {
                     "余额": item['balance'],
                     "冻结": item['hold'],
                     "可用": item['hold']
                 }
             else:
                 raise DataBankError
     if self.spot == True and databank == "mongodb":
         storage.mongodb_save(database="okex账户",
                              collection="现货",
                              data={
                                  "data": {
                                      "时间": get_localtime(),
                                      "账户": "现货"
                                  },
                                  "accounts": spot_dict
                              })
Example #2
0
 def save_strategy_position(self, strategy_direction, strategy_amount):
     """下单后将仓位信息保存至数据库."""
     if self.__databank == "mysql":
         storage.mysql_save_strategy_position(self.__database, self.__datasheet, strategy_direction,
                                        strategy_amount)
     elif self.__databank == "mongodb":
         storage.mongodb_save(data={"时间": get_localtime(), "strategy_direction": strategy_direction, "strategy_amount": strategy_amount}, database=self.__database, collection=self.__datasheet)
     else:
         raise DataBankError
Example #3
0
async def handle_ws_data(*args, **kwargs):
    """ callback function
    Args:
        args: values
        kwargs: key-values.
    """
    try:
        dict = {"data": ("callback param", *args)}
        # print(dict['data'][1])
        if "topic" in dict['data'][1]:
            topic = dict['data'][1]['topic']
            if "position" in topic:
                if 'data' in dict['data'][1]:
                    data = dict['data'][1]['data'][0]
                    if 'contract_code' in data:
                        contract_code = data['contract_code']
                        amount = data['volume']
                        price = data['cost_hold']
                        direction = data['direction']
                        last = data['last_price']
                        leverage = data['lever_rate']
                        info = "【交易提醒】HUOBI交割合约持仓更新!合约ID:{} 持仓方向:{} 持仓量:{} 持仓均价:{} 最新成交价:{} 杠杆倍数:{}".format(
                            contract_code, direction, amount, price, last,
                            leverage)
                        if dict['data'][1]['event'] == 'order.match' or dict[
                                'data'][1]['event'] == 'settlement' or dict[
                                    'data'][1]['event'] == 'order.liquidation':
                            push(info)
        else:
            if config.mongodb_console == "true":
                print("callback param", *args, **kwargs)
            dict = {"data": ("callback param", *args)}
            storage.mongodb_save(dict, config.mongodb_database,
                                 config.mongodb_collection)
    except:
        pass
Example #4
0
async def subscribe_without_login(url, channels):
    l = []
    while True:
        try:
            async with websockets.connect(url) as ws:
                sub_param = {"op": "subscribe", "args": channels}
                sub_str = json.dumps(sub_param)
                await ws.send(sub_str)

                while True:
                    try:
                        res_b = await asyncio.wait_for(ws.recv(), timeout=25)
                    except (asyncio.TimeoutError,
                            websockets.exceptions.ConnectionClosed) as e:
                        try:
                            await ws.send('ping')
                            res_b = await ws.recv()
                            timestamp = get_timestamp()
                            res = inflate(res_b).decode('utf-8')
                            print(timestamp + res)
                            continue
                        except Exception as e:
                            timestamp = get_timestamp()
                            print(timestamp + "连接关闭,正在重连……")
                            print(e)
                            break

                    timestamp = get_timestamp()
                    res = inflate(res_b).decode('utf-8')
                    if config.mongodb_console == "true":
                        print(timestamp + res)
                    data = {'data': res}
                    storage.mongodb_save(data, config.mongodb_database,
                                         config.mongodb_collection)

                    res = eval(res)
                    if 'event' in res:
                        continue
                    for i in res:
                        if 'depth' in res[i] and 'depth5' not in res[i]:
                            # 订阅频道是深度频道
                            if res['action'] == 'partial':
                                for m in l:
                                    if res['data'][0]['instrument_id'] == m[
                                            'instrument_id']:
                                        l.remove(m)
                                # 获取首次全量深度数据
                                bids_p, asks_p, instrument_id = partial(
                                    res, timestamp)
                                d = {}
                                d['instrument_id'] = instrument_id
                                d['bids_p'] = bids_p
                                d['asks_p'] = asks_p
                                l.append(d)

                                # 校验checksum
                                checksum = res['data'][0]['checksum']
                                print(timestamp + '推送数据的checksum为:' +
                                      str(checksum))
                                check_num = check(bids_p, asks_p)
                                print(timestamp + '校验后的checksum为:' +
                                      str(check_num))
                                if check_num == checksum:
                                    print("校验结果为:True")
                                else:
                                    print("校验结果为:False,正在重新订阅……")

                                    # 取消订阅
                                    await unsubscribe_without_login(
                                        url, channels, timestamp)
                                    # 发送订阅
                                    async with websockets.connect(url) as ws:
                                        sub_param = {
                                            "op": "subscribe",
                                            "args": channels
                                        }
                                        sub_str = json.dumps(sub_param)
                                        await ws.send(sub_str)
                                        timestamp = get_timestamp()
                                        print(timestamp + f"send: {sub_str}")

                            elif res['action'] == 'update':
                                for j in l:
                                    if res['data'][0]['instrument_id'] == j[
                                            'instrument_id']:
                                        # 获取全量数据
                                        bids_p = j['bids_p']
                                        asks_p = j['asks_p']
                                        # 获取合并后数据
                                        bids_p = update_bids(
                                            res, bids_p, timestamp)
                                        asks_p = update_asks(
                                            res, asks_p, timestamp)

                                        # 校验checksum
                                        checksum = res['data'][0]['checksum']
                                        print(timestamp + '推送数据的checksum为:' +
                                              str(checksum))
                                        check_num = check(bids_p, asks_p)
                                        print(timestamp + '校验后的checksum为:' +
                                              str(check_num))
                                        if check_num == checksum:
                                            print("校验结果为:True")
                                        else:
                                            print("校验结果为:False,正在重新订阅……")

                                            # 取消订阅
                                            await unsubscribe_without_login(
                                                url, channels, timestamp)
                                            # 发送订阅
                                            async with websockets.connect(
                                                url) as ws:
                                                sub_param = {
                                                    "op": "subscribe",
                                                    "args": channels
                                                }
                                                sub_str = json.dumps(sub_param)
                                                await ws.send(sub_str)
                                                timestamp = get_timestamp()
                                                print(timestamp +
                                                      f"send: {sub_str}")
        except Exception as e:
            timestamp = get_timestamp()
            print(timestamp + "连接断开,正在重连……")
            print(e)
            continue
Example #5
0
    def __persistence_okex_futures_account(self, databank, access_key,
                                           secret_key, passphrase):
        futures_usdt_crossed_dict = {}
        futures_usd_crossed_dict = {}
        futures_usdt_fixed_dict = {}
        futures_usd_fixed_dict = {}
        okex_futures = _okfutures(access_key, secret_key, passphrase)
        futures_accounts_info = okex_futures.get_accounts()["info"]
        for key, value in futures_accounts_info.items():
            if "usdt" in key and value[
                    "margin_mode"] == "crossed":  # USDT本位的全仓模式
                symbol = value["underlying"]
                currency = value["currency"]
                margin_mode = value["margin_mode"]
                equity = value["equity"]
                total_avail_balance = value["total_avail_balance"]
                margin = value["margin"]
                margin_frozen = value["margin_frozen"]
                margin_for_unfilled = value["margin_for_unfilled"]
                realized_pnl = value["realized_pnl"]
                unrealized_pnl = value["unrealized_pnl"]
                margin_ratio = value["margin_ratio"]
                maint_margin_ratio = value["maint_margin_ratio"]
                liqui_mode = value["liqui_mode"]
                can_withdraw = value["can_withdraw"]
                liqui_fee_rate = value["liqui_fee_rate"]
                if databank == "mysql":
                    storage.mysql_save_okex_crossedfutures_accounts(
                        "okex账户", "交割合约usdt全仓模式", symbol, currency,
                        margin_mode, equity, total_avail_balance, margin,
                        margin_frozen, margin_for_unfilled, realized_pnl,
                        unrealized_pnl, margin_ratio, maint_margin_ratio,
                        liqui_mode, can_withdraw, liqui_fee_rate)
                elif databank == "mongodb":
                    self.futures_usdt_crossed = True
                    futures_usdt_crossed_dict[symbol] = {
                        "余额币种": currency,
                        "账户类型": margin_mode,
                        "账户权益": equity,
                        "账户余额": total_avail_balance,
                        "保证金": margin,
                        "持仓已用保证金": margin_frozen,
                        "挂单冻结保证金": margin_for_unfilled,
                        "已实现盈亏": realized_pnl,
                        "未实现盈亏": unrealized_pnl,
                        "保证金率": margin_ratio,
                        "维持保证金率": maint_margin_ratio,
                        "强平模式": liqui_mode,
                        "可划转数量": can_withdraw,
                        "强平手续费": liqui_fee_rate
                    }
                else:
                    raise DataBankError

            if "usdt" not in key and value[
                    "margin_mode"] == "crossed":  # 币本位的全仓模式
                symbol = value["underlying"]
                currency = value["currency"]
                margin_mode = value["margin_mode"]
                equity = value["equity"]
                total_avail_balance = value["total_avail_balance"]
                margin = value["margin"]
                margin_frozen = value["margin_frozen"]
                margin_for_unfilled = value["margin_for_unfilled"]
                realized_pnl = value["realized_pnl"]
                unrealized_pnl = value["unrealized_pnl"]
                margin_ratio = value["margin_ratio"]
                maint_margin_ratio = value["maint_margin_ratio"]
                liqui_mode = value["liqui_mode"]
                can_withdraw = value["can_withdraw"]
                liqui_fee_rate = value["liqui_fee_rate"]
                if databank == "mysql":
                    storage.mysql_save_okex_crossedfutures_accounts(
                        "okex账户", "交割合约usd全仓模式", symbol, currency, margin_mode,
                        equity, total_avail_balance, margin, margin_frozen,
                        margin_for_unfilled, realized_pnl, unrealized_pnl,
                        margin_ratio, maint_margin_ratio, liqui_mode,
                        can_withdraw, liqui_fee_rate)
                elif databank == "mongodb":
                    self.futures_usd_crossed = True
                    futures_usd_crossed_dict[symbol] = {
                        "余额币种": currency,
                        "账户类型": margin_mode,
                        "账户权益": equity,
                        "账户余额": total_avail_balance,
                        "保证金": margin,
                        "持仓已用保证金": margin_frozen,
                        "挂单冻结保证金": margin_for_unfilled,
                        "已实现盈亏": realized_pnl,
                        "未实现盈亏": unrealized_pnl,
                        "保证金率": margin_ratio,
                        "维持保证金率": maint_margin_ratio,
                        "强平模式": liqui_mode,
                        "可划转数量": can_withdraw,
                        "强平手续费": liqui_fee_rate
                    }
                else:
                    raise DataBankError

            if "usdt" in key and value["margin_mode"] == "fixed" and len(
                    value["contracts"]) > 0:  # USDT本位的逐仓模式
                v = value["contracts"][0]
                symbol = v["instrument_id"][0:8]
                fixed_balance = v["fixed_balance"]
                available_qty = v["available_qty"]
                margin_frozen = v["margin_frozen"]
                margin_for_unfilled = v["margin_for_unfilled"]
                realized_pnl = v["realized_pnl"]
                unrealized_pnl = v["unrealized_pnl"]
                total_avail_balance = value["total_avail_balance"]
                currency = value["currency"]
                margin_mode = value["margin_mode"]
                equity = value["equity"]
                auto_margin = value["auto_margin"]
                liqui_mode = value["liqui_mode"]
                can_withdraw = value["can_withdraw"]
                if databank == "mysql":
                    storage.mysql_save_okex_fixedfutures_accounts(
                        "okex账户", "交割合约usdt逐仓模式", symbol, currency,
                        margin_mode, equity, fixed_balance, available_qty,
                        margin_frozen, margin_for_unfilled, realized_pnl,
                        unrealized_pnl, total_avail_balance, auto_margin,
                        liqui_mode, can_withdraw)
                elif databank == "mongodb":
                    self.futures_usdt_fixed = True
                    futures_usdt_fixed_dict[symbol] = {
                        "余额币种": currency,
                        "账户类型": margin_mode,
                        "账户动态权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "逐仓可用余额": available_qty,
                        "持仓已用保证金": margin_frozen,
                        "挂单冻结保证金": margin_for_unfilled,
                        "已实现盈亏": realized_pnl,
                        "未实现盈亏": unrealized_pnl,
                        "账户静态权益": total_avail_balance,
                        "是否自动追加保证金": auto_margin,
                        "强平模式": liqui_mode,
                        "可划转数量": can_withdraw
                    }
                else:
                    raise DataBankError

            if "usdt" not in key and value["margin_mode"] == "fixed" and len(
                    value["contracts"]) > 0:  # 币本位的逐仓模式
                v = value["contracts"][0]
                symbol = v["instrument_id"][0:7]
                fixed_balance = v["fixed_balance"]
                available_qty = v["available_qty"]
                margin_frozen = v["margin_frozen"]
                margin_for_unfilled = v["margin_for_unfilled"]
                realized_pnl = v["realized_pnl"]
                unrealized_pnl = v["unrealized_pnl"]
                total_avail_balance = value["total_avail_balance"]
                currency = value["currency"]
                margin_mode = value["margin_mode"]
                equity = value["equity"]
                auto_margin = value["auto_margin"]
                liqui_mode = value["liqui_mode"]
                can_withdraw = value["can_withdraw"]
                if databank == "mysql":
                    storage.mysql_save_okex_fixedfutures_accounts(
                        "okex账户", "交割合约usd逐仓模式", symbol, currency, margin_mode,
                        equity, fixed_balance, available_qty, margin_frozen,
                        margin_for_unfilled, realized_pnl, unrealized_pnl,
                        total_avail_balance, auto_margin, liqui_mode,
                        can_withdraw)
                elif databank == "mongodb":
                    self.futures_usd_fixed = True
                    futures_usd_fixed_dict[symbol] = {
                        "余额币种": currency,
                        "账户类型": margin_mode,
                        "账户动态权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "逐仓可用余额": available_qty,
                        "持仓已用保证金": margin_frozen,
                        "挂单冻结保证金": margin_for_unfilled,
                        "已实现盈亏": realized_pnl,
                        "未实现盈亏": unrealized_pnl,
                        "账户静态权益": total_avail_balance,
                        "是否自动追加保证金": auto_margin,
                        "强平模式": liqui_mode,
                        "可划转数量": can_withdraw
                    }
                else:
                    raise DataBankError
        if self.futures_usdt_crossed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="交割合约usdt全仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "交割合约usdt全仓模式"
                                     },
                                     "accounts": futures_usdt_crossed_dict
                                 })
        if self.futures_usd_crossed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="交割合约usd全仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "交割合约usd全仓模式"
                                     },
                                     "accounts": futures_usd_crossed_dict
                                 })
        if self.futures_usd_fixed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="交割合约usd逐仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "交割合约usd逐仓模式"
                                     },
                                     "accounts": futures_usd_fixed_dict
                                 })
        if self.futures_usdt_fixed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="交割合约usdt逐仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "交割合约usdt逐仓模式"
                                     },
                                     "accounts": futures_usdt_fixed_dict
                                 })
Example #6
0
    def __persistence_okex_swap_account(self, databank, access_key, secret_key,
                                        passphrase):
        swap_usdt_crossed_dict = {}
        swap_usdt_fixed_dict = {}
        swap_usd_crossed_dict = {}
        swap_usd_fixed_dict = {}
        okex_swap = _okswap(access_key, secret_key, passphrase)
        swap_accounts_info = okex_swap.get_accounts()["info"]
        for item in swap_accounts_info:
            currency = item["currency"]
            equity = item["equity"]
            fixed_balance = item["fixed_balance"]
            maint_margin_ratio = item["maint_margin_ratio"]
            margin = item["margin"]
            margin_frozen = item["margin_frozen"]
            margin_mode = item["margin_mode"]
            margin_ratio = item["margin_ratio"]
            max_withdraw = item["max_withdraw"]
            realized_pnl = item["realized_pnl"]
            timestamp = item["timestamp"]
            total_avail_balance = item["total_avail_balance"]
            symbol = item["underlying"]
            unrealized_pnl = item["unrealized_pnl"]

            if currency == "USDT" and margin_mode == "crossed" and float(
                    equity) > 0:  # 永续合约USDT全仓模式
                if databank == "mysql":
                    storage.mysql_save_okex_swap_accounts(
                        "okex账户", "永续合约usdt全仓模式", timestamp, symbol, currency,
                        margin_mode, equity, total_avail_balance,
                        fixed_balance, margin, margin_frozen, realized_pnl,
                        unrealized_pnl, margin_ratio, maint_margin_ratio,
                        max_withdraw)
                elif databank == "mongodb":
                    self.swap_usdt_crossed = True
                    swap_usdt_crossed_dict[symbol] = {
                        "账户余额币种": currency,
                        "账户权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "维持保证金率": maint_margin_ratio,
                        "已用保证金": margin,
                        "开仓冻结保证金": margin_frozen,
                        "仓位模式": margin_mode,
                        "保证金率": margin_ratio,
                        "可划转数量": max_withdraw,
                        "已实现盈亏": realized_pnl,
                        "时间": timestamp,
                        "账户余额": total_avail_balance,
                        "未实现盈亏": unrealized_pnl
                    }
                else:
                    raise DataBankError
            if currency != "USDT" and margin_mode == "crossed" and float(
                    equity) > 0:  # 永续合约币本位全仓模式
                if databank == "mysql":
                    storage.mysql_save_okex_swap_accounts(
                        "okex账户", "永续合约usd全仓模式", timestamp, symbol, currency,
                        margin_mode, equity, total_avail_balance,
                        fixed_balance, margin, margin_frozen, realized_pnl,
                        unrealized_pnl, margin_ratio, maint_margin_ratio,
                        max_withdraw)
                elif databank == "mongodb":
                    self.swap_usd_crossed = True
                    swap_usd_crossed_dict[symbol] = {
                        "账户余额币种": currency,
                        "账户权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "维持保证金率": maint_margin_ratio,
                        "已用保证金": margin,
                        "开仓冻结保证金": margin_frozen,
                        "仓位模式": margin_mode,
                        "保证金率": margin_ratio,
                        "可划转数量": max_withdraw,
                        "已实现盈亏": realized_pnl,
                        "时间": timestamp,
                        "账户余额": total_avail_balance,
                        "未实现盈亏": unrealized_pnl
                    }
                else:
                    raise DataBankError
            if currency == "USDT" and margin_mode == "fixed" and float(
                    equity) > 0:  # 永续合约USDT逐仓模式
                if databank == "mysql":
                    storage.mysql_save_okex_swap_accounts(
                        "okex账户", "永续合约usdt逐仓模式", timestamp, symbol, currency,
                        margin_mode, equity, total_avail_balance,
                        fixed_balance, margin, margin_frozen, realized_pnl,
                        unrealized_pnl, margin_ratio, maint_margin_ratio,
                        max_withdraw)
                elif databank == "mongodb":
                    self.swap_usdt_fixed = True
                    swap_usdt_fixed_dict[symbol] = {
                        "账户余额币种": currency,
                        "账户权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "维持保证金率": maint_margin_ratio,
                        "已用保证金": margin,
                        "开仓冻结保证金": margin_frozen,
                        "仓位模式": margin_mode,
                        "保证金率": margin_ratio,
                        "可划转数量": max_withdraw,
                        "已实现盈亏": realized_pnl,
                        "时间": timestamp,
                        "账户余额": total_avail_balance,
                        "未实现盈亏": unrealized_pnl
                    }
                else:
                    raise DataBankError
            if currency != "USDT" and margin_mode == "fixed" and float(
                    equity) > 0:  # 永续合约USDT本位全仓模式
                if databank == "mysql":
                    storage.mysql_save_okex_swap_accounts(
                        "okex账户", "永续合约usd逐仓模式", timestamp, symbol, currency,
                        margin_mode, equity, total_avail_balance,
                        fixed_balance, margin, margin_frozen, realized_pnl,
                        unrealized_pnl, margin_ratio, maint_margin_ratio,
                        max_withdraw)
                elif databank == "mongodb":
                    self.swap_usd_fixed = True
                    swap_usd_fixed_dict[symbol] = {
                        "账户余额币种": currency,
                        "账户权益": equity,
                        "逐仓账户余额": fixed_balance,
                        "维持保证金率": maint_margin_ratio,
                        "已用保证金": margin,
                        "开仓冻结保证金": margin_frozen,
                        "仓位模式": margin_mode,
                        "保证金率": margin_ratio,
                        "可划转数量": max_withdraw,
                        "已实现盈亏": realized_pnl,
                        "时间": timestamp,
                        "账户余额": total_avail_balance,
                        "未实现盈亏": unrealized_pnl
                    }
                else:
                    raise DataBankError
        if self.swap_usdt_crossed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="永续合约usdt全仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "永续合约usdt全仓模式"
                                     },
                                     "accounts": swap_usdt_crossed_dict
                                 })
        if self.swap_usd_crossed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="永续合约usd全仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "永续合约usd全仓模式"
                                     },
                                     "accounts": swap_usd_crossed_dict
                                 })
        if self.swap_usdt_fixed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="永续合约usdt逐仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "永续合约usdt逐仓模式"
                                     },
                                     "accounts": swap_usdt_fixed_dict
                                 })
        if self.swap_usd_fixed == True and databank == "mongodb":
            storage.mongodb_save(database="okex账户",
                                 collection="永续合约usd逐仓模式",
                                 data={
                                     "data": {
                                         "时间": get_localtime(),
                                         "账户": "永续合约usd逐仓模式"
                                     },
                                     "accounts": swap_usd_fixed_dict
                                 })