예제 #1
0
 def __maximize(self):
     """
     最大化浏览器
     :return:
     """
     try:
         self.drive.maximize_window()
     except:
         logger.exception(traceback.format_exc())
         logger.exception('最大化浏览器失败')
예제 #2
0
 def quit(self):
     """
     退出浏览器;
     自动化测试时,禁止频繁启动停止浏览器
     原因:启动很慢,运行也比较慢,不过,启动之后Webdriver的操作速度虽然不快但还是可以接受的
     :return:
     """
     try:
         self.drive.quit()
         return True
     except:
         logger.exception(traceback.format_exc())
         return False
예제 #3
0
 def visit_url(self, url='None'):
     """
     访问被测页面
     :param url:
     :return:
     """
     try:
         self.drive.get(url)
         return True
     except:
         logger.exception(traceback.format_exc())
         logger.exception('访问页面失败')
         return False
예제 #4
0
 def screenshot(self, locator='None', save_img_path='../data/imgs/verify_img.png'):
     """
     在当前元素上进行截图,默认格式:.png
     :param locator: 定位表达式
     :param save_img_path: 截图图片保存路径
     :return:
     """
     try:
         element_img = self.__locator_element(locator)
         element_img.screenshot(filename=save_img_path)
         return True
     except:
         logger.exception(traceback.format_exc())
         return False
예제 #5
0
 def run_js(self, js='None'):
     """
     执行js
     :param js: 可执行的语句
     :return:
     """
     try:
         # print(js)
         self.js_data = self.drive.execute_script(js)
         return True
     except:
         logger.exception(traceback.format_exc())
         logger.exception('js语言执行失败')
         return False
예제 #6
0
 def __js_click(self, locator='None'):
     """
     找到元素,并点击
     :param locator: 定位器
     :return: 是否点击成功
     """
     try:
         element = self.__locator_element(locator=locator)
         self.drive.execute_script("$(arguments[0]).click()", element)
         return True
     except:
         logger.exception('元素未找到或者点击失败')
         logger.exception(traceback.format_exc())
         return False
예제 #7
0
 def sleep(self, times=1):
     """
     固定等待时间,默认等待1s'
     :param times: 需要等待的时间
     :return:
     """
     try:
         times = int(times)
         time.sleep(times)
         return True
     except:
         logger.exception(traceback.format_exc())
         time.sleep(1)
         logger.exception('固定等待输入格式不对,程序自动默认等待1s')
         return False
예제 #8
0
 def into_iframe(self, locator='None'):
     """
     进入iframe
     :param locator: 定位器
     :return: 是否进入成功
     """
     try:
         element = self.__locator_element(locator=locator)
         # self.drive.switch_to_frame(element)   # 已过时
         self.drive.switch_to.frame(element)
         return True
     except:
         logger.exception(traceback.format_exc())
         logger.exception('进入iframe失败')
         return False
예제 #9
0
 def input(self, locator='None', content='None'):
     """
     找到元素后,并输入文本内容
     :param locator: 定位器
     :param content: 输入文本内容
     :return: 是否输入成功
     """
     # print('input=%s' % locator)
     try:
         element = self.__locator_element(locator=locator)
         element.send_keys(str(content))
         return True
     except:
         logger.exception(traceback.format_exc())
         logger.exception('元素未找到或者输入失败')
         return False
예제 #10
0
    def __get_element_src(self, locator='None'):
        """
        根据元素定位,获取元素中src属性的url地址,下载照片
        :param locator: 定位表达式
        :return: 查找元素的src信息
        """
        try:
            element = self.__locator_element(locator)
            # 获取照片url
            element_src = element.get_attribute('src')

            self.width = element.size['width']
            self.height = element.size['height']
            return element_src
        except:
            logger.exception(traceback.format_exc())
            return None
예제 #11
0
 def verify_recognition(self, locator='None', img_path='../data/imgs/verify_img.png', code_type='1902'):
     """
     常见4~6位英文数字验证码识别识别
     :param locator: 定位表达式
     :param code_type: 验证码类型 参考:http://www.chaojiying.com/price.html
     :param img_path:
     :return:
     """
     try:
         self.screenshot(locator, img_path)
         # 提供的账号和密码,超级鹰平台图片识别一分钱识别一次,账号没有可能无法识别
         verify1 = Verify('wuqingfqng', '6e8ebd2e301f3d5331e1e230ff3f3ca5', '96001')
         self.verify_code = verify1.post_picture(code_type=code_type, im=img_path)
         return self.verify_code
     except:
         logger.exception(traceback.format_exc())
         return 'None'
