Exemplo n.º 1
0
 def kline_storage(self, database, data_sheet, platform, instrument_id,
                   time_frame):
     """
     实时获取上一根k线存储至数据库中。
     :param database: 数据库名称
     :param data_sheet: 数据表名称
     :param instrument_id: 交易对或合约id
     :param time_frame: k线周期,如'1m', '1d',字符串格式
     :return:
     """
     indicators = INDICATORS(platform, instrument_id, time_frame)
     if indicators.BarUpdate() == True:
         last_kline = platform.get_kline(time_frame)[1]
         if last_kline != self.__old_kline:  # 若获取得k线不同于已保存的上一个k线
             timestamp = last_kline[0]
             open = last_kline[1]
             high = last_kline[2]
             low = last_kline[3]
             close = last_kline[4]
             volume = last_kline[5]
             self.__six_save_kline_func(database, data_sheet, timestamp,
                                        open, high, low, close, volume)
             print("时间:{} 实时k线数据已保存至MySQL数据库中!".format(
                 time.get_localtime()))
             self.__old_kline = last_kline  # 将刚保存的k线设为旧k线
         else:
             return
Exemplo n.º 2
0
def __dingtalk(text):
    """
    推送钉钉消息。
    :param data: 要推送的数据内容,字符串格式
    :return:
    """
    json_text = {
        "msgtype": "text",
        "at": {
            "atMobiles": [""],
            "isAtAll": True
        },
        "text": {
            "content": text
        }
    }

    headers = {'Content-Type': 'application/json;charset=utf-8'}
    api_url = config.ding_talk_api
    dingtalk_result = requests.post(api_url,
                                    json.dumps(json_text),
                                    headers=headers).content  # 发送钉钉消息并返回发送结果
    storage.text_save("时间:" + str(get_localtime()) + "  发送状态:" +
                      str(dingtalk_result) + "发送内容:" + str(text),
                      './dingtalk.txt')  # 将发送时间、结果和具体发送内容保存至当前目录下text文件中
Exemplo n.º 3
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
                              })
Exemplo n.º 4
0
 def binance_kline_save(self, database, data_sheet, platform, instrument_id, time_frame):
     """存储币安交易所历史k线"""
     result = platform.get_kline(time_frame)
     result.reverse()
     for data in result:
         self.__binance_save_kline_func(database, data_sheet, data[0], data[1], data[2], data[3], data[4], data[5])
     print("{} {} {} 获取的币安交易所的历史k线数据已存储至mysql数据库!".format(time.get_localtime(), instrument_id, time_frame))
Exemplo n.º 5
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
Exemplo n.º 6
0
 def __init__(self, databank, database, data_sheet, exchange, instrument_id, time_frame):
     print("{} {} 持仓同步功能已启动!".format(get_localtime(), instrument_id))
     self.__databank = databank
     self.__database = database
     self.__datasheet = data_sheet
     self.__exchange = exchange
     self.__instrument_id = instrument_id
     self.__time_frame = time_frame
     self.__position = POSITION(self.__exchange, self.__instrument_id, self.__time_frame)
     self.__market = MARKET(self.__exchange, self.__instrument_id, self.__time_frame)
     self.__overprice_range = config.overprice_range
