Ejemplo n.º 1
0
def realinfo(realtypes):
    from koapy import KiwoomOpenApiPlusRealType

    def get_realtypes():
        if realtypes:
            if '-' in realtypes:
                with click.open_file('-', 'r') as f:
                    for realtype in f:
                        yield realtype.strip()
            else:
                for realtype in realtypes:
                    yield realtype
        else:
            while True:
                try:
                    realtype = click.prompt('realtype', prompt_suffix=' >>> ')
                    realtype = realtype.strip()
                    if realtype == 'exit':
                        break
                    if realtype:
                        yield realtype
                except EOFError:
                    break

    for realtype in get_realtypes():
        fids = KiwoomOpenApiPlusRealType.get_fids_by_realtype(realtype)
        if fids:
            names = [KiwoomOpenApiPlusRealType.Fid.get_name_by_fid(fid, str(fid)) for fid in fids]
            for fid, name in zip(fids, names):
                click.echo('  [%s] = %s' % (fid, name))
        else:
            click.echo('Given realtype is invalid')
Ejemplo n.º 2
0
Archivo: cli.py Proyecto: LKH-1/koapy
def realinfo(realtypes):
    from koapy import KiwoomOpenApiPlusRealType

    def get_realtypes():
        if realtypes:
            if "-" in realtypes:
                with click.open_file("-", "r") as f:
                    for realtype in f:
                        yield realtype.strip()
            else:
                for realtype in realtypes:
                    yield realtype
        else:
            while True:
                try:
                    realtype = click.prompt("realtype", prompt_suffix=" >>> ")
                    realtype = realtype.strip()
                    if realtype == "exit":
                        break
                    if realtype:
                        yield realtype
                except EOFError:
                    break

    for realtype in get_realtypes():
        fids = KiwoomOpenApiPlusRealType.get_fids_by_realtype_name(realtype)
        if fids:
            names = [
                KiwoomOpenApiPlusRealType.Fid.get_name_by_fid(fid, str(fid))
                for fid in fids
            ]
            for fid, name in zip(fids, names):
                click.echo("  [%s] = %s" % (fid, name))
        else:
            click.echo("Given realtype is invalid")
Ejemplo n.º 3
0
            request_name,
            screen_no,
            account_no,
            order_type,
            code,
            quantity,
            price,
            quote_type,
            original_order_no,
    ):
        pprint_event(event)
else:
    logging.info("Cannot send an order while market is not open, skipping...")

code_list = [code]
fid_list = KiwoomOpenApiPlusRealType.get_fids_by_realtype_name("주식시세")
real_type = "0"  # 기존 화면에 추가가 아니라 신규 생성

# 현재는 기본적으로 실시간 이벤트를 무한정 가져옴 (커넥션 컨트롤 가능한 예시)
logging.info("Starting to get realtime stock data for code: %s", code)
stream = entrypoint.GetRealDataForCodesAsStream(
    code_list,
    fid_list,
    real_type,
    screen_no=None,
    infer_fids=True,
    readable_names=True,
    fast_parse=False,
)

Ejemplo n.º 4
0
def realdata(verbose):
    set_verbosity(verbose)
    from koapy import KiwoomOpenApiPlusRealType
    KiwoomOpenApiPlusRealType.dump_realtype_by_desc()
Ejemplo n.º 5
0
def watch(codes, input, fids, realtype, output, format, port, verbose):
    if (codes, fids, realtype) == (tuple(), tuple(), None):
        fail_with_usage()

    set_verbosity(verbose)

    codes_len = len(codes)

    if codes_len == 0:
        if input is None:
            fail_with_usage('Either code or input should be given.')
        if not os.path.exists(input):
            fail_with_usage('Given input does not exist.')

        if os.path.isfile(input):
            if input.endswith('.xlsx'):
                import pandas as pd
                df = pd.read_excel(input, dtype=str)
                code_column = '종목코드'
                if code_column in df:
                    codes = df[code_column]
                else:
                    codes = df.iloc[0]
                codes_len = len(codes)
            elif input.endswith('.txt'):
                with open(input) as f:
                    codes = [line.strip() for line in f]
                codes_len = len(codes)
            else:
                fail_with_usage('Unrecognized input type.')
        else:
            fail_with_usage('Unrecognized input type.')

    if realtype is not None:
        from koapy import KiwoomOpenApiPlusRealType
        fids_from_realtype = KiwoomOpenApiPlusRealType.get_fids_by_realtype(realtype)
        fids = list(set(fids).union(set(fids_from_realtype)))

    if not codes:
        fail_with_usage('No codes to watch. Set --code or --input.')

    if not fids:
        fail_with_usage('Cannot infer fids to watch. Set either --fid or --realtype.')

    import datetime
    import pandas as pd

    from koapy import KiwoomOpenApiPlusEntrypoint
    from koapy import KiwoomOpenApiPlusRealType

    def parse_message(message):
        fids = event.single_data.names
        names = [KiwoomOpenApiPlusRealType.Fid.get_name_by_fid(fid, str(fid)) for fid in fids]
        values = event.single_data.values
        dic = dict((name, value) for fid, name, value in zip(fids, names, values) if name != fid)
        series = pd.Series(dic)
        return series

    if format == 'json':
        def print_message(message):
            click.echo(parse_message(message).to_json(), file=output)
    else:
        def print_message(message):
            code = event.arguments[0].string_value
            name = event.arguments[1].string_value
            click.echo('[%s] [%s]' % (code, name), file=output)
            click.echo('[%s]' % datetime.datetime.now(), file=output)
            click.echo(parse_message(message).to_markdown(), file=output)

    with KiwoomOpenApiPlusEntrypoint(port=port, client_check_timeout=client_check_timeout, verbosity=verbose) as context:
        context.EnsureConnected()

        for event in context.GetRealDataForCodesAsStream(codes, fids, infer_fids=True):
            print_message(event)
Ejemplo n.º 6
0
    # 현재는 기본적으로 주문수량이 모두 소진되기 전까지 이벤트를 듣도록 되어있음 (단순 호출 예시)
    if is_currently_in_session():
        logging.info(
            'Sending order to buy %s, quantity of 1 stock, at market price...',
            code)
        for event in context.OrderCall(request_name, screen_no, account_no,
                                       order_type, code, quantity, price,
                                       quote_type, original_order_no):
            pp.pprint(MessageToDict(event))
    else:
        logging.info(
            'Cannot send an order while market is not open, skipping...')

    # 실시간 예시
    code_list = [code]
    fid_list = KiwoomOpenApiPlusRealType.get_fids_by_realtype('주식시세')
    real_type = '0'  # 기존 화면에 추가가 아니라 신규 생성

    # 현재는 기본적으로 실시간 이벤트를 무한정 가져옴 (커넥션 컨트롤 가능한 예시)
    logging.info('Starting to get realtime stock data for code: %s', code)
    stream = context.GetRealDataForCodesAsStream(code_list,
                                                 fid_list,
                                                 real_type,
                                                 screen_no=None,
                                                 infer_fids=True,
                                                 readable_names=True,
                                                 fast_parse=False)

    def stop_listening():
        logging.info('Stopping to listen events...')
        stream.cancel()