예제 #12
0
 def switch_window(self, index='0'):
     """
     切换窗口
     :param index:需要切换到的窗口序号
     :return:是否切换成功
     """
     try:
         # 将输入的index转化为字符串
         index = int(index)
         # 获取当前页面有多少个窗口选项
         handle = self.drive.window_handles
         # 切换
         self.drive.switch_to.window(handle[index])
         return True
     except:
         logger.exception(traceback.format_exc())
         logger.exception('窗口切换失败,需切换的窗口序号%s' % index)
         return False
예제 #13
0
 def upload_picture(self, locator, path='../data/imgs/upload.png'):
     """
     实现文件上传
     :param locator: 定位表达式
     :param path: 上传文件的路径:绝对路径
     :return: 是否成功
     """
     try:
         path = os.path.abspath(path)
         if os.path.isfile(path):
             element = self.__locator_element(locator)
             element.sendkeys(path)
             return True
         else:
             logger.exception('文件不存在,路径:%s' % path)
             return False
     except:
         logger.exception(traceback.format_exc())
         return False
예제 #14
0
    def click(self, locator='None'):
        """
        找到元素,并点击
        :param locator: 定位器
        :return: 是否点击成功
        """
        try:
            # ie调用.click()没有作用,使用js点击
            if self.browser == "ie":
                return self.__js_click(locator)
            else:
                element = self.__locator_element(locator=locator)
                element.click()
                return True

        except Exception:
            logger.exception(traceback.format_exc())
            logger.exception('元素未找到或者点击失败')
            return False
예제 #15
0
    def __locator_element(self, locator='None', method='xpath'):
        """
        8种定位方式,默认使用xpath
        基于method的值,来选择定位的方式,并且使用locator作为定位表达式
        :param method:定位方式类型
        :param locator:定位表达式
        :return:
        """
        # xpath定位,最大优势,可以用text()文本定位
        # 放在第一个便于自动化时第一个判决就可以找到xpath
        try:
            if method == 'xpath':
                self.element = self.drive.find_element_by_xpath(locator)
            # 基于元素的id属性进行定位,实际上用的就是  # id通过css选择器定位。  用kw.
            elif method == 'id':
                self.element = self.drive.find_element_by_id(locator)
            # 基于元素name属性定位 用 wd
            elif method == 'name':
                self.element = self.drive.find_element_by_name(locator)
            # 基于元素标签名定位,就是input标签
            elif method == 'tagname':
                self.element = self.drive.find_element_by_tag_name(locator)
            # 基于css样式class属性定位 s_ipt
            elif method == 'classname' or method == 'class':
                self.element = self.drive.find_element_by_class_name(locator)
            # 基于超链接的文本内容定位,只能用于a元素
            elif method == 'linktext' or method == 'link':
                self.element = self.drive.find_element_by_link_text(locator)
            # 基于超链接的部分文本内容定位,只能用于a元素
            elif method == 'partiallinktext' or method == 'partiallink':
                self.element = self.drive.find_element_by_partial_link_text(locator)
            # css选择器定位。 速度快
            elif method == 'css':
                self.element = self.drive.find_element_by_css(locator)
            # 输入mothod不匹配时,默认使用xpath
            else:
                self.element = self.drive.find_element_by_xpath(locator)

            return self.element
        except Exception:
            logger.exception(traceback.format_exc())
            return False
예제 #16
0
 def hovering(self, locator='None'):
     """
     找到元素,将鼠标悬停在上面,用一些特定场景:如,鼠标移动到元素上,会出现下拉框
     :param locator: 定位表达式
     :return: 成功或者失败
     """
     try:
         element = self.__locator_element(locator)
         # ie浏览器使用js滚动到所以查找的元素位置
         if self.browser == 'ie':
             x = element.location.get('x')
             y = element.location.get('y')
             self.run_js('window.scrollTo(%d,%d)' % (x, y))
         else:
             action = ActionChains(self.drive)
             action.move_to_element(element).perform()
         return True
     except:
         logger.exception(traceback.format_exc())
         return False
