kiwoompy

실시간 현재가 수신

WebSocket으로 주식 체결 데이터를 실시간으로 수신하는 예제입니다.

단일 종목 현재가 출력

import asyncio
from kiwoompy import KiwoomClient
from kiwoompy.realtime import KiwoomRealtime
from kiwoompy.models import RealtimeEvent

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

async def on_trade(event: RealtimeEvent) -> None:
    price = event.values.get("10", "")
    change = event.values.get("11", "")
    rate = event.values.get("12", "")
    volume = event.values.get("15", "")
    print(f"[{event.item}] 현재가: {price}원  전일대비: {change}  등락률: {rate}%  체결량: {volume}주")

async def main():
    async with KiwoomRealtime(client.api, env="demo") as rt:
        await rt.subscribe("0B", items=["005930"], callback=on_trade)
        await asyncio.sleep(60)

asyncio.run(main())

여러 종목 동시 수신

import asyncio
from kiwoompy import KiwoomClient
from kiwoompy.realtime import KiwoomRealtime
from kiwoompy.models import RealtimeEvent

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

WATCHLIST = ["005930", "000660", "035720", "005380", "051910"]

async def on_trade(event: RealtimeEvent) -> None:
    v = event.values
    print(
        f"{event.item:>8}  "
        f"현재가: {v.get('10', ''):>8}원  "
        f"등락률: {v.get('12', ''):>6}%  "
        f"거래량: {v.get('13', ''):>12}주"
    )

async def main():
    async with KiwoomRealtime(client.api, env="demo") as rt:
        await rt.subscribe("0B", items=WATCHLIST, callback=on_trade)
        print(f"{len(WATCHLIST)}개 종목 실시간 수신 시작")
        await asyncio.sleep(300)

asyncio.run(main())

체결 + 호가 동시 수신

import asyncio
from kiwoompy import KiwoomClient
from kiwoompy.realtime import KiwoomRealtime
from kiwoompy.models import RealtimeEvent

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

async def on_trade(event: RealtimeEvent) -> None:
    v = event.values
    print(f"[체결] {event.item}: {v.get('10')}원  체결량: {v.get('15')}주")

async def on_orderbook(event: RealtimeEvent) -> None:
    v = event.values
    # 매도 1~5호가
    asks = [v.get(f"4{i+1}", "") for i in range(5)]
    # 매수 1~5호가
    bids = [v.get(f"5{i+1}", "") for i in range(5)]
    print(f"[호가] {event.item}  매도1: {asks[0]}  매수1: {bids[0]}")

async def main():
    async with KiwoomRealtime(client.api, env="demo") as rt:
        await rt.subscribe("0B", items=["005930"], callback=on_trade)
        await rt.subscribe("0D", items=["005930"], callback=on_orderbook)
        await asyncio.sleep(60)

asyncio.run(main())

내 주문 체결 알림

주문 접수·체결·취소 이벤트를 실시간으로 수신합니다.

import asyncio
from kiwoompy import KiwoomClient
from kiwoompy.realtime import KiwoomRealtime
from kiwoompy.models import RealtimeEvent

client = KiwoomClient(env="demo", appkey="...", secretkey="...")

async def on_my_order(event: RealtimeEvent) -> None:
    v = event.values
    status = v.get("913", "")    # 주문상태: 접수/체결/취소/거부
    name = v.get("302", "")      # 종목명
    order_no = v.get("9203", "") # 주문번호
    side = v.get("905", "")      # 주문구분: 매수/매도
    qty = v.get("900", "")       # 주문수량
    filled_qty = v.get("911", "") # 체결량
    filled_price = v.get("910", "") # 체결가

    print(f"[{status}] {name} ({side}) — 주문번호: {order_no}")
    if status == "체결":
        print(f"  체결가: {filled_price}원 / 체결량: {filled_qty}주")

async def main():
    async with KiwoomRealtime(client.api, env="demo") as rt:
        # 계좌 기반 구독 — items에 빈 문자열 전달
        await rt.subscribe("00", items=[""], callback=on_my_order)
        print("주문체결 알림 수신 대기 중...")
        await asyncio.sleep(3600)  # 1시간

asyncio.run(main())

실행 예시

005930  현재가:   71,500원  등락률:  +1.42%  거래량:  12,345,678주
000660  현재가:  185,000원  등락률:  -0.54%  거래량:   3,456,789주
005930  현재가:   71,600원  등락률:  +1.56%  거래량:  12,346,100주

관련 가이드