Esempio n. 1
0
 def parse_prices(self, content: str) -> dict:
     # rate
     """
     ,
     20
     USDJPY,112.643,112.646,112.485,112.885,112.405,0.100,112.543,,0
     EURJPY,118.840,118.846,118.671,118.890,118.506,0.108,118.732,,0
     """
     if not content:
         return {}
     prices = {}
     now = jst_now_aware()
     for row in csv.reader(StringIO(content)):
         if len(row) < 3:
             continue
         instrument = row[0][:3] + '/' + row[0][-3:]
         bid = float(row[1])
         ask = float(row[2])
         price = Price(self.NAME,
                       instrument=instrument,
                       time=now,
                       bid=bid,
                       ask=ask)
         prices.setdefault(self.NAME, {})[instrument] = price
     return dict(prices=prices)
Esempio n. 2
0
    def handle_websocket_message(self, flow: WebSocketFlow):
        content = None
        try:
            addr = '{}{}'.format(flow.server_conn.address, flow.handshake_flow.request.path)
            if not addr.startswith(self.WS_RATE_URL):
                return
            content = flow.messages[-1].content  # type: bytes
            if not content:
                return
            message = json.loads(content.decode('utf-8'))
            if 'event' not in message and message['event'] != 'QUOTE':
                return
            data = message['data']
            prices = {}
            now = jst_now_aware()
            for quote in data:
                code = quote[1]
                if code not in self.INSTRUMENT_CODES:
                    continue
                instrument = self.INSTRUMENT_CODES[code]
                ask = float(quote[4])
                bid = float(quote[5])
                price = Price(self.NAME, instrument=instrument, time=now, bid=bid, ask=ask)
                prices.setdefault(self.NAME, {})[instrument] = price

            self.push_data(accounts=self.accounts, prices=prices)
        except Exception as e:
            self.exception(str(e) + 'message={}'.format(content))
Esempio n. 3
0
        def update_price(self, x_price: Price, y_price: Price,
                         close_flag: bool) -> Optional[dict]:
            params = self.config[self.instrument]
            try:
                if close_flag:
                    check_spread = params['close_spread']
                    check_period = params['close_period']
                else:
                    check_spread = params['open_spread']
                    check_period = params['open_period']
            except KeyError:
                if not self.NO_SIGNAL_CONFIG_WARNINGS.get(self.instrument):
                    self.NO_SIGNAL_CONFIG_WARNINGS[self.instrument] = True
                    logging.warning('instrument={} no signal config'.format(
                        self.instrument))
                return None

            sp = (x_price.bid - y_price.ask) * get_pip_scale(self.instrument)
            if check_spread > sp:
                self.sp_history.clear()
                return None
            price_time = max(x_price.time, y_price.time)
            now = jst_now_aware()
            if now - price_time >= timedelta(seconds=5):
                self.sp_history.clear()
                return None

            if len(self.sp_history) > 0:
                if self.sp_history[-1]['time'] >= price_time:
                    return None
            self.sp_history.append({
                'time': price_time,
                'sp': sp,
            })
            period = self.sp_history[-1]['time'] - self.sp_history[0]['time']
            if period.total_seconds() >= check_period:
                if time.time() - self.signaled_at >= 10:
                    self.signaled_at = time.time()
                    self.sp_history.clear()
                    return {
                        'time':
                        price_time.astimezone(JST).strftime(
                            '%Y%m%d %H:%M:%S JST'),
                        'instrument':
                        self.instrument,
                        'bidder':
                        x_price.name,
                        'bid':
                        format_price(self.instrument, x_price.bid),
                        'asker':
                        y_price.name,
                        'ask':
                        format_price(self.instrument, y_price.ask),
                        'sp':
                        format_sp(-sp),
                    }
            return None
Esempio n. 4
0
 def save(self):
     os.makedirs(self.dir_path, exist_ok=True)
     now = jst_now_aware()
     self.char.save(os.path.join(self.dir_path, self.CHAR_FILE))
     self.char.save(
         os.path.join(
             self.dir_path, '{}.{}'.format(self.CHAR_FILE,
                                           now.strftime('%Y%m%dT%H%M%S'))))
     self.width.save(os.path.join(self.dir_path, self.WIDTH_FILE))
     self.width.save(
         os.path.join(
             self.dir_path, '{}.{}'.format(self.WIDTH_FILE,
                                           now.strftime('%Y%m%dT%H%M%S'))))