예제 #17
0
def check_order_status():
    while 1:
        bnb_order_id = -1
        bhb_order_sell_id = -1
        bhb_order_buy_id = -1
        bnb_order_info = None
        bhb_order_sell_info = None
        bhb_order_buy_info = None
        for hedge in hedges:
            for bnb_order_id, bnb_order_info in hedge['binance_orders'].items(
            ):
                if bnb_order_info is not None:
                    if bnb_order_info['status'] == 'CANCLED':
                        continue
                    else:
                        break
                    #bnb_order_info = bnb.get_order_info(bnb_order_id)
                    #hedge['binance_orders'][bnb_order_id] = bnb_order_info

            for bhb_order_sell_id, bhb_order_sell_info in hedge[
                    'bithumb_sells'].items():
                if bhb_order_sell_info is not None:
                    if bhb_order_sell_info['status'] == "CANCLED":
                        continue
                    else:
                        break
                    #bhb_order_sell_info = bhb.get_order_status(bhb_order_sell_id)
                    #if bhb_order_sell_info is not None:
                    #   hedge['bithumb_sells'][bhb_order_sell_id] = bhb_order_sell_info

            for bhb_order_buy_id, bhb_order_buy_info in hedge[
                    'bithumb_buys'].items():
                if bhb_order_buy_info is not None:
                    if bhb_order_buy_info['status'] == "CANCLED":
                        continue
                    else:
                        break
                    #bhb_order_buy_info = bhb.get_order_status(bhb_order_buy_id)
                    #if bhb_order_buy_info is not None:
                    #   hedge['bithumb_buys'][bhb_order_buy_id] = bhb_order_buy_info
            '''1,1,1:全部成功,直接入库'''
            try:

                if (bnb_order_info is not None
                        and bnb_order_info['status'] == 'FILLED') and (
                            bhb_order_buy_info is not None
                            and bhb_order_buy_info['status'] == 'FILLED') and (
                                bhb_order_sell_info is not None
                                and bhb_order_sell_info['status'] == 'FILLED'):
                    logger.info(bnb_order_info)
                    logger.info(bhb_order_buy_info)
                    logger.info(bhb_order_sell_info)
                    hedge['status'] = 'success'

                    if bnb_order_info['side'] == 'BUY':
                        hedge['profit'] = bhb_order_buy_info[
                            'deal_quantity'] - bnb_order_info['deal_amount']
                    else:
                        hedge['profit'] = bnb_order_info[
                            'deal_amount'] - bhb_order_sell_info[
                                'deal_quantity']

                    logger.info("hedge success: %s", hedge)
                    write_hedge_info(hedge)
                    hedges.remove(hedge)
                else:
                    logger.error("对冲未成功:%s", hedge)
                    bnb_order_info = bnb.get_order_info(bnb_order_id)
                    bhb_order_sell_info = bhb.get_order_status(
                        bhb_order_sell_id)
                    bhb_order_buy_info = bhb.get_order_status(bhb_order_buy_id)
                    if bnb_order_info is not None:
                        hedge['binance_orders'][bnb_order_id] = bnb_order_info
                    if bhb_order_buy_info is not None:
                        hedge['bithumb_buys'][
                            bhb_order_buy_id] = bhb_order_buy_info
                    if bhb_order_sell_info is not None:
                        hedge['bithumb_sells'][
                            bhb_order_sell_id] = bhb_order_sell_info

            except BaseException, e:
                logger.exception("check_order_status: %s", e)
                '''0,0,0:全部不成功,直接取消交易
            elif bnb_order_info['status'] == 'PARTIALLY_FILLED' and bhb_order_buy_info['status'] == 'PARTIALLY_FILLED' and bhb_order_sell_info['status'] == 'PARTIALLY_FILLED':
                bnb.order_cancel(bnb_order_id)
                bhb.order_cancel(bhb_order_buy_id)
                bhb.order_cancel(bhb_order_sell_id)

                0,0,1:binance不成功,bithumb买入不成功,检查目前深度数据是否适合继续交易,如果适合,把剩余的量交易掉
            #elif bnb_order_info['status'] == 'PARTIALLY_FILLED' and bhb_order_buy_info['status'] == 'PARTIALLY_FILLED' and bhb_order_sell_info['status'] == 'FILLED':

                0,1,0:binance不成功,bithumb卖出不成功
            #elif bnb_order_info['status'] == 'PARTIALLY_FILLED' and bhb_order_buy_info['status'] == 'FILLED' and bhb_order_sell_info['status'] == 'PARTIALLY_FILLED':

                0,1,1:binance不成功
            elif bnb_order_info['status'] == 'PARTIALLY_FILLED' and bhb_order_buy_info['status'] == 'FILLED' and bhb_order_sell_info['status'] == 'FILLED':
                bnb_depth = bnb.get_current_depth()
                if bnb_order_info['side'] == 'BUY' and ((bhb_order_sell_info['deal_price'] / bhb_order_buy_info['deal_price']) / bnb_depth['asks'][0]['price'] - 1 > config.profit_rate):
                    tries = 0
                    while tries < 5:
                        bnb_new_order_id, bnb_new_order_info = bnb.create_order("BUY", bnb_depth['asks'][0]['price'], bnb_order_info['order_quantity'] - bnb_order_info['deal_quantity'])
                        if bnb_new_order_id > 0:
                            break
                        tries += 1
                        time.sleep(0.1)
                    if tries == 5:
                        logger.error("bnb未成交重新交易失败,维持原交易")
                    else:
                        bnb.order_cancel(bnb_order_id)
                        hedge['binance_orders'][bnb_new_order_id] = bnb_new_order_info
                elif bnb_order_info['side'] == 'SELL' and (bnb_depth['bids'][0]['price']/ (bhb_order_sell_info['deal_price'] / bhb_order_buy_info['deal_price']) - 1 > config.profit_rate):
                    tries = 0
                    while tries < 5:
                        bnb_new_order_id, bnb_new_order_info = bnb.create_order("SELL", bnb_depth['bids'][0]['price'],
                                                                                bnb_order_info['order_quantity'] -
                                                                                bnb_order_info['deal_quantity'])
                        if bnb_new_order_id > 0:
                            break
                        tries += 1
                        time.sleep(0.1)
                    if tries == 5:
                        logger.error("bnb未成交重新交易失败,维持原交易")
                    else:
                        bnb.order_cancel(bnb_order_id)
                        hedge['binance_orders'][bnb_new_order_id] = bnb_new_order_info

                1,0,0:bithumb买入、卖出都不成功
            #elif bnb_order_info['status'] == 'FILLED' and bhb_order_buy_info['status'] == 'PARTIALLY_FILLED' and bhb_order_sell_info['status'] == 'PARTIALLY_FILLED':

                1,0,1:bithumb买入不成功
            elif bnb_order_info['status'] == 'FILLED' and bhb_order_buy_info['status'] == 'PARTIALLY_FILLED' and bhb_order_sell_info['status'] == 'FILLED':
                bhb_depth = bhb.get_current_depth()
                if bnb_order_info['side'] == 'BUY' and ((bhb_order_sell_info['deal_price']/bhb_depth[payment_currency]['asks'][0]['price']) / bnb_order_info['deal_price'] - 1 > config.profit_rate):
                    tries = 0
                    while tries < 5:
                        bhb_new_order_buy_id, bhb_new_order_buy_info = bhb.order_buy(bhb_depth[payment_currency]['asks'][0]['price'], bhb_order_buy_info['order_quantity'] - bhb_order_buy_info['deal_quantity'], payment_currency)
                        if bhb_new_order_buy_id > 0:
                            break
                        tries += 1
                        time.sleep(0.1)
                    if tries == 5:
                        logger.error("bhb未成交重新交易失败,维持原交易")
                    else:
                        bhb.order_cancel(bhb_order_buy_id)
                        hedge['bithumb_buys'][bhb_new_order_buy_id] = bhb_new_order_buy_info
                elif bnb_order_info['side'] == 'SELL' and (bnb_order_info['deal_price']/(bhb_depth[order_currency]['asks'][0]['price'] / bhb_order_sell_info['deal_price']) - 1 > config.profit_rate):
                    tries = 0
                    while tries < 5:
                        bhb_new_order_buy_id, bhb_new_order_buy_info = bhb.order_buy(
                            bhb_depth[order_currency]['asks'][0]['price'],
                            bhb_order_buy_info['order_quantity'] - bhb_order_buy_info['deal_quantity'],
                            payment_currency)
                        if bhb_new_order_buy_id > 0:
                            break
                        tries += 1
                        time.sleep(0.1)
                    if tries == 5:
                        logger.error("bhb未成交重新交易失败,维持原交易")
                    else:
                        bhb.order_cancel(bhb_order_buy_id)
                        hedge['bithumb_buys'][bhb_new_order_buy_id] = bhb_new_order_buy_info

                1,1,0:bithumb卖出不成功
            #elif bnb_order_info['status'] == 'FILLED' and bhb_order_buy_info['status'] == 'FILLED' and bhb_order_sell_info['status'] == 'PARTIALLY_FILLED':'''

        time.sleep(1)
