Metadata-Version: 2.5
Name: kiwoom-client
Version: 0.5.0
Summary: 키움증권 REST API 파이썬 클라이언트 — 엔드포인트 182개·실시간 WebSocket·sync/async·AI 에이전트용 MCP 서버 (비공식) | Unofficial Python client for the Kiwoom Securities REST API with a built-in MCP server
Project-URL: Homepage, https://github.com/younghwan91/kiwoom-client
Project-URL: Repository, https://github.com/younghwan91/kiwoom-client
Project-URL: Documentation, https://younghwan91.github.io/kiwoom-client/
Project-URL: Issues, https://github.com/younghwan91/kiwoom-client/issues
Project-URL: Changelog, https://github.com/younghwan91/kiwoom-client/blob/main/CHANGELOG.md
Author-email: Younghwan Chae <chyohw97@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,algorithmic-trading,async,asyncio,claude-code,cursor,investment,kiwoom,kiwoom-api,kiwoom-rest-api,kiwoom-securities,korea-finance,kosdaq,kospi,krx,llm,mcp,mcp-server,model-context-protocol,openapi,pandas,quant,rest-api,stock,trading,trading-bot,websocket,자동매매,자동주문,주식,증권,퀀트,키움,키움 REST API,키움증권
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27.0
Requires-Dist: websockets>=13.0
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pandas>=2.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.34.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-awesome-nav>=3.0; extra == 'docs'
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Requires-Dist: mkdocs-static-i18n>=1.2; extra == 'docs'
Requires-Dist: mkdocs<2,>=1.6; extra == 'docs'
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.0; extra == 'mcp'
Provides-Extra: pandas
Requires-Dist: pandas>=2.0; extra == 'pandas'
Description-Content-Type: text/markdown

