def setup_class(cls): dr = Driver() cls.driver = dr.init_driver(device_name) cls.GDL = gdl.Get_device_log()
def setUp(self) -> None: with allure.step("Instantiate Driver"): self.driver = Driver() with allure.step("Set desired capabilities"): self.driver.set_capability("platformName", self.args["platformName"]) self.driver.set_capability("deviceName", self.args["deviceName"]) self.driver.set_capability("automationName", self.args["automationName"]) self.driver.set_capability("browserName", "Chrome") self.driver.set_capability( 'chromedriverExecutable', 'C:\\Users\\superadmin\\Documents\\GitHub\\' 'TEST_AUTOMATION_FRAMEWORK_USING_APPIUM_WITH_PYTHON\\' 'drivers\\chromedriver\\v2_44\\chromedriver.exe') # Set Implicit Wait Timeout - the amount of time # the driver should wait when searching for element self.driver.driver_instance.implicitly_wait(5000) # NOTE: In addCleanup, the first in, is executed last. with allure.step("Add clean up methods"): self.addCleanup(self.driver.driver_instance.quit) self.addCleanup(self.snap_shot) with allure.step("Get driver/page instance"): self.driver.driver_instance.implicitly_wait(3) self.driver = self.driver.driver_instance
def __init__(self): self.logger = logging.getLogger(__name__ + ".wrapper") self.driver = Driver() self._my_contract_details = {} self._my_market_data_dict = {} self._my_open_orders = queue.Queue() self._my_executions_stream = queue.Queue() self._my_commission_stream = queue.Queue()
def save_cookie(self): driver = Driver() driver.login() cookie = driver.get_cookie() with open(COOKIE_PATH, 'w', encoding='utf-8') as f: f.write(str(cookie)) f.close() return cookie
def __init__(self, init_speed=10): self.cam = Cam() self.ultrasonic = UltraSonic() self.driver = Driver() self.driver.SetSpeed(init_speed) self.servo_s = Servo(23) self.moved_distance = 0 self.micro_move_cnt = 0
class Car(): def __init__(self, init_speed=10): self.cam = Cam() self.ultrasonic = UltraSonic() self.driver = Driver() self.driver.SetSpeed(init_speed) self.servo_s = Servo(23) self.moved_distance = 0 self.micro_move_cnt = 0 def StartToGo(self): self.driver.GoForward() def ComingOutFromJam(self): self.driver.DoShortFastBackward() if (random.randint(-2, 1) > 0): self.driver.DoSpinRight90Turn() else: self.driver.DoSpinLeft90Turn() def GoToCorrectDirection(self): ori_speed = self.driver.GetSpeed() self.driver.SetSpeed(ori_speed / 3) if self.GetNextDirection(): self.driver.DoSpinRight90Turn() else: self.driver.DoSpinLeft90Turn() self.driver.SetSpeed(ori_speed) def GetNextDirection(self): self.servo_s.TurnToLeft() l_distance = self.ultrasonic.GetDistance() self.servo_s.TurnToRight() r_distance = self.ultrasonic.GetDistance() self.servo_s.TurnToCenter() time.sleep(0.1) return r_distance > l_distance def RandomStep(self, blocked_distance=50): self.StartToGo() last_distance = self.ultrasonic.last_distance distance = self.ultrasonic.GetDistance() print("*******************cur_distance is %.5s " % distance, end="") if distance < blocked_distance: print("################# wall") self.GoToCorrectDirection() self.micro_move_cnt = 0 else: print("................ go") self.StartToGo() time.sleep(0.1) if abs(last_distance - distance) < 1: self.micro_move_cnt = self.micro_move_cnt + 1 else: self.micro_move_cnt = 0 if self.micro_move_cnt > 5: self.ComingOutFromJam()
def elements(xpath_selection): """ Return list of elements that match xpath selection Args: selection (str): xpath selection string Returns: WebElement """ driver = Driver().connect() return driver.find_elements_by_xpath(xpath_selection)
def driver(request): browser = request.config.getoption('--browser') desired_capabilities = capabilities_for_browser_name(browser) test_name = f'{request.node.location[0]}::{request.node.location[2].replace(".", "::")}' desired_capabilities['name'] = test_name desired_capabilities['enableVNC'] = True remote_driver = Driver(command_executor=settings.REMOTE_URL, desired_capabilities=desired_capabilities) remote_driver.set_window_size(1920, 1080) yield remote_driver
class Installer(RPCServer): def __init__(self, addr, port): RPCServer.__init__(self, addr, port) self._app = App() self._driver = Driver() def install(self, uid, package, version, typ, content): if typ == APP: return self._app.install(uid, package, version, content) elif typ == DRIVER: return self._driver.install(uid, package, version) else: show_error(self, 'failed to install, invalid type, typ=%s' % str(typ)) def uninstall(self, uid, package, typ): if typ == APP: return self._app.uninstall(uid, package) else: show_error(self, 'failed to uninstall, invalid type, typ=%s' % str(typ)) def get_packages(self, uid, typ): if typ == APP: return self._app.get_packages(uid) def has_package(self, uid, package, typ): if typ == APP: return self._app.has_package(uid, package) def start(self): t = Thread(target=self.run) t.start() t.join()
def open_web_browser(config: Config, page_model, page_content): """ Take care of following procedure: 1. Instantiate Selenium webdriver 2. Instantiate Page Model Object 3. Checks HTTP status code 4. Open web browser > open test web page 5. Refresh web browser in case test web site is not loaded 6. Returns page instance (Page Model Object) :param config: :param page_model: :param page_content: :return: """ # Open web page with allure.step("Open following web page: {}.".format(page_content.URL)): driver = Driver(config=config, is_debug=True) print('\nbase_url: {}\n'.format(config.base_url)) page = page_model(config=config, driver=driver, implicit_wait_time=1, explicit_wait_time=10) page.go() get_http_status_code(page.url) refresh_page(page_content.TITLE, page) return page
def run_singlethread(): dl_client = Client(g_dl_server_addr) pc_client = Client(g_pc_server_addr) with Driver(signal_period=0, camera_resolution=(320, 240)) as driver_h: for state in driver_h: speed = config.BASE_SPEED angle = 45 ## car stat if state.power is None: # connect car failed logging.info("[RUN] car stat is None...") continue ## request DLServer pc_client.send(state.image_str) response = dl_client.send(state.image_str) if response is None: # connect DLServer failed logging.info("[RUN] dl_client rpc failed...") continue ## drive if state.sonar <= 20: speed = 0 angle = response.angle driver_h.drive(angle=angle, speed=5)
def main(): image_list = get_file_path_list(image_dir, ["png", "jpg", "jpeg"]) message_tmp = read_txt(messge_path) values = read_excel(customer_info_path, sheet_index=0, start_row=1, cols=2) names = values[0] mails = values[1] fail_list = list() url = "https://web.whatsapp.com/" wait_locator = (By.ID, "side") with Driver(url, executable_path=chromedriver_path, options=options, wait_locator=wait_locator) as driver: wap = WhatsAppPlug(driver) for i, mail in enumerate(mails): try: message = message_tmp.format(name=names[i].title()) messages = message.strip().split('\n') wap.search_customer(mail.strip()) wap.send_message(messages, image_list) except Exception as e: LOG.error(e) fail_list.append((names[i], mail)) if fail_list: LOG.error("fail_list: %s " % fail_list) write_exist_excel(customer_info_path, fail_list, sheet_index=1, start_row=0) time.sleep(60 * 3)
def test_success_auth(self, login, password, lang_btn_loc): Driver().get_url_with_basic_auth(LoginPage.BASE_URL) lang_btn_loc().click() LoginPage.login_input().wait_for_displayed().fill(login) LoginPage.password_input().fill(password) LoginPage.submit_btn().click() PaymentPage.status_selector().wait_for_displayed().assert_displayed() active_status = PaymentPage.gold_item().text with allure.step("Проверяем что активен статус Gold"): assert_that(active_status, contains_string('GOLD\n$1000 +100%'))
def setUp(self) -> None: with allure.step("Set up driver object"): self._driver = Driver() # Add desired capabilities: for key in self.args: if self.args[key] is not None: print("key: {}, value: {}".format(key, self.args[key])) self._driver.set_capability(key, self.args[key]) self._driver.set_capability('chromedriverExecutable', 'C:\\Users\\superadmin\\Documents\\GitHub\\' 'TEST_AUTOMATION_FRAMEWORK_USING_APPIUM_WITH_PYTHON\\' 'drivers\\chromedriver\\v2_44\\chromedriver.exe') ''' self._driver.set_capability("platformName", "android_native") self._driver.set_capability("deviceName", "Android Tablet") self._driver.set_capability("automationName", "Appium") self._driver.set_capability("appPackage", "com.android_native.calculator2") self._driver.set_capability("appActivity", "com.android_native.calculator2.Calculator") ''' with allure.step("Set up Page Model object"): self._driver.driver_instance.implicitly_wait(3) self.app = CalculatorPageModel(self._driver.driver_instance) # NOTE: In addCleanup, the first in, is executed last. with allure.step("Set up Cleanup methods"): self.addCleanup(self._driver.driver_instance.quit) self.addCleanup(self.snap_shot)
class Login(object): def __init__(self): self.driver = Driver().connect() def log_in(self): logger.info('Logging in.') # first open div containing fields for logging in self.driver.find_element_by_id('btn-login').click() logserver_select = Select( self.driver.find_element_by_id(conf.logserver_field_id)) username_input = self.driver.find_element_by_id(conf.username_field_id) password_input = self.driver.find_element_by_id(conf.password_field_id) submit_button = self.driver.find_element_by_id(conf.login_button_id) logserver_select.select_by_visible_text(credentials.server) username_input.send_keys(credentials.username) password_input.send_keys(credentials.password) submit_button.click() return self.wait_until_logged() def wait_until_logged(self): try: WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( (By.XPATH, conf.logged_in_check_element))) return True except: print("[ERROR] Timeout occurred while waiting for log in.") self.driver.save_screenshot('logging-in-err.png') return False @staticmethod def is_logged(): username_selector = '#GF_toolbar > ul > li.avatarName' if is_element_present(username_selector, 'css'): return element_text(username_selector, 'css') == credentials.username else: return False def ensure_logged(self): if not self.is_logged(): self.driver.get(conf.site_url) self.log_in()
def get_selector_method(sel_type): driver = Driver().connect() selector = None if sel_type == 'id': selector = driver.find_element_by_id elif sel_type == 'xpath': selector = driver.find_element_by_xpath elif sel_type == 'text': selector = driver.find_element_by_visible_text elif sel_type == 'css': selector = driver.find_element_by_css_selector return selector
def _driver_tag(gene_name, driver, suffix=None): if driver is None or driver.mutation_effect == 'unknown': return gene_name # number of supporting sources if Driver.MaxSourceSupport > 0: r, g, b, _ = Driver.colors()[len(driver.sources)] else: r, g, b = (0.8, 0.2, 0.2) c = 'color:#{0:02x}{1:02x}{2:02x};'.format(_clamp(r*255), _clamp(g*255), _clamp(b*255)) tag = '<font style="{}">{}{}</font>'.format(c, gene_name, '' if suffix is None else suffix) if driver.cgc_driver: # is driver in CGC list tag = '<strong>'+tag+'</strong>' return tag
def wait_for_displayed(self, wait_time=5, poll_frequency=0.3): with allure.step( f'Ожидаем что элемент {self.allure_name} появится в DOM дереве в течении {wait_time} секунд' ): try: WebDriverWait( Driver(), timeout=wait_time, poll_frequency=poll_frequency).until( expected_conditions.presence_of_element_located( (self.by, self.value))) except TimeoutException: raise NoSuchElementException( f'Элемент {self.allure_name} не появился в DOM дереве за {wait_time} секунд' ) return self()
def is_element_present(selection, sel_type='id'): driver = Driver().connect() driver.implicitly_wait(0) exists = True try: element(selection, sel_type) except NoSuchElementException: exists = False finally: driver.implicitly_wait(10) return exists
def test_forgot_password(self, lang_btn_loc, popup_text, btn_text): Driver().get_url_with_basic_auth(LoginPage.BASE_URL) lang_btn_loc().click() LoginPage.forgot_pass_btn().click() LoginPage.forgot_pass_input().wait_for_displayed().fill('test@test') LoginPage.forgot_pass_send_btn().click() LoginPage.FailAuthPopUp.notification_popup().wait_for_displayed() ''' Логически правильно было бы вынести это в отдельные тесты на локализацию, но т.к. посути это эмуляция отправки пароля я использовал это и тут ''' popup_existed_text = LoginPage.FailAuthPopUp.notification_popup_text().text popup_existed_btn = LoginPage.FailAuthPopUp.notification_popup_btn().text with allure.step("Проверяем что текст попапа совпадает с ожидаемым"): assert_that(popup_existed_text, equal_to(popup_text)) with allure.step("Проверяем что текст на кнопке попапа совпадает с ожидаемым"): assert_that(popup_existed_btn, equal_to(btn_text))
def run_multithread(): join_timeout_s = 3 # thread join timeout ## for exit signal.signal(signal.SIGINT, stop_worker) signal.signal(signal.SIGTERM, stop_worker) with Driver(signal_period=0, camera_resolution=(320, 240)) as driver_h: dl_client = Client(g_dl_server_addr) pc_client = Client(g_pc_server_addr) state_q = Queue.Queue() # for car state info # worker car_state_worker = CarStateWorker(driver_h, state_q) car_ctl_worker = CarCtlWorker(driver_h, state_q, dl_client, pc_client) car_state_worker.start() car_ctl_worker.start() while True: # just for signal to exit car_state_worker.join(join_timeout_s) car_ctl_worker.join(join_timeout_s) if not (car_ctl_worker.isAlive() or car_state_worker.isAlive()): break
class TestGoogleSearch(unittest.TestCase): browser = Driver() driver = None @classmethod def setUpClass(cls): cls.browser.start_driver() cls.driver = cls.browser.driver @classmethod def tearDownClass(cls): cls.browser.quit_driver() def test_search_action(self): data = Yaml( "/usr/src/selenium/src/python/useUnittest/data/testGoogleSearch.yml" ).read() I_AGREE_BUTTON = data["elements"]["buttons"]["i_agree_button"] SEARCH_INPUT = data["elements"]["inputs"]["search_input"] SEARCH_TERM = data["text"]["search_term"] # accept t&c self.current_selection = self.driver.find_element( By.XPATH, I_AGREE_BUTTON, ).click() # make a simple search self.current_selection = self.driver.find_element( By.XPATH, SEARCH_INPUT, ).send_keys(SEARCH_TERM + Keys.ENTER) # perform test title_arr = self.driver.title.split("-") self.assertEqual(title_arr[0].strip(), SEARCH_TERM) time.sleep(10)
def screen_swipe(self, tag=1): """ 滑动方法 :param tag: 1:↑ 2: ↓ 3: ← 4: → :return: """ driver = Driver.get_app_driver() # 分辨率 size = driver.get_window_size() # 宽 width = size.get("width") # 高 height = size.get("height") # 等待 time.sleep(1.5) if tag == 1: # 宽*50%,高*80% -> 宽*50%,高*20% logging.info("向上滑动") driver.swipe(width * 0.5, height * 0.8, width * 0.5, height * 0.2, 1500) if tag == 2: logging.info("向下滑动") # 宽*50%,高*20% -> 宽*50%,高*80% driver.swipe(width * 0.5, height * 0.2, width * 0.5, height * 0.8, 1500) if tag == 3: logging.info("向左滑动") # 宽*80%,高*50% -> 宽*20%,高*50% driver.swipe(width * 0.8, height * 0.5, width * 0.2, height * 0.5, 1500) if tag == 4: logging.info("向右滑动") # 宽*20%,高*50% -> 宽*80%,高*50% driver.swipe(width * 0.2, height * 0.5, width * 0.8, height * 0.5, 1500)
def teardown_class(self): Driver.quit_app_driver()
def __call__(self, wait_time=10) -> 'Locator': self.driver = Driver() self.element = (self.parent_element or self.driver).get_element(self, wait_time=wait_time) return self
from utils.driver import Driver from utils.neuron import Neuron from utils.detector import Detector from utils.player import Player import numpy as np from scipy import signal import matplotlib.pyplot as plt import time import keyboard from brian2 import NeuronGroup, ms # initialise classes det = Detector("hand") plr = Player() drv = Driver() time.sleep(0.1) drv.lowerTurn() ## Comment to remove plottingqq fig, ax = plt.subplots() ax.set_ylim([-0.08, 0.07]) line1, = ax.plot(np.linspace(0, 10000, 10000), np.zeros(10000), 'r-') line2, = ax.plot(np.linspace(0, 10000, 10000), np.zeros(10000), 'b-') line3, = ax.plot(np.linspace(0, 10000, 10000), np.zeros(10000), 'g-') plt.show(block=False) fig.canvas.draw() ## /Comment to remove plotting # Izhikevitch Neuron Model from http://brian2.readthedocs.io/en/stable/introduction/brian1_to_2/library.html eqs = '''dv/dt = (0.04*active/ms/mV + 0.04/ms/mV)*v**2+(5/ms)*v+130*mV/ms-w + I : volt (unless refractory)
from scipy import signal import matplotlib.pyplot as plt import time import keyboard from brian2 import NeuronGroup, ms ## Comment to remove plotting fig, ax = plt.subplots() ax.set_ylim([-0.08, 0.07]) line1, = ax.plot(np.linspace(0, 10000, 10000), np.zeros(10000), 'r-') line2, = ax.plot(np.linspace(0, 10000, 10000), np.zeros(10000), 'b-') plt.show(block=False) fig.canvas.draw() ## /Comment to remove plotting drv = Driver() eqs_1 = '''dv/dt = (0.04*active/ms/mV + 0.04/ms/mV)*v**2+(5/ms)*v+130*mV/ms-w + I : volt (unless refractory) dw/dt = (0.02/ms)*((0.2/ms)*v-w) : volt/second active : 1 I : volt/second''' eqs_2 = '''dv/dt = (0.04*active/ms/mV + 0.04/ms/mV)*v**2+(5/ms)*v+140*mV/ms-w + I : volt (unless refractory) dw/dt = (0.02/ms)*((0.2/ms)*v-w) : volt/second active : 1 I : volt/second''' nrn_1 = Neuron( NeuronGroup(1, eqs_1, threshold='v > 50*mV',
class IBWrapper(EWrapper): """ The wrapper deals with the action coming back from the IB gateway or TWS instanc. We override methods in EWrapper that will get called when this action happens, like currentTime. """ _msg_queue = queue.Queue() _contract_details = {} _my_historic_data_dict = {} _accepted_error_codes = [2106, 2107] _my_accounts = {} def __init__(self): self.logger = logging.getLogger(__name__ + ".wrapper") self.driver = Driver() self._my_contract_details = {} self._my_market_data_dict = {} self._my_open_orders = queue.Queue() self._my_executions_stream = queue.Queue() self._my_commission_stream = queue.Queue() def add_to_queue_class(ibwrapper_function): def wrap_the_wrapper(*args, **kwargs): _self = args[0] # just in case ibwrapper_function(*args, **kwargs) return wrap_the_wrapper @add_to_queue_class def currentTime(self, time_from_server): # Overriden method self._msg_queue.put(time_from_server) # self._time_queue.put(time_from_server) def handle_queue_timeout(self, queue): """Handles timeouts of queue readings. Try to read the queue several times in case of delayed data delivery by IB. :param queue: the queue to be read :return: the processed data in the queue """ for t in range(MAX_TRIES_READING_QUEUE): self.logger.info("Attempt %s to read hist data queue." % t) queue_data = queue.get(timeout=MAX_WAIT_SECONDS) if not queue_data.timed_out(): return queue_data return queue.timed_out() # error handling code def init_error(self): error_queue = queue.Queue() self._my_errors = error_queue def get_error(self, timeout=5): if self.is_error(): try: return self._my_errors.get(timeout=timeout) except queue.Empty: return None return None def is_error(self): an_error_if = not self._my_errors.empty() return an_error_if def error(self, id, errorCode, errorString): # Overriden method if errorCode not in self._accepted_error_codes: errormsg = "IB error id %d errorcode %d string %s" % ( id, errorCode, errorString) self._my_errors.put(errormsg) """ Executions and commissions Requested executions get dropped into single queue: self._my_requested_execution[reqId] Those that arrive as orders are completed without a relevant reqId go into self._my_executions_stream. All commissions go into self._my_commission_stream (could be requested or not). The *_stream queues are permanent, and init when the TestWrapper instance is created """ def execDetails(self, reqId, contract, execution): """ This is called if a) we have submitted an order and a fill has come back (in which case reqId will be FILL_CODE) b) We have asked for recent fills to be given to us (reqId will be See API docs for more details """ execdata = execInformation(execution.execId, contract=contract, ClientId=execution.clientId, OrderId=execution.orderId, time=execution.time, AvgPrice=execution.avgPrice, AcctNumber=execution.acctNumber, Shares=execution.shares, Price=execution.price) self.logger.info("in execData") # there are some other things in execution you could add # make sure you add them to the .attributes() field of the # execInformation class reqId = int(reqId) # We either put this into a stream if its just happened, # or store it for a specific request if reqId == FILL_CODE: self._my_executions_stream.put(execdata) else: self._my_requested_execution[reqId].put(execdata) def execDetailsEnd(self, reqId): """ No more orders to look at if execution details requested """ self._my_requested_execution[reqId].put(FINISHED) # orders def init_open_orders(self): open_orders_queue = self._my_open_orders = queue.Queue() return open_orders_queue def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permid, parentId, lastFillPrice, clientId, whyHeld, mktCapPrice=0): order_details = orderInformation(orderId, status=status, filled=filled, avgFillPrice=avgFillPrice, permid=permid, parentId=parentId, lastFillPrice=lastFillPrice, clientId=clientId, whyHeld=whyHeld) self.driver.trace_order_status(orderId, order_details) self._my_open_orders.put(order_details) def openOrder(self, orderId, contract, order, orderstate): """ Tells us about any orders we are working now overriden method """ self.logger.info("Order: %s, %s %s %s (%s) %s@%s %s", orderId, order.orderType, order.action, contract.symbol, contract.secType, order.totalQuantity, order.auxPrice, order.tif) order_details = orderInformation(orderId, contract=contract, order=order, orderstate=orderstate) self._my_open_orders.put(order_details) def openOrderEnd(self): """ Finished getting open orders Overriden method """ self._my_open_orders.put(FINISHED) # order ids def init_nextvalidid(self): orderid_queue = self._my_orderid_data = queue.Queue() return orderid_queue def nextValidId(self, orderId): """ Give the next valid order id Note this doesn't 'burn' the ID; if you call again without executing the next ID will be the same If you're executing through multiple clients you are probably better off having an explicit counter """ if getattr(self, '_my_orderid_data', None) is None: # getting an ID which we haven't asked for # this happens, IB server just sends this along occassionally self.init_nextvalidid() self._my_orderid_data.put(orderId) # get contract details code def init_contractdetails(self, reqId): contract_details_queue = self._my_contract_details[ reqId] = queue.Queue() return contract_details_queue def contractDetails(self, reqId, contractDetails): # overridden method if reqId not in self._my_contract_details.keys(): self.init_contractdetails(reqId) self._my_contract_details[reqId].put(contractDetails) def contractDetailsEnd(self, reqId): # overriden method if reqId not in self._my_contract_details.keys(): self.init_contractdetails(reqId) self._my_contract_details[reqId].put(FINISHED) # Historic data code def init_historicprices(self, tickerid): historic_data_queue = self._my_historic_data_dict[ tickerid] = queue.Queue() return historic_data_queue def historicalData(self, tickerid, bar): # Overriden method # Note I'm choosing to ignore barCount, WAP and hasGaps but you could use them if you like bardata = (bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume) historic_data_dict = self._my_historic_data_dict # Add on to the current data if tickerid not in historic_data_dict.keys(): self.init_historicprices(tickerid) historic_data_dict[tickerid].put(bardata) def historicalDataEnd(self, tickerid, start: str, end: str): # overriden method if tickerid not in self._my_historic_data_dict.keys(): self.init_historicprices(tickerid) self._my_historic_data_dict[tickerid].put(FINISHED) # market data def init_market_data(self, tickerid): market_data_queue = self._my_market_data_dict[tickerid] = queue.Queue() return market_data_queue def get_time_stamp(self): # Time stamp to apply to market data # We could also use IB server time return datetime.datetime.now() def tickPrice(self, tickerid, tickType, price, attrib): # overriden method # For simplicity I'm ignoring these but they could be useful to you... # See the documentation http://interactivebrokers.github.io/tws-api/md_receive.html#gsc.tab=0 # attrib.canAutoExecute # attrib.pastLimit this_tick_data = IBtick(self.get_time_stamp(), tickType, price) self._my_market_data_dict[tickerid].put(this_tick_data) def tickSize(self, tickerid, tickType, size): # overriden method this_tick_data = IBtick(self.get_time_stamp(), tickType, size) self._my_market_data_dict[tickerid].put(this_tick_data) def tickString(self, tickerid, tickType, value): # overriden method # value is a string, make it a float, and then in the parent class will be resolved to int if size this_tick_data = IBtick(self.get_time_stamp(), tickType, float(value)) self._my_market_data_dict[tickerid].put(this_tick_data) def tickGeneric(self, tickerid, tickType, value): # overriden method this_tick_data = IBtick(self.get_time_stamp(), tickType, value) self._my_market_data_dict[tickerid].put(this_tick_data) # get account summary def init_accounts(self, reqId): accounting_queue = self._my_accounts[reqId] = queue.Queue() return accounting_queue def accountSummary(self, reqId: int, account: str, tag: str, value: str, currency: str): # use this to seperate out different account data data = (reqId, account, tag, value, currency) self._my_accounts[reqId].put(data) def accountSummaryEnd(self, reqId: int): self._my_accounts[reqId].put(FINISHED)
def __init__(self): self.logger = logging.getLogger(__name__) self.driver = Driver()
def __init__(self): self.driver = Driver().get_driver()