Exemplo n.º 7
0
 def mysql_save_okex_spot_accounts(self,
                                   database,
                                   data_sheet,
                                   currency,
                                   balance,
                                   frozen,
                                   available,
                                   timestamp=None):
     """存储okex现货账户信息至mysql数据库"""
     timestamp = timestamp if timestamp is not None else time.get_localtime(
     )  # 默认是自动填充本地时间,也可以传入*****来做数据分割
     # 检查数据库是否存在,如不存在则创建
     user = config.mysql_user_name if config.mysql_authorization == "enabled" else 'root'
     password = config.mysql_password if config.mysql_authorization == "enabled" else 'root'
     conn1 = mysql.connector.connect(user=user, password=password)
     cursor1 = conn1.cursor()
     cursor1.execute("SHOW DATABASES")
     list1 = []
     for item in cursor1:
         for x in item:
             list1.append(x)
     if database in list1:
         pass
     else:
         cursor1.execute("CREATE DATABASE {}".format(database))
     conn1.commit()
     cursor1.close()
     conn1.close()
     # 检查数据表是否存在,如不存在则创建
     conn2 = mysql.connector.connect(user=user,
                                     password=password,
                                     database=database)
     cursor2 = conn2.cursor()
     cursor2.execute("SHOW TABLES")
     list2 = []
     for item in cursor2:
         for x in item:
             list2.append(x)
     if data_sheet in list2:
         pass
     else:  # 如果数据表不存在就创建
         cursor2.execute(
             "CREATE TABLE {} (时间 TEXT, 币种 TEXT, 余额 TEXT, 冻结 TEXT, 可用 TEXT)"
             .format(data_sheet))
     # 插入新数据
     cursor2.execute(
         'insert into {} (时间, 币种, 余额, 冻结, 可用) values (%s, %s, %s, %s, %s)'.
         format(data_sheet),
         [timestamp, currency, balance, frozen, available])
     conn2.commit()
     cursor2.close()
     conn2.close()
Exemplo n.º 8
0
 def binance_kline_storage(self, database, data_sheet, platform, instrument_id, time_frame):
     """存储实时的币安交易所k线数据"""
     indicators = INDICATORS(platform, instrument_id, time_frame)
     if indicators.BarUpdate() == True:
         last_kline = platform.get_kline(time_frame)[1]
         if last_kline != self.__old_kline:    # 若获取得k线不同于已保存的上一个k线
             timestamp = last_kline[0]
             open = last_kline[1]
             high = last_kline[2]
             low = last_kline[3]
             close = last_kline[4]
             volume = last_kline[5]
             self.__binance_save_kline_func(database, data_sheet, timestamp, open, high, low, close, volume)
             print("{} {} {} 币安交易所实时k线数据已保存至MySQL数据库中!".format(time.get_localtime(), instrument_id, time_frame))
             self.__old_kline = last_kline  # 将刚保存的k线设为旧k线
         else:
             return
Exemplo n.º 9
0
 def mysql_save_okex_fixedfutures_accounts(self, database, data_sheet, 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, timestamp=None):
     """存储okex逐仓模式交割合约账户信息至mysql数据库"""
     timestamp = timestamp if timestamp is not None else time.get_localtime()   # 默认是自动填充本地时间,也可以传入*****来做数据分割
     # 检查数据库是否存在,如不存在则创建
     user = config.mysql_user_name if config.mysql_authorization == "enabled" else 'root'
     password = config.mysql_password if config.mysql_authorization == "enabled" else 'root'
     conn1 = mysql.connector.connect(user=user, password=password)
     cursor1 = conn1.cursor()
     cursor1.execute("SHOW DATABASES")
     list1 = []
     for item in cursor1:
         for x in item:
             list1.append(x)
     if database in list1:
         pass
     else:
         cursor1.execute("CREATE DATABASE {}".format(database))
     conn1.commit()
     cursor1.close()
     conn1.close()
     # 检查数据表是否存在,如不存在则创建
     conn2 = mysql.connector.connect(user=user, password=password, database=database)
     cursor2 = conn2.cursor()
     cursor2.execute("SHOW TABLES")
     list2 = []
     for item in cursor2:
         for x in item:
             list2.append(x)
     if data_sheet in list2:
         pass
     else:  # 如果数据表不存在就创建
         cursor2.execute("CREATE TABLE {} (时间 TEXT, 币对 TEXT, 余额币种 TEXT, 账户类型 TEXT, 账户权益 TEXT, 逐仓账户余额 TEXT, 逐仓可用余额 TEXT, 持仓已用保证金 TEXT, 挂单冻结保证金 TEXT, 已实现盈亏 TEXT, 未实现盈亏 TEXT, 账户静态权益 TEXT, 是否自动追加保证金 TEXT, 强平模式 TEXT, 可划转数量 TEXT)".format(data_sheet))
     # 插入新数据
     cursor2.execute(
         'insert into {} (时间, 币对, 余额币种, 账户类型, 账户权益, 逐仓账户余额, 逐仓可用余额, 持仓已用保证金, 挂单冻结保证金, 已实现盈亏, 未实现盈亏, 账户静态权益, 是否自动追加保证金, 强平模式, 可划转数量) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'.format(
             data_sheet),
         [timestamp, 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])
     conn2.commit()
     cursor2.close()
     conn2.close()