[한국어](https://github.com/younghwan91/kiwoom-client/blob/main/README.md) | [English](https://github.com/younghwan91/kiwoom-client/blob/main/README_EN.md)

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/brand/wordmark-dark.svg">
  <img alt="kiwoom-client" src="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/brand/wordmark-light.svg" height="56">
</picture>

# kiwoom-client — 키움증권 REST API 파이썬 클라이언트

**키움 REST API, 파이썬과 AI 에이전트로.** 182개 엔드포인트, 실시간 WebSocket, 그리고 MCP 서버로 AI 에이전트까지 — COM/OCX 없이 Windows · macOS · Linux 어디서나 돌아갑니다. 키움증권과 무관한 비공식 오픈소스입니다.

[![PyPI version](https://img.shields.io/pypi/v/kiwoom-client)](https://pypi.org/project/kiwoom-client/)
[![Python](https://img.shields.io/pypi/pyversions/kiwoom-client)](https://pypi.org/project/kiwoom-client/)
[![Downloads](https://img.shields.io/pypi/dm/kiwoom-client)](https://pypi.org/project/kiwoom-client/)
[![CI](https://github.com/younghwan91/kiwoom-client/actions/workflows/ci.yml/badge.svg)](https://github.com/younghwan91/kiwoom-client/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/github/license/younghwan91/kiwoom-client)](https://github.com/younghwan91/kiwoom-client/blob/main/LICENSE)
[![Docs](https://img.shields.io/badge/docs-%EB%AC%B8%EC%84%9C%20%EC%82%AC%EC%9D%B4%ED%8A%B8-blue)](https://younghwan91.github.io/kiwoom-client/)

- **REST 182개 + 조건검색 4종 + 실시간 19종**을 모듈 15개로 감쌌습니다. 아래 그림은 코드에서 센 것이라 타일 하나가 엔드포인트 하나입니다.
- **MCP 서버 내장** — Claude Code · Cursor 가 `stock_info_basic_stock_info` 같은 도구로 시세·계좌·주문을 직접 부릅니다. 실전 계좌에서는 `KIWOOM_MCP_ALLOW_LIVE_ORDERS=true` 를 켜기 전까지 주문 도구가 **등록조차 되지 않습니다**.
- **봇이 토큰 만료로 죽지 않습니다** — 만료 전 자동 갱신, 401 이면 재발급 후 재시도. TR별 Rate Limiter 가 429 를 막고, 그래도 나오면 백오프 후 다시 보냅니다.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/hero-dark.png">
  <img alt="kiwoom-client 가 감싼 키움 REST 엔드포인트 182개와 WebSocket 호출 23개를 도메인별 타일로 그린 모자이크" src="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/hero-light.png" width="100%">
</picture>

## 빠른 시작

```bash
pip install kiwoom-client
```

```python
from kiwoom_client import KiwoomAPI

api = KiwoomAPI.from_env(is_mock=True)  # KIWOOM_APP_KEY·KIWOOM_APP_SECRET 환경변수 (.env 는 from_env(".env"))
# 또는 직접: KiwoomAPI(app_key="발급받은_앱키", app_secret="발급받은_시크릿키", is_mock=True)

info = api.stock_info.basic_stock_info(stk_cd=api.stock_code("삼성전자"))  # 종목명 → 005930
chart = api.chart.stock_daily_chart(stk_cd="005930", base_dt="20260326", upd_stkpc_tp="1")  # 일봉
print(info["stk_nm"])
```

접근토큰은 첫 호출에서 자동 발급되고 만료 전에 갱신되므로 따로 할 일이 없습니다. 앱키·시크릿키는
[키움 REST API 포털](https://openapi.kiwoom.com)에서 발급받고, 처음에는 모의투자(`is_mock=True`)로 시작하세요.

### AI 에이전트에서 (MCP)

```bash
pip install 'kiwoom-client[mcp]'
claude mcp add --transport stdio \
  --env KIWOOM_APP_KEY=발급받은_앱키 --env KIWOOM_APP_SECRET=발급받은_시크릿키 --env KIWOOM_IS_MOCK=true \
  kiwoom-client -- kiwoom-client-mcp
```

이제 Claude Code 에서 "삼성전자 지금 얼마야?" 라고 물으면 됩니다. Cursor 등 다른 클라이언트 설정과 환경변수는 [MCP 서버로 사용하기](#mcp-서버로-사용하기).

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/demo-mcp-ko-dark.png">
  <img alt="예시 화면: MCP 클라이언트가 stock_info_basic_stock_info 도구로 삼성전자 시세를 조회하고, 실전투자 서버에서 매수를 요청하자 주문 도구가 등록돼 있지 않아 거절하는 대화" src="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/demo-mcp-ko-light.png" width="100%">
</picture>

<sub>실서버를 호출하지 않고 만든 예시 화면입니다(시세 값은 가상). 실전투자 서버에서는 `KIWOOM_MCP_ALLOW_LIVE_ORDERS=true` 를 켜기 전까지 주문 도구가 등록되지 않아, 에이전트가 주문할 방법 자체가 없습니다.</sub>

더 읽을거리: [왜 kiwoom-client 인가 — OpenAPI+·pykiwoom·다른 REST 래퍼와 비교](https://younghwan91.github.io/kiwoom-client/why/) · [엔드포인트 전체 목록](https://younghwan91.github.io/kiwoom-client/endpoints/)

## 무엇을 하나

- **크로스 플랫폼**: REST 기반이라 Windows · macOS · Linux, 헤드리스 서버에서도 돌아갑니다.
- **sync / async 양쪽**: `KiwoomAPI` 와 `AsyncKiwoomAPI` 가 같은 엔드포인트를 제공합니다.
- **자동 토큰 관리**: 발급·만료 전 갱신·401 재발급을 라이브러리가 맡습니다.
- **내장 Rate Limiter**: TR(api_id)별 토큰 버킷(1 req/s, 버스트 2) + 429 자동 재시도.
- **자동 페이지네이션**: `request_all()` 이 `cont-yn`/`next-key` 를 끝까지 따라갑니다.
- **바로 쓰는 응답**: `to_dataframe()` 이 `"+70000"` 같은 문자열을 숫자로 바꿔 DataFrame 으로 넘깁니다.
- **호가단위 보정**: `round_to_tick()` 으로 지정가를 KRX 호가단위에 맞춥니다.
- **실시간 WebSocket**: 체결·호가·잔고 등 19종 구독, PING 응답·재연결·구독 복원 내장. 조건검색도 같은 소켓.
- **MCP 서버**: 모듈 15개의 REST 엔드포인트 전부와 조건검색 4종이 MCP 도구로 노출됩니다.

### 기존 키움 OpenAPI / pykiwoom 과 무엇이 다른가?

키움 **OpenAPI+(OCX/COM)** 와 이를 감싼 `pykiwoom` 은 32bit Windows 에 묶여 있어 서버 배포·자동화가 어렵습니다.
이 라이브러리는 키움의 **신규 REST API** 를 쓰므로 그 제약이 없습니다.

| 항목 | 키움 OpenAPI+ (OCX) | pykiwoom | **kiwoom-client** |
|------|---------------------|----------|---------------------|
| 연동 방식 | COM/OCX | OCX 래퍼 | **REST + WebSocket** |
| 운영체제 | Windows 전용 | Windows 전용 | **Windows · macOS · Linux** |
| Python 비트수 | 32bit 전용 | 32bit 전용 | **64bit 지원** |
| 서버/헤드리스 배포 | 어려움 (GUI 필요) | 어려움 | **가능** |
| 실시간 데이터 | 이벤트 콜백 | 이벤트 콜백 | **async WebSocket** |
| 설치 | 별도 모듈 설치 | OCX + 모듈 | **`pip install` 한 줄** |

키움 공식 저장소·다른 REST 래퍼까지 넣은 비교는 [왜 kiwoom-client 인가](https://younghwan91.github.io/kiwoom-client/why/), OpenAPI+ TR·함수를 REST 로 옮기는 대응표는 [옮겨 오기](https://younghwan91.github.io/kiwoom-client/migration-from-openapi-plus/).

## 설치와 사전 준비

```bash
pip install kiwoom-client            # 기본
pip install 'kiwoom-client[pandas]'  # to_dataframe() 까지
pip install 'kiwoom-client[mcp]'     # MCP 서버까지
uv add kiwoom-client                 # uv 를 쓴다면
```

- Python **3.10 이상**. 소스에서 쓰려면 `git clone` 뒤 `pip install -e .`
- [키움 REST API 포털](https://openapi.kiwoom.com)에서 **API 사용신청**으로 앱키·시크릿키를 발급받습니다. 환경변수는 [`.env.example`](https://github.com/younghwan91/kiwoom-client/blob/main/.env.example) 참고.
- 모의투자용 키와 실전투자용 키는 다릅니다. `is_mock` 과 짝이 맞지 않으면 인증이 거부됩니다.

| 구분 | 실전투자 | 모의투자 |
|------|---------|---------|
| `is_mock` | `False` (기본값) | `True` |
| REST URL | `https://api.kiwoom.com` | `https://mockapi.kiwoom.com` |
| WebSocket URL | `wss://api.kiwoom.com:10000` | `wss://mockapi.kiwoom.com:10000` |

## 사용법

### 계좌와 주문

```python
evaluation = api.account.account_evaluation(qry_tp="0", dmst_stex_tp="KRX")  # 계좌 평가 현황
deposit = api.account.deposit_detail(qry_tp="3")  # 예수금 상세
position = api.account.filled_position(dmst_stex_tp="KRX")  # 체결 잔고
unfilled = api.account.unfilled_orders(all_stk_tp="0", trde_tp="0", stex_tp="0")  # 미체결 주문

# 삼성전자 10주 지정가 매수 — 값은 키움 공식 스펙 기준 (문자열)
result = api.order.buy_order(
    dmst_stex_tp="KRX",  # 거래소 구분: KRX / NXT / SOR
    stk_cd="005930",     # 종목코드
    ord_qty="10",        # 주문 수량
    ord_uv="70000",      # 주문 단가
    trde_tp="0",         # 매매구분: 0 보통(지정가), 3 시장가, 28 스톱지정가 ...
)
api.order.sell_order(dmst_stex_tp="KRX", stk_cd="005930", ord_qty="10", ord_uv="75000", trde_tp="0")
api.order.modify_order(   # 정정 (kt10002)
    dmst_stex_tp="KRX", orig_ord_no="원주문번호", stk_cd="005930", mdfy_qty="5", mdfy_uv="71000",
)
api.order.cancel_order(   # 취소 (kt10003) — cncl_qty="0" 이면 잔량 전부
    dmst_stex_tp="KRX", orig_ord_no="원주문번호", stk_cd="005930", cncl_qty="5",
)

api.logout()  # 토큰 폐기 (선택)
api.close()   # 연결 종료 — with 문을 쓰면 자동
```

지정가(`ord_uv`)는 KRX 호가단위의 배수여야 합니다. 아니면 거부되거나 의도와 다른 가격에 체결됩니다.

```python
from kiwoom_client import add_ticks, round_to_tick, tick_size

tick_size(70123)        # Decimal('100')   (5만~20만원대는 1틱 100원)
round_to_tick(70123)    # Decimal('70100') (직전 유효 호가로 내림)
add_ticks(49950, 2)     # Decimal('50100') (구간 경계를 넘는 N틱 이동)

api.order.buy_order(
    dmst_stex_tp="KRX", stk_cd="005930", ord_qty="10",
    ord_uv=str(round_to_tick(target_price)), trde_tp="0",
)
```

### asyncio

`AsyncKiwoomAPI` 는 `KiwoomAPI` 와 같은 엔드포인트를 제공하며, 호출 앞에 `await` 만 붙이면 됩니다.

```python
import asyncio
from kiwoom_client import AsyncKiwoomAPI

async def main():
    async with AsyncKiwoomAPI(app_key="앱키", app_secret="시크릿키", is_mock=True) as api:
        # 서로 다른 TR은 동시에 나간다 — 직렬로 돌리면 3배 걸린다
        info, chart, ranking = await asyncio.gather(
            api.stock_info.basic_stock_info(stk_cd="005930"),
            api.chart.stock_daily_chart(stk_cd="005930", base_dt="20260326", upd_stkpc_tp="1"),
            api.ranking.top_volume_today(  # ka10030 — 필드는 api.describe("ka10030")
                mrkt_tp="000", sort_tp="1", mang_stk_incls="0", crd_tp="0", trde_qty_tp="0",
                pric_tp="0", trde_prica_tp="0", mrkt_open_tp="0", stex_tp="3",
            ),
        )
        print(info["stk_nm"])

asyncio.run(main())
```

Rate Limiter 는 TR(api_id)별로 걸립니다. 서로 다른 TR 은 서로를 막지 않고 동시에 나가며,
같은 TR 을 반복 호출할 때만 초당 1건으로 조여집니다. 전체 예제는 [`examples/async_usage.py`](https://github.com/younghwan91/kiwoom-client/blob/main/examples/async_usage.py).

### 응답을 숫자·DataFrame으로 받기

키움은 모든 값을 문자열로 돌려줍니다. 가격은 `"+70000"`, 등락률은 `"-1.23"`, 거래량은 `"1,234,567"` 같은 식이라 그대로는 계산에 쓸 수 없습니다.

```python
from kiwoom_client import to_dataframe, to_number, normalize

result = api.ranking.top_volume_today(...)

df = to_dataframe(result)     # 페이로드 키를 자동으로 찾아 DataFrame 으로 (문자열 → 숫자 포함)
print(df["cur_prc"].mean())   # 바로 계산 가능

data = normalize(result)      # dict 그대로 쓰고 싶다면
price = to_number("+70000")   # 70000
```

종목코드(`"005930"`)처럼 앞자리 0 이 의미를 갖는 값과 `base_dt` 같은 날짜·식별자 필드는 문자열로 남깁니다.
`to_dataframe()` 에는 pandas 가 필요합니다(`pip install 'kiwoom-client[pandas]'`).
차트 응답은 `to_ohlcv(resp)` 가 `open/high/low/close/volume` + 날짜 인덱스 DataFrame 으로 바꿉니다.

![to_dataframe() 실행 결과 — 문자열 응답이 계산 가능한 DataFrame 이 된다](https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/to_dataframe.png)

<sub>샘플 응답을 `to_dataframe()` 에 넣은 실제 출력입니다. 시세 값 자체는 예시입니다 — `stk_cd` 는 문자열로 남고 가격·거래량만 숫자가 되는 것을 보세요.</sub>

### 실시간 WebSocket

```python
import asyncio
from kiwoom_client import KiwoomAPI

api = KiwoomAPI(app_key="앱키", app_secret="시크릿키")
ws = api.create_websocket()

async def main():
    # connect()가 LOGIN 핸드셰이크까지 끝냅니다. 실패하면 KiwoomWebSocketError
    await ws.connect()

    # 콜백은 REAL 프레임의 항목 하나를 받습니다:
    # {"type": "0B", "item": "005930", "values": {"10": "+70000", ...}}
    ws.on("0B", lambda d: print(f"체결 {d['item']}: {d['values'].get('10')}"))
    ws.on("0D", lambda d: print(f"호가 {d['item']}: {d['values'].get('41')}"))

    # async 콜백도 그대로 등록할 수 있습니다
    async def save(d): ...
    ws.on("0B", save)

    # 삼성전자 실시간 체결+호가 구독
    await ws.subscribe("0B", "005930")
    await ws.subscribe(["0B", "0D"], ["005930", "000660", "035420"])

    # PING 응답과 재연결(재로그인·구독 복원)은 listen()이 알아서 처리합니다
    await ws.listen()

asyncio.run(main())
```

`values` 의 키는 키움 FID 번호입니다(10=현재가, 13=누적거래량, 41=매도최우선호가).

조건검색도 같은 WebSocket 을 씁니다. `api.condition_search` 가 요청 페이로드를 만들고, `ws.send()` 로 보낸 뒤 `ws.on_trnm()` 으로 응답을 받습니다.

```python
await ws.connect()
ws.on_trnm("CNSRLST", lambda d: print("조건식 목록:", d["data"]))
ws.on_trnm("CNSRREQ", lambda d: print("검색 결과:", d.get("data")))

# 조건식 목록을 먼저 조회해야 seq를 알 수 있습니다
await ws.send(api.condition_search.condition_list())

# seq로 검색 (search_type="1"이면 실시간 편입/이탈까지 수신)
await ws.send(api.condition_search.condition_search_realtime(seq="1"))
await ws.listen()
```

> **검증 상태**: 실서버(api.kiwoom.com) 대상으로 LOGIN 핸드셰이크 · PING 프레임 · REG 등록 응답까지 확인했습니다.
> 다만 **REAL 프레임의 항목 필드명(`item`/`values`)은 장 마감 중이라 아직 미확정**입니다. 장중 이상 동작을 만나면
> [이슈](https://github.com/younghwan91/kiwoom-client/issues)로 알려주세요. 직접 확인하려면 `python tests/integration_ws_smoke.py --prod`.

### 연속 조회 (페이지네이션)

응답 헤더의 `cont-yn` 이 `"Y"` 이면 다음 페이지가 있다는 뜻입니다. `request_all()` 이 끝까지 따라갑니다.

```python
all_data = api._client.request_all(
    "/api/dostk/acnt", "ka10076",
    data_key="filled_list",  # 응답에서 리스트 데이터의 키 이름
)
```

### 요청 제한 (Rate Limit)

키움 REST API 는 **TR(api_id)별로 독립적인** 호출 제한을 둡니다. 실측 결과:

| 항목 | 측정값 |
|---|---|
| 지속(sustained) 안전 속도 | **TR당 약 1 req/s** (이 속도에선 거부 0) |
| 순간 버스트(burst) 허용량 | **TR당 약 2건** |
| 초과 시 응답 | HTTP `429` + `{"return_code": 5, "return_msg": "허용된 요청 개수를 초과하였습니다"}` |
| 제한 단위 | **TR(api_id)별 독립** — 서로 다른 TR은 영향 없음 |

라이브러리는 기본으로 **TR별 토큰 버킷(1 req/s, 버스트 2)** 을 걸고, 그래도 `429` 가 나면 **백오프 후 재시도**합니다.

```python
api = KiwoomAPI(app_key="...", app_secret="...")                                  # 기본값
api = KiwoomAPI(app_key="...", app_secret="...", rate_limit=2.0, rate_burst=3, max_retries=5)  # 직접 조정
api = KiwoomAPI(app_key="...", app_secret="...", rate_limit=None)                 # 클라이언트 측 스로틀 끄기
```

> 서로 다른 TR 을 섞어 호출하면 합산 처리량은 더 높습니다. 같은 TR 을 반복(연속조회 루프 등)할 때는 1 req/s 에 수렴합니다 — 이 경우 `request_all()` 을 쓰세요.

### 에러 처리

```python
from kiwoom_client.base import KiwoomAPIError

try:
    result = api.order.buy_order(
        dmst_stex_tp="KRX", stk_cd="005930", ord_qty="10", ord_uv="70000", trde_tp="0",
    )
except KiwoomAPIError as e:
    print(f"에러 코드: {e.code}")
    print(f"에러 메시지: {e.message}")
    print(f"전체 응답: {e.response}")
```

`KiwoomTokenError`·`KiwoomServerMismatchError`(모의/실전 키 불일치)·`KiwoomRateLimitError` 같은 세분 예외도 있고,
모두 `KiwoomAPIError` 하위라 위 코드가 그대로 잡습니다. 원인을 아는 오류는 `e.hint` 에 다음 할 일이 담깁니다.

### 편의 기능

종목명 검색(`api.find_stock`), 코드값 상수(`OrderType.LIMIT`, `Exchange.KRX`), 조회 전용 CLI(`kiwoom quote 005930 --mock`),
마스킹된 `repr`·DEBUG 로그·`timeout=` 은 [편의 기능 문서](https://younghwan91.github.io/kiwoom-client/convenience/)에 모아 두었습니다.

## MCP 서버로 사용하기

<!-- mcp-name: io.github.younghwan91/kiwoom-client (MCP 레지스트리 PyPI 소유 확인용, server.json 참고) -->

Claude Code·Claude Desktop·Cursor·Codex 같은 MCP 클라이언트가 이 라이브러리를 도구로 부릅니다. 모듈 15개의 REST 엔드포인트 전부와 조건검색 4종, 그리고 편의 도구(`stock_search` 종목명→코드, `stock_snapshot`, `account_summary`, 전송하지 않는 `order_preview`)가 노출됩니다.

```bash
uvx --from 'kiwoom-client[mcp]' kiwoom-client-mcp config claude-code   # 붙여넣을 설정 출력 (claude-desktop·cursor·codex 도)
```

| 환경변수 | 설명 | 기본값 |
|---|---|---|
| `KIWOOM_APP_KEY` / `KIWOOM_APP_SECRET` | 앱키·시크릿키 (필수) | — |
| `KIWOOM_IS_MOCK` | 모의투자 서버 사용 여부 (true/false) | `false` |
| `KIWOOM_MCP_TOOLSETS` | 노출할 모듈 (예: `market,chart,account`) | 전부 |
| `KIWOOM_MCP_MODE` | `discovery` 면 메타 도구 3개만 노출해 컨텍스트 절약 | — |
| `KIWOOM_MCP_ALLOW_LIVE_ORDERS` | 실전투자 계좌에서 주문 도구를 노출할지 여부 | `false` |

**실주문 가드**: `KIWOOM_IS_MOCK=false`(실전투자)이고 `KIWOOM_MCP_ALLOW_LIVE_ORDERS` 가 `true` 가 아니면 주문 관련 도구는 서버 시작 시점에 아예 등록되지 않습니다. 도구 목록·toolset 필터·discovery 모드 어디로도 AI 에이전트가 그 도구에 닿지 못합니다. 모의투자(`KIWOOM_IS_MOCK=true`)는 이 가드 없이 항상 사용 가능합니다. 가드는 MCP 서버 경로에만 적용되며, 파이썬 코드에서 `KiwoomAPI`/`AsyncKiwoomAPI` 를 직접 쓰는 방식에는 영향이 없습니다.

클라이언트별 설정, 옵션 전체(`--toolsets`·`--discovery`·`--max-rows`), 도구·resources·prompts, 문제 해결은 [MCP 서버 문서](https://younghwan91.github.io/kiwoom-client/mcp/)에 있습니다.

## 아키텍처

`KiwoomAPI`(sync) / `AsyncKiwoomAPI`(async) 는 같은 구조를 공유하는 파사드입니다. 15개 엔드포인트 모듈은 `ModuleRegistry` 가 지연 생성하고, HTTP 호출·인증·재시도는 `BaseClient`/`AsyncBaseClient` 한 곳에 모여 있습니다. 실시간 데이터는 `KiwoomWebSocket` 이 같은 토큰을 재사용해 처리합니다.

```mermaid
flowchart LR
    User["사용자 코드"] --> API["KiwoomAPI / AsyncKiwoomAPI\n(ModuleRegistry 파사드)"]

    API --> Modules["15개 엔드포인트 모듈\naccount · stock_info · market · chart\norder · credit_order · ranking · sector\nforeign_institution · short_selling · slb\ntheme · condition_search · elw · etf"]

    Modules --> Client["BaseClient / AsyncBaseClient\n(request / request_all)"]

    Client --> Auth["KiwoomAuth\n(토큰 발급 · 만료전 갱신 · 401 재발급)"]
    Client --> RateLimiter["PerKeyRateLimiter\n(TR별 토큰 버킷, 429 자동 재시도)"]
    Client --> Parsing["parsing\n(to_number / to_dataframe)"]

    Auth -->|"POST /oauth2/token"| REST["키움 REST API\napi.kiwoom.com / mockapi.kiwoom.com"]
    Client -->|"POST /api/dostk/..."| REST

    API --> WS["KiwoomWebSocket"]
    Auth -->|"access_token 재사용"| WS
    WS <-->|"REG/REMOVE/REAL, 조건검색"| WSS["키움 실시간 WebSocket\nwss://.../api/dostk/websocket"]
```

## 지원 API 목록

```python
api.login()      # 접근토큰 발급 (선택 — 첫 호출에서 자동 발급됩니다)
api.logout()     # 접근토큰 폐기
```

| 모듈 | 개수 | 설명 |
|---|---|---|
| `api.account` | 33 | 계좌 — 예수금·잔고·손익·증거금·주문내역 |
| `api.stock_info` | 31 | 종목정보 — 기본정보·거래원·신용동향·업종코드 |
| `api.market` | 25 | 시세 — 호가·기관/외국인 매매·프로그램매매 |
| `api.ranking` | 23 | 순위정보 — 거래량·등락률·신용비율·외국인 상위 |
| `api.chart` | 21 | 차트 — 틱·분·일·주·월·년봉 (종목·업종·금현물) |
| `api.elw` | 11 | ELW — 민감도지표·괴리율·조건검색 |
| `api.etf` | 9 | ETF — 수익율·시세·시간대별 체결 |
| `api.order` | 8 | 주문 — 매수·매도·정정·취소 (금현물 포함) |
| `api.sector` | 6 | 업종 — 현재가·지수·투자자 순매수 |
| `api.credit_order` | 4 | 신용주문 — 매수·매도·정정·취소 |
| `api.foreign_institution` | 4 | 기관/외국인 매매 동향 |
| `api.slb` | 4 | 대차거래 — 추이·상위종목 |
| `api.condition_search` | 4 | 조건검색 (WebSocket, `trnm` 기반) |
| `api.theme` | 2 | 테마 — 그룹·구성종목 |
| `api.short_selling` | 1 | 공매도 추이 |
| `api.create_websocket()` | 19종 | 실시간 시세 — 체결·호가·잔고·VI 등 |

182개 메서드의 api_id·한글 TR 이름 전체 표는 [엔드포인트 목록](https://younghwan91.github.io/kiwoom-client/endpoints/)에 있습니다(코드에서 생성). API ID(`ka10001` 등)는 키움 공식 가이드의 TR 코드와 같습니다.

## 자주 묻는 질문 (FAQ)

**Q. sync(`KiwoomAPI`)와 async(`AsyncKiwoomAPI`) 중 뭘 써야 하나요?**
단발성 조회·간단한 스크립트라면 sync 로 충분합니다. 여러 종목을 동시에 조회하거나 실시간 WebSocket 과 함께 쓴다면 async 가 유리합니다.

**Q. 인증 에러(`유효하지 않은 토큰` 등)가 나요.**
토큰 만료라면 라이브러리가 자동으로 재발급 후 재시도합니다. 계속 실패한다면 `is_mock` 값과 앱키/시크릿키가 서로 맞는지 확인하세요 — 모의투자용 키로 실전투자 서버를(또는 반대로) 호출하면 인증이 거부됩니다.

**Q. HTTP `429` 가 계속 떠요.**
기본 Rate Limiter(TR당 1 req/s, 버스트 2)가 있어도, 같은 TR 을 여러 프로세스나 스레드에서 동시에 호출하면 넘길 수 있습니다. `rate_limit` 을 낮추거나 호출을 한 곳에서 조율하세요. [요청 제한](#요청-제한-rate-limit) 참고.

**Q. 지정가 주문(`buy_order`/`sell_order`)이 거부돼요.**
`ord_uv` 가 KRX 호가단위의 배수가 아니면 거부되거나 의도와 다른 가격에 체결됩니다. [`round_to_tick()`](#계좌와-주문)으로 보정한 값을 넘기세요.

**Q. pandas 없이도 쓸 수 있나요?**
네. `to_dataframe()` 만 pandas 가 필요하고, 기본 설치는 dict/list 형태 그대로 응답을 돌려줍니다.

**Q. 연속조회를 직접 관리하지 않고 한 번에 다 받고 싶어요.**
`request_all()` 을 쓰세요. `cont-yn`/`next-key` 를 자동으로 순회합니다. [연속 조회](#연속-조회-페이지네이션) 참고.

더 많은 질문은 [FAQ](https://younghwan91.github.io/kiwoom-client/faq/), 에러 코드별 해결은 [문제 해결](https://younghwan91.github.io/kiwoom-client/troubleshooting/)에 있습니다. 그래도 궁금한 점은 [Issues](https://github.com/younghwan91/kiwoom-client/issues)에 남겨주세요.

## 어디서 쓰이나

[quant-airflow](https://github.com/younghwan91/quant-airflow)의 일일 수집 DAG 가 이 라이브러리로 시세·수급·신용·공매도를 매일 TimescaleDB 에 적재합니다.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/pypi_downloads_dark.png">
  <img alt="kiwoom-client 누적 PyPI 다운로드 추이" src="https://raw.githubusercontent.com/younghwan91/kiwoom-client/main/docs/images/pypi_downloads_light.png" width="640">
</picture>

## 참고

- kiwoom-client 는 **키움증권과 무관한 비공식 오픈소스 프로젝트**입니다. "키움"·"Kiwoom" 은 키움증권(주)의 상표이며, 이 프로젝트는 키움증권이 공개한 REST API 를 호출하는 클라이언트일 뿐입니다.
- 공식 API 가이드: https://openapi.kiwoom.com/guide/apiguide
- 모의투자는 KRX 만 지원됩니다.
- 모든 API 이름은 키움증권 공식 가이드 기준입니다.

## 라이선스

MIT

## 기여 및 이슈 제보

- 🐛 버그 제보 및 기능 요청: [GitHub Issues](https://github.com/younghwan91/kiwoom-client/issues)
- 💡 새로운 기능 제안 및 PR 환영: [CONTRIBUTING.md](https://github.com/younghwan91/kiwoom-client/blob/main/CONTRIBUTING.md) 가이드라인을 확인해 주세요.

## 만든 사람

**채영환 (Younghwan Chae)** · [GitHub @younghwan91](https://github.com/younghwan91) · [LinkedIn](https://www.linkedin.com/in/younghwan-chae/)

전체 오픈소스 퀀트 스택은 [프로필](https://github.com/younghwan91)에서 한눈에 볼 수 있습니다.
