示例#1
0
    def get_realtime_stock_data(self, args):
        def _data_notify(resp):
            # close = resp['close'][0]
            # volume = float(resp['volume'][0])
            pass

        def _handle_K_1M_data(resp):
            if self.low == 9999999 or self.high == 0:
                return

            close = resp['close'][0]
            volume = float(resp['volume'][0])
            tz = timezone('EST')
            cur_datetime = datetime.datetime.now(tz)
            self.rt_data.append((time.time(), float('%.3f' % close), float('%.3f' % volume)))
            rt_data_p = list(map(lambda x: x[1], self.rt_data))
            rt_data_v = list(map(lambda x: x[2], self.rt_data))
            prev_percent = (close / rt_data_p[-2] - 1) * 100 if len(self.rt_data) > 1 else 0
            cur_time = cur_datetime.strftime('%H:%M:%S')
            move_avg = sum(rt_data_p[-50:]) / min(50, len(rt_data_p)) if rt_data_p else 0
            move_avg_volume = sum(rt_data_v[-50:]) / min(50, len(rt_data_v)) if rt_data_v else 0
            print('\n%s min:%.3f(+%.4f%%), max:%f(-%.4f%%), open:%.3f(%s%.4f%%), '
                  'today:(%s%.4f%%), cur:%.3f\nmove_avg:%.3f(%s%.4f%%), prev:(%s%.4f%%), volume:%.3f(%s%.4f%%)' % (
                      cur_time,
                      self.low, (close / self.low - 1) * 100,
                      self.high, (self.high / close - 1) * 100,
                      self.open,
                      '+' if close > self.open != -1 else '',
                      (close / self.open - 1) * 100 if self.open != -1 else 0,
                      '+' if close > self.yesterday_close != -1 else '',
                      (close / self.yesterday_close - 1) * 100 if self.yesterday_close != -1 else 0,
                      move_avg,
                      close, '+' if close > move_avg > 0 else '',
                      (close / move_avg - 1) * 100 if move_avg > 0 else 0,
                      '+' if prev_percent > 0 else '', prev_percent,
                      volume, '+' if volume > move_avg_volume > 0 else '',
                      (volume / move_avg_volume - 1) * 100
                  ))
            _data_notify(resp)

        def _handle_K_DAY_data(resp):
            self.high = max(self.high, list(resp['high'])[-1])
            self.low = min(self.low, list(resp['low'])[-1])
            self.open = list(resp['open'])[-1]
            self.close = list(resp['close'])[-1]

        def _handle_data(resp):
            k_type = resp['k_type'][0]
            if k_type == 'K_1M':
                _handle_K_1M_data(resp)
            elif k_type == 'K_DAY':
                _handle_K_DAY_data(resp)

        api.subscribe(args.stocks, args.ktype, True)
        api.subscribe(args.stocks, 'K_DAY', True)
        cur_data = api.get_cur_kline(args.stocks, 2)
        self.yesterday_close = cur_data[1]['close'][0]
        api.get_cur_kline(args.stocks, 1, ktype=args.ktype, async_handler=_handle_data)
        api.get_cur_kline(args.stocks, 2, ktype='K_DAY', async_handler=_handle_data)
        api.start()
示例#2
0
def sync_futu_premarket():
    import futu_api as api

    cur_date = datetime.datetime.now(
        timezone('America/New_York')).strftime("%Y-%m-%d %H:%M:%S").split()[0]

    with open('stock_sync_codes.txt') as f:
        symbols = list(map(lambda x: x.strip(), f.readlines()))

    loggers = {
        symbol:
        setup_logger('%s_order_book' % symbol,
                     'order_book/%s_%s_order_book.log' % (symbol, cur_date))
        for symbol in symbols
    }

    def _handle_order_book(param):
        current_dt = datetime.datetime.now(timezone('America/New_York'))
        time = current_dt.strftime("%Y-%m-%d %H:%M:%S")
        loggers[param['stock_code']].info(
            '%s~%s~%s' % (str(time), param['Ask'][0], param['Bid'][0]))

    for code in symbols:
        api.subscribe(code, 'ORDER_BOOK', True)
        api.get_order_book(code, _handle_order_book)
    api.start()