Exemplo n.º 10
0
 def mysql_save_strategy_position(self, database, data_sheet, direction,
                                  amount):
     """存储持仓方向与持仓数量信息至mysql数据库"""
     # 检查数据库是否存在,如不存在则创建
     user = config.mysql_user_name if config.mysql_authorization == "enabled" else 'root'
     password = config.mysql_password if config.mysql_authorization == "enabled" else 'root'
     conn1 = mysql.connector.connect(user=user, password=password)
     cursor1 = conn1.cursor()
     cursor1.execute("SHOW DATABASES")
     list1 = []
     for item in cursor1:
         for x in item:
             list1.append(x)
     if database in list1:
         pass
     else:
         cursor1.execute("CREATE DATABASE {}".format(database))
     conn1.commit()
     cursor1.close()
     conn1.close()
     # 检查数据表是否存在,如不存在则创建
     conn2 = mysql.connector.connect(user=user,
                                     password=password,
                                     database=database)
     cursor2 = conn2.cursor()
     cursor2.execute("SHOW TABLES")
     list2 = []
     for item in cursor2:
         for x in item:
             list2.append(x)
     if data_sheet in list2:
         pass
     else:
         cursor2.execute(
             "CREATE TABLE {} (timestamp TEXT, direction TEXT, amount FLOAT)"
             .format(data_sheet))
     # 插入数据
     cursor2.execute(
         'insert into {} (timestamp, direction, amount) values (%s, %s, %s)'
         .format(data_sheet), [time.get_localtime(), direction, amount])
     conn2.commit()
     cursor2.close()
     conn2.close()
Exemplo n.º 11
0
async def subscribe(url, api_key, passphrase, secret_key, channels):
    while True:
        try:
            async with websockets.connect(url) as ws:
                # login
                timestamp = str(server_timestamp())
                login_str = login_params(timestamp, api_key, passphrase,
                                         secret_key)
                await ws.send(login_str)
                # time = get_timestamp()
                # print(time + f"send: {login_str}")
                res_b = await ws.recv()
                res = inflate(res_b).decode('utf-8')
                time = get_timestamp()
                # print(time + res)

                # subscribe
                sub_param = {"op": "subscribe", "args": channels}
                sub_str = json.dumps(sub_param)
                await ws.send(sub_str)
                time = get_timestamp()
                # print(time + f"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()
                            time = get_timestamp()
                            res = inflate(res_b).decode('utf-8')
                            # print(time + res)
                            continue
                        except Exception as e:
                            time = get_timestamp()
                            print(time + "连接关闭,正在重连……")
                            print(e)
                            break

                    time = get_timestamp()
                    res = inflate(res_b).decode('utf-8')
                    # print(time + res)
                    # 持仓更新
                    length = len(res)
                    result = eval(res)
                    if length > 99:
                        if channels[0][0:16] == "futures/position":
                            data = result['data'][0]
                            long_qty = data["long_qty"]
                            short_qty = data["short_qty"]
                            leverage = data["leverage"]
                            long_avg_cost = data["long_avg_cost"]
                            short_avg_cost = data["short_avg_cost"]
                            last = data["last"]
                            instrument_id = data['instrument_id']
                            info = "【交易提醒】OKEX交割合约持仓更新!合约ID:{} 多头仓位:{} 持多均价:{} 空头仓位:{} 持空均价:{} 最新成交价:{} 杠杆倍数:{}".format(
                                instrument_id, long_qty, long_avg_cost,
                                short_qty, short_avg_cost, last, leverage)
                            if get_localtime()[11:16] != "16:00":
                                push(info)
                        if channels[0][0:13] == "swap/position":
                            data = result['data'][0]['holding'][1]
                            data2 = result['data'][0]['holding'][0]
                            direction2 = data2['side']
                            amount2 = data2['position']
                            price2 = data2['avg_cost']
                            instrument_id = result['data'][0]['instrument_id']
                            direction = data['side']
                            amount = data['position']
                            price = data['avg_cost']
                            last = data['last']
                            leverage = data['leverage']
                            info = "【交易提醒】OKEX永续合约持仓更新!合约ID:{} 多头方向:{} 持多均价:{} 持多数量:{} 空头方向:{} 持空均价:{} 持空数量:{} 最新成交价:{} 杠杆倍数:{}".format(
                                instrument_id, direction2, price2, amount2,
                                direction, price, amount, last, leverage)
                            if get_localtime()[11:16] != "16:00":
                                push(info)
                        if channels[0][0:12] == "spot/account":
                            data = result["data"][0]
                            balance = data["balance"]
                            available = data["available"]
                            currency = data["currency"]
                            hold = data["hold"]
                            info = "【交易提醒】OKEX币币账户更新!币种:{} 余额:{} 冻结:{} 可用:{} ".format(
                                currency, balance, hold, available)
                            if get_localtime()[11:16] != "16:00":
                                push(info)
                        if channels[0][0:19] == "spot/margin_account":
                            symbol = result['data'][0]['instrument_id']
                            liquidation_price = result['data'][0][
                                'liquidation_price']
                            if len(symbol) == 8:
                                dollar_name = 'currency:{}'.format(symbol[4:8])
                                coin_name = 'currency:{}'.format(symbol[0:3])
                            elif len(symbol) == 9:
                                dollar_name = 'currency:{}'.format(symbol[5:9])
                                coin_name = 'currency:{}'.format(symbol[0:4])
                            else:
                                dollar_name = 'currency:{}'.format(
                                    symbol[6:10])
                                coin_name = 'currency:{}'.format(symbol[0:5])
                            dollar_info = result['data'][0][dollar_name]
                            coin_info = result['data'][0][coin_name]
                            dollar_balance = dollar_info['balance']
                            coin_balance = coin_info['balance']
                            dollar_available = dollar_info['available']
                            coin_available = coin_info['available']
                            dollar_hold = dollar_info['hold']
                            coin_hold = coin_info['hold']
                            dollar_borrowed = dollar_info['borrowed']
                            coin_borrowed = coin_info['borrowed']
                            info = "【交易提醒】OKEX币币杠杆账户更新!交易对:{} 强平价:{} 计价币:【{} 余额:{} 可用:{} 冻结:{} 已借未还:{}】 交易币:【{} 余额:{} 可用:{} 冻结:{} 已借未还:{}】".format(
                                symbol, liquidation_price, dollar_name,
                                dollar_balance, dollar_available, dollar_hold,
                                dollar_borrowed, coin_name, coin_balance,
                                coin_available, coin_hold, coin_borrowed)
                            if get_localtime()[11:16] != "16:00":
                                push(info)
                        if channels[0][0:15] == "option/position":
                            data = result['data'][0]
                            instrument_id = data['instrument_id']
                            position = data['position']
                            avg_cost = data['avg_cost']
                            option_value = data['option_value']
                            info = "【交易提醒】OKEX期权合约持仓更新! 合约ID:{} 净持仓数量:{} 开仓平均价:{} 期权市值:{}".format(
                                instrument_id, position, avg_cost,
                                option_value)
                            if get_localtime()[11:16] != "16:00":
                                push(info)
        except Exception as e:
            time = get_timestamp()
            print(time + "连接断开,正在重连……")
            print(e)
            continue
Exemplo n.º 12
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
                                 })
Exemplo n.º 13
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
                                 })