def update_prices(): services = [ 'click', 'gaitame', 'lion', 'pfx', 'nano', 'sbi', 'try', 'yjfx', 'noaccount' ] instruments = ('USD/JPY', 'EUR/JPY', 'GBP/JPY', 'AUD/JPY') prices = [] accounts = [] for service in services: positions = {} for i, instrument in enumerate(instruments): bid = 101 + i + random.random() * 0.8 / 100 ask = 100 + i + random.random() * 0.2 / 100 prices.append( dict(time=timeutil.jst_now(), service=service, instrument=instrument, bid=bid, ask=ask)) if services.index(service) < len(services) / 2: positions[instrument] = random.randint(0, 3) * 1000 else: positions[instrument] = random.randint(0, 3) * -1000 if service != 'noaccount': accounts += [new_account(service, positions=positions)] GlobalSignal().update_prices.emit(prices) GlobalSignal().update_accounts.emit(accounts)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.account = new_account(self.name) self.update_accounts([self.account]) self.conn_factory = lambda *args, **kwargs: CustomConnection( *args, on_data=self.on_data, **kwargs) self.currencies = {} # type: Dict[str, str]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._accounts = {k: new_account(k) for k in self.KEYS} self.update_accounts(list(self._accounts.values())) self.conn_factory = self.create_connection self.currencies = {} # type: Dict[str, str] self.positions = {}
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.account = new_account(self.name) self.update_accounts([self.account]) self.streaming_positios = {} self.conn_factory = lambda *args, **kwargs: CustomConnection( *args, on_data=self.on_data, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.accounts = {k: new_account(k) for k in self.KEYS} class EventHandler(EventHandlerBase): def on_event(_self, event: dict): self.on_event(event) self.event_handler = EventHandler() self.client_factory = lambda *args, **kwargs: self.Client(*args, event_handler=self.event_handler, **kwargs) self.clients = {} # type: Dict[str, Pfxnano.Client]
def run_put_accounts(self): while not self.stopped: try: pool = Pool(PoolClient, dict(name=self.name, server_address=self.master_address)) while True: accounts = [] for service in ['click', 'nano', 'yjfx']: accounts.append(new_account(service, equity=100)) with pool.connection() as client: client.put_accounts(accounts) gevent.sleep(1.0) except Exception as e: self.logger.exception(str(e)) gevent.sleep(1.0)
def __init__(self, *args, accounts_title_re: str, accounts_rects: dict, **kwargs): super().__init__(*args, **kwargs) self.accounts_title_re = accounts_title_re self.accounts_rects = accounts_rects self.accounts_recognizer = Recognizer(name=self.name + '_accounts', in_width=16, in_height=16, n_units=100, n_out=128, filter_mode=self.filter_mode, chrome=self.chrome) self.accounts_handle = None self.account = new_account(self.name)
def capture_accounts(self): if not self.accounts_handle: self.accounts_handle = self.find_window(self.accounts_title_re) if not self.accounts_handle: return [] img = self.capture_window(self.accounts_handle) results = [] d = {} for k, rect in self.accounts_rects.items(): cropped = img.crop(rect) s = '' for x in self.split_image(cropped): s += self.accounts_recognizer.recognize(x) d[k] = float(s) account = new_account(self.name, **d) return [account]
def update_accounts(self, accounts: List[dict] = None): accounts = accounts or {} config = Config() disabled = config.disabled_services self.resize_row(len(self.services) + 1) serivce_accounts = {a['service']: a for a in accounts} equity_total = 0 pl_total = 0 amount_total = 0 positive_amount_total = 0 for row, service in enumerate(sorted(self.services)): d = serivce_accounts.get(service, new_account(service, equity=-1)) self.set_item(row, 'E', checked=d['service'] not in disabled, flags=Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) self.set_item(row, 'service', value=d['service']) self.set_item(row, 'equity', value='{:,d}'.format(int(d['equity']))) equity_total += int(d['equity']) self.set_item(row, 'pl', value='{:,d}'.format(int(d['pl']))) pl_total += int(d['pl']) self.set_item(row, 'margin_ratio', value='{:,.2f} %'.format(d.get('margin_ratio', 0))) self.set_item(row, 'available', value='{:,d}'.format(int(d.get('available', 0)))) # amount = d['positions'].get(self.instrument, 0) # self.set_item(row, 'amount', value='{:d} k'.format(int(amount / 1000))) # amount_total += int(amount) # if amount > 0: # positive_amount_total += int(amount) config.accounts.setdefault(d['service'], {}).update(d) equity_total += int(self.bank) self.set_item(len(self.services), 'equity', value='{:,d}'.format(equity_total)) self.set_item(len(self.services), 'pl', value='{:,d}'.format(pl_total)) # self.set_item(len(self.services), 'amount', # value='{:d}({:d}) k'.format(amount_total // 1000, positive_amount_total // 1000)) return
def _get_accounts_impl(self, service: str, do_refresh: bool = False): self.driver.switch_to.frame('header') html = self.get_element_html(css_selector='#marginstatusinfo') if not html: print('no header html') return {} dom = lxml.html.fromstring(html) text = re.sub('[\s]+', ' ', dom.text_content()) text = re.sub(',', '', text) m = re.search('実効レバレッジ: ([-.0-9]+)倍 取引余力: ([-.0-9]+)円 純資産: ([-.0-9]+)円 証拠金維持率: ([-.0-9]*)', text) if not m: return {} leverage = float(m.group(1)) available = float(m.group(2)) equity = float(m.group(3)) margin_rate = float(m.group(4) or 0) margin = equity - available account = new_account(service, equity=equity, margin=margin) self.driver.switch_to.default_content() self.driver.switch_to.frame('main') # refresh position if do_refresh or self.will_refresh(service): print('click') self.driver.get_element(css_selector='input.button', value='更新').click() html = self.get_element_html(css_selector='#grid2') dom = lxml.html.fromstring(html) positions = {} pl = 0 for th, dom in zip(dom.cssselect('tr th a'), dom.cssselect('tr.total')): text = th.text_content() instrument = re.sub('\s', '', text) text = dom.text_content() text = re.sub('\s+', ' ', text) text = re.sub(',', '', text) m = re.search('\((.+?)\) ([-0-9]+)', text) if m: positions[instrument] = int(m.group(1)) pl += int(m.group(2)) account.update(pl=pl, positions=positions) return account
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.account = new_account(self.name) self.prices = [] parent = self class EventHandler(EventHandlerBase): def on_event(self, event: dict): parent.on_event(event) class Client(ChromeClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.wait_connected() self.network.enable() self.register_event_handler(EventHandler()) self.client_factory = Client self.clients = {} # type: Dict[str, Client]
def on_positions(self, content: str): body = json.loads(content) self.account_info = info = body['accountInfo'] equity = float(info['equity']) margin = float(info['position_margin']) pl = equity - float(info['balance']) positions = defaultdict(int) self.position_list = body['positionList'] for position in body['positionList']: currency = position['currencyPair'] instrument = '{}/{}'.format(currency[:3], currency[-3:]) amount = float(position['positionQty']) if position['buySell'] == '2': amount = -amount positions[instrument] += amount self.account = new_account(self.name, equity=equity, pl=pl, margin=margin, positions=dict(**positions)) self.logger.info('account: {}'.format(self.account)) self.update_accounts([self.account])
def on_event(self, event: dict): try: handler = event['handler'] # type: ChromeClient data = event['data'] method = data['method'] params = data['params'] if method == 'Network.responseReceived': url = params['response']['url'] # type: str if url.startswith('https://triauto.invast.jp/TriAuto/user/api/getHomeRateMap.do'): body = handler.network.get_response_body(params['requestId']) if not body: self.prices = [] return prices = [] for k, v in json.loads(body)['rateMap'].items(): instrument = '{}/{}'.format(k[:3], k[-3:]) bid, ask = float(v['bid']), float(v['ask']) d = dict(service=self.name, instrument=instrument, bid=bid, ask=ask) prices += [d] self.prices = prices elif url.startswith('https://triauto.invast.jp/TriAuto/user/api/getContainerAccountInfo.do'): body = json.loads(handler.network.get_response_body(params['requestId'])) self.account_info = info = body['accountInfo'] equity = float(info['equity']) margin = float(info['position_margin']) pl = equity - float(info['balance']) positions = defaultdict(int) self.position_list = body['positionList'] for position in body['positionList']: currency = position['currencyPair'] instrument = '{}/{}'.format(currency[:3], currency[-3:]) amount = float(position['positionQty']) if position['buySell'] == '2': amount = -amount positions[instrument] += amount self.account = new_account(self.name, equity=equity, pl=pl, margin=margin, positions=dict(**positions)) self.logger.info('account: {}'.format(self.account)) elif 'DOM' in method: pass except Exception as e: self.logger.exception(str(e)) print(event)
def get_accounts_impl(self, do_refresh: bool = False) -> List[dict]: return [] try: URL = 'https://triauto.invast.jp/TriAuto/user/index.do' if not self.find_window(url_re=URL, frame_list=['triautocontent']): return [] text = self.get_element_text(css_selector='html') text = re.sub('[\s]+', ' ', text) text = re.sub(',', '', text) print('#', text) m = re.search(('証拠金預託額(\d+)円 有効証拠金額(\d+)円 \(([.\d]+)%\) 評価損益(\d+)円 証拠金不足額(\d+)円' ' 必要証拠金(\d+)円 発注証拠金(\d+)円 発注可能額(\d+)円'), text) if not m: print('#not found') return [] l = m.groups() account = new_account(service='try', equity=float(l[1]), pl=float(l[2]), margin=float(l[5])) return [account] finally: self.last_handle = None
def update_accounts(self, accounts: List[dict] = None): accounts = accounts or {} config = Config() disabled = config.disabled_services self.resize_row(len(self.services)) serivce_accounts = {a['service']: a for a in accounts} for row, service in enumerate(sorted(self.services)): d = serivce_accounts.get(service, new_account(service, equity=-1)) self.set_item(row, 'E', checked=d['service'] not in disabled, flags=Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) self.set_item(row, 'service', value=d['service']) self.set_item(row, 'time', value=d['time']) self.set_item(row, 'equity', value='{:.1f}'.format(d['equity'])) self.set_item(row, 'pl', value='{:.1f}'.format(d['pl'])) self.set_item(row, 'margin', value='{:.1f}'.format(d['margin'])) amount = d['positions'].get(self.instrument, 0) self.set_item(row, 'amount', value='{}'.format(amount)) config.accounts.setdefault(d['service'], {}).update(d) return
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.account = new_account(self.name) self.prices = [] self.position_list = [] class EventHandler(EventHandlerBase): def on_event(_self, event: dict): self.on_event(event) class Client(ChromeClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.wait_connected() self.network.enable() self.register_event_handler(EventHandler()) def get_account(self, url: str) -> dict: try: account = {} if url != 'https://triauto.invast.jp/TriAuto/user/index.do': return account html = self.dom.get_html(css_selector='table table') if not html: self.dom.switch_frame('#triautocontent') html = self.dom.get_html(css_selector='table table') if not html: return account dom = lxml.html.fromstring(html) text = dom.text_content() text = re.sub('\s+', ' ', text).replace(',', '') """ 証拠金預託額 1,534,876円 有効証拠金額 1,498,226円 (146.88%) 評価損益 -36,650円 証拠金不足額 0円 必要証拠金 1,020,000円 発注証拠金 0円 発注可能額 478,226円 """ map = { '証拠金預託額': 'balance', '有効証拠金額': 'equity', '評価損益': 'pl', '必要証拠金': 'margin', '発注可能額': 'available', } for word, key in map.items(): m = re.search('{}.*?([-,.0-9]+)'.format(word), text) if m: account[key] = float(m.group(1)) if 'margin' in account and 'equity' in account: if account['margin'] > 0: account['margin_ratio'] = account['equity'] / account['margin'] * 100.0 else: account['margin_ratio'] = 0.0 return account except Exception as e: self.logger.exception(str(e)) return {} self.client_factory = Client self.clients = {} # type: Dict[str, Client]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.account = new_account(self.name) self.prices = [] self.position_list = [] self.currency_map = {} parent = self class EventHandler(EventHandlerBase): def on_event(_self, event: dict): self.on_event(event) class Client(ChromeClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.wait_connected() self.network.enable() self.dom.enable() self.register_event_handler(EventHandler()) def update_currency_map(self, url: str): if parent.currency_map: return if url != 'https://gaikaex.net/servlet/lzca.pc.cfr001.servlet.CFr00101': return self.dom.switch_frame(to_default_content=True) self.dom.switch_frame('#priceboard') self.dom.switch_frame('iframe[name="CIf00301"]') html = self.dom.get_html('#priceBoard') if not html: return dom = lxml.html.fromstring(html) map = {} for tr in dom.cssselect('tbody tr'): id = tr.get('id') td_list = tr.cssselect('.currencyPair') if not td_list: continue instrument = convert_instrument(td_list[0].text_content()) map[id] = instrument parent.currency_map = map self.logger.info('#CURRENCY_MAP: {}'.format(parent.currency_map)) def get_account(self, url: str) -> dict: try: account = {} if url != 'https://gaikaex.net/servlet/lzca.pc.cfr001.servlet.CFr00101': return account self.dom.switch_frame(to_default_content=True) self.dom.switch_frame('#customerInfo_v2') html = self.dom.get_html(css_selector='#left_navi') if not html: return account dom = lxml.html.fromstring(html) text = dom.text_content() text = re.sub('\s+', ' ', text).replace(',', '') map = { '資産合計': 'balance', '評価損益': 'pl', '証拠金維持率': 'margin_ratio', } d = {} for word, key in map.items(): m = re.search('{}.*?([-,.0-9]+)'.format(word), text) if m: try: account[key] = d[key] = float(m.group(1)) except ValueError: pass account['equity'] = account['balance'] + account['pl'] if 'margin_ratio' in d: account['margin'] = account['equity'] / (d['margin_ratio'] / 100) else: account['margin'] = account['equity'] account['available'] = account['equity'] - account['margin'] return account except Exception as e: self.logger.exception(str(e)) return {} self.client_factory = Client self.clients = {} # type: Dict[str, Client]