示例#3
0
def sync_rt_data():
    import futu_api as api

    cur_date = datetime.datetime.now(
        timezone('America/New_York')).strftime("%Y-%m-%d %H:%M:%S").split()[0]

    with open('stock_sync_codes.txt') as f:
        symbols = list(map(lambda x: x.strip(), f.readlines()))

    loggers = {
        symbol: setup_logger('%s_rt_data' % symbol,
                             'rt_data/%s_%s_rt_data.log' % (symbol, cur_date))
        for symbol in symbols
    }

    def _handle_rt_data(param):
        currentDT = datetime.datetime.now(timezone('America/New_York'))
        time = currentDT.strftime("%Y-%m-%d %H:%M:%S")
        symbol = param.values[0][0]
        dt = param.values[0][1]
        status = param.values[0][2]
        cur_price = param.values[0][4]
        last_close = param.values[0][5]
        avg_price = param.values[0][6]
        turn_over = param.values[0][7]
        volume = param.values[0][8]
        loggers[symbol].info(
            '%s~%s~%s~%s~%s~%s' %
            (time, cur_price, last_close, avg_price, turn_over, volume))

    for code in symbols:
        api.subscribe(code, 'RT_DATA', True)
        api.get_rt_data(code, _handle_rt_data)
    api.start()
示例#4
0
def stream():
    code = request.args.get('code')
    ktype = request.args.get('ktype')
    api.subscribe(code, ktype, True)
    api.get_cur_kline(code,
                      1000,
                      ktype=ktype,
                      async_handler=get_cur_kline_handler)
    api.start()
    return Response(get_cur_kline_stream(), mimetype="text/event-stream")
示例#5
0
def azero():
    # quote_ctx = OpenQuoteContext(host='10.140.0.5', port=11111)
    # quote_ctx.subscribe('US.IQ', 'K_1M')
    # quote_ctx.subscribe('US.IQ', 'TICKER')
    # print(quote_ctx.get('US.IQ', 500))
    def _handler(param):
        param = param.values[0]
        if 'TT_BUY' == param[5]:
            Mine.BUY += [(param[1], param[2], int(param[3]), param[4])]
        elif 'TT_SELL' == param[5]:
            Mine.SELL += [(param[1], param[2], int(param[3]), param[4])]
        buy_total = sum(map(lambda x: x[3], Mine.BUY))
        sell_total = sum(map(lambda x: x[3], Mine.SELL))
        tip = ""
        if buy_total > sell_total:
            tip = '<*>(%.2fx)' % ((
                (buy_total / sell_total) if sell_total != 0 else 1) - 1)
        else:
            tip = '<*>(%.2fx)' % ((
                (sell_total / buy_total) if buy_total != 0 else 1) - 1)
        print(
            ((tip if buy_total > sell_total else '') +
             'BUY[%s] %f %d total: (%d)-----SELL[%s] %f %d total: (%d)' +
             (tip if sell_total >= buy_total else '')) %
            (Mine.BUY[-1][0], Mine.BUY[-1][1], Mine.BUY[-1][2], buy_total,
             Mine.SELL[-1][0], Mine.SELL[-1][1], Mine.SELL[-1][2], sell_total))

    def _handle_rt(param):
        param = param.values[0]
        print(param)

    code = 'US.IQ'
    print(api.subscribe(code, 'K_1M', True))
    # print(api.subscribe('US.IQ', 'ORDER_BOOK', True))
    # print(api.subscribe('US.IQ', 'BROKER', True))
    print(api.subscribe(code, 'TICKER', True))
    print(api.subscribe(code, 'RT_DATA', True))
    # print(api.subscribe('US.IQ', 'QUOTE', True))
    # print(api.get_cur_kline('US.IQ', 1000, ktype='K_1M'))
    # print(api.get_broker_queue('US.IQ', async_handler=_handler))
    # print(api.get_order_book('US.IQ', async_handler=_handler))
    print(api.get_rt_ticker(code, num=1000, async_handler=_handler))
    print(api.get_rt_data(code, async_handler=_handle_rt))
    # print(api.get_stock_quote(['US.IQ'], async_handler=_handler))
    api.start()