예제 #18
0
def write_hedge_info(hedge):
    try:
        conn.execute('INSERT INTO hedge_info  VALUES (?,?,?,?,?,?,?,?)', [
            str(hedge['hedge_id']), hedge['bid_exchange'],
            hedge['ask_exchange'], hedge['symbol'], hedge['quantity'],
            hedge['profit'], hedge['status'], hedge['date_time']
        ])

        for order_id, order_info in hedge['binance_orders'].items():
            conn.execute(
                'INSERT INTO order_info VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                [
                    order_id, 'binance', order_info['symbol'],
                    order_info['side'], order_info['status'],
                    order_info['order_price'], order_info['deal_price'],
                    order_info['order_quantity'], order_info['deal_quantity'],
                    order_info['order_amount'], order_info['deal_amount'],
                    order_info['deal_fee'], order_info['fee_asset'],
                    order_info['date_time'],
                    str(hedge['hedge_id'])
                ])
            for trade in order_info['trades'].values():
                conn.execute('insert into trade_info values (?,?,?,?,?,?,?)', [
                    trade['trade_id'], trade['commission'],
                    trade['commissionAsset'], trade['order_id'],
                    trade['price'], trade['quantity'], trade['date_time']
                ])

            for order_id, order_info in hedge['bithumb_buys'].items():
                conn.execute(
                    'INSERT INTO order_info VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                    [
                        order_id, 'bithumb', order_info['symbol'],
                        order_info['side'], order_info['status'],
                        order_info['order_price'], order_info['deal_price'],
                        order_info['order_quantity'],
                        order_info['deal_quantity'],
                        order_info['order_amount'], order_info['deal_amount'],
                        order_info['deal_fee'], order_info['fee_asset'],
                        order_info['date_time'],
                        str(hedge['hedge_id'])
                    ])
                for trade in order_info['trades'].values():
                    conn.execute(
                        'insert into trade_info values (?,?,?,?,?,?,?)', [
                            trade['trade_id'], trade['commission'],
                            trade['commissionAsset'], trade['order_id'],
                            trade['price'], trade['quantity'],
                            trade['date_time']
                        ])

            for order_id, order_info in hedge['bithumb_sells'].items():
                conn.execute(
                    'INSERT INTO order_info VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                    [
                        order_id, 'bithumb', order_info['symbol'],
                        order_info['side'], order_info['status'],
                        order_info['order_price'], order_info['deal_price'],
                        order_info['order_quantity'],
                        order_info['deal_quantity'],
                        order_info['order_amount'], order_info['deal_amount'],
                        order_info['deal_fee'], order_info['fee_asset'],
                        order_info['date_time'],
                        str(hedge['hedge_id'])
                    ])
                for trade in order_info['trades'].values():
                    conn.execute(
                        'insert into trade_info values (?,?,?,?,?,?,?)', [
                            trade['trade_id'], trade['commission'],
                            trade['commissionAsset'], trade['order_id'],
                            trade['price'], trade['quantity'],
                            trade['date_time']
                        ])
    except BaseException, e:
        logger.exception("write_hedge_info: %s", e)