Esempio n. 5
0
 def parse_prices(self, content: str):
     prices = {}
     now = jst_now_aware()
     for k, v in json.loads(content)['rateMap'].items():
         instrument = '{}/{}'.format(k[:3], k[-3:])
         bid, ask = float(v['bid']), float(v['ask'])
         price = Price(self.NAME,
                       instrument=instrument,
                       time=now,
                       bid=bid,
                       ask=ask)
         prices.setdefault(self.NAME, {})[instrument] = price
     return dict(prices=prices)
Esempio n. 6
0
 def update_data(self):
     prices = {}
     now = jst_now_aware()
     for name, instrument_v in copy.deepcopy(self.prices).items():
         for instrument, price in instrument_v.items():
             if price.time >= now - timedelta(seconds=10):
                 prices.setdefault(name, {})[instrument] = price
     data = {
         'accounts': copy.deepcopy(self.accounts),
         'prices': prices,
     }
     self.account_ui.on_data(data)
     for price_table in self.price_ui_list:
         price_table.on_data(data)
     self.signals.on_data(data)
Esempio n. 7
0
 def parse_prices(self, content: str) -> dict:
     """
     var priceList = {"timestamp":"1492609861707","requestId":"1492609827340",
         "priceList":[
             {"timestamp":"2017/04/19 22:51:00",
              "suspend":"false","change":"0.589","high":"109.082","convRate":"1","low":"108.385",
                 "ask":{"price":"109.053","fractionPips":1,"priceId":"303064890002331733A",
                        "head":"109","tail":"053","dealable":true},
                 "currencyPair":"USD/JPY","bid":{"price":"109.050","fractionPips":1,"priceId":"303064890002331733B",
                                                 "head":"109","tail":"050","dealable":true
                 }
             },
             {"timestamp":"2017/04/19 22:51:00",
              "suspend":"false","change":"0.433","high":"116.972","convRate":"1","low":"116.278"
             ,"ask":{"price":"116.827","fractionPips":1,"priceId":"303064920001696275A",
                     "head":"116","tail":"827","dealable":true},
             "currencyPair":"EUR/JPY","bid":{"price":"116.821","fractionPips":1,"priceId":"303064920001696275B",
                     "head":"116","tail":"821","dealable":true}},
                     ...
         ]};if (window.top.pullBsController) window.top.pullBsController.fire(priceList);
     """
     try:
         if not content:
             return {}
         m = re.search('var priceList = (.*?);', content)
         if not m:
             print('not m')
             return {}
         prices = {}
         now = jst_now_aware()
         data = json.loads(m.group(1))
         for price_info in data.get('priceList', []):
             instrument = price_info['currencyPair']
             ask = float(price_info['ask']['price'])
             bid = float(price_info['bid']['price'])
             price = Price(self.NAME,
                           instrument=instrument,
                           time=now,
                           bid=bid,
                           ask=ask)
             prices.setdefault(self.NAME, {})[instrument] = price
         return dict(prices=prices)
     except Exception as e:
         self.error(content and content[:100])
         self.exception(str(e))
     return {}
Esempio n. 8
0
def main():
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s|%(name)s|%(levelname)s| %(message)s')
    args = docopt("""
    Usage:
      {f}
      {f} [options] capture TITLE DIR
      {f} [options] make_data NAME DIR
      {f} [options] train DIR
      
    Options:
      --epoch EPOCH  [default: 10]
      --capture-interval SEC  [default: 5]
    """.format(f=sys.argv[0]))

    name = args['NAME']
    title = args['TITLE']
    dir_name = args['DIR']
    os.makedirs(dir_name, exist_ok=True)
    os.chdir(dir_name)
    if args['capture']:
        windows = tuple(
            filter(lambda x: re.search(title, x.get_title()),
                   Window.iter_window()))
        while True:
            for window in windows:
                window.get_screen_shot().save('{}.png'.format(
                    jst_now_aware().strftime('%Y%m%dT%H%M%S')))
                sleep(float(args['--capture-interval']))
    if args['make_data']:
        recognizer = CharRecognizer('.')
        recognizer.make_train_data(name)
    if args['train']:
        epoch = int(args['--epoch'])
        recognizer = CharRecognizer('.')
        recognizer.train(epoch)
        recognizer.save()

    for w in Window.iter_window():
        print(w.get_title())

    return