# kiwoom-client

> Python client for the Kiwoom Securities (키움증권) REST API and real-time WebSocket: 182 REST endpoints, 4 condition-search calls and 19 real-time types, sync (`KiwoomAPI`) and asyncio (`AsyncKiwoomAPI`) facades, automatic token refresh, per-TR rate limiting, response parsing to numbers/DataFrames, KRX tick sizes, and a built-in MCP server. REST, not OCX/COM — runs on Windows, macOS and Linux.

Install `pip install kiwoom-client` (extras `[pandas]`, `[mcp]`), Python 3.10+, import name `kiwoom_client`. Keys come from the Kiwoom REST API portal (https://openapi.kiwoom.com).

Rules for writing code against this library:

- `KiwoomAPI(app_key, app_secret, is_mock=False)` — **`is_mock` defaults to `False`, the live server.** Pass `is_mock=True` for paper trading (모의투자, mockapi.kiwoom.com). Live and paper keys are different; a key used against the wrong server is rejected (Kiwoom error 8030/8031, raised as `KiwoomServerMismatchError`).
- `KiwoomAPI.from_env(is_mock=True)` reads `KIWOOM_APP_KEY` / `KIWOOM_APP_SECRET` / `KIWOOM_IS_MOCK` (the same variables as the MCP server). Never hard-code or print keys.
- `api.order.*` and `api.credit_order.*` place **real, irreversible orders** when `is_mock=False`. Nothing in the Python API blocks them; only the MCP server has an opt-in guard (`KIWOOM_MCP_ALLOW_LIVE_ORDERS`). Do not run order code against a live account unless the user explicitly asks.
- `api.logout()` revokes the access token. Other processes sharing the same app key may lose their session — do not call it casually.
- Every REST method has the same signature `(cont_yn="N", next_key="", **fields)`. Pass Kiwoom's own request field names as keyword arguments with **string** values (`stk_cd="005930"`, `ord_qty="10"`). Find the method for an api_id (`ka10081`) or a Korean TR name in the endpoint reference; look fields up with `kiwoom_client.spec.get("ka10081").required_fields` or Kiwoom's guide. Do not invent method names.
- Coded fields have named constants in `kiwoom_client.codes` (`OrderType.LIMIT`, `Exchange.KRX`, …).
- Responses are plain dicts whose values are strings (`"+70000"`, `"1,234"`). `to_dataframe()` / `normalize()` / `to_number()` convert them; codes and dates stay strings. A non-zero `return_code` raises `KiwoomAPIError(code, message, response)` or one of its subclasses in `kiwoom_client.errors`.
- Continuation: a response carries `"cont-yn"` and `"next-key"`; call again with `cont_yn="Y", next_key=...`, or use `api._client.request_all(url, api_id, body)`.
- Rate limits are per api_id (about 1 req/s, burst 2) and handled by the client; different api_ids run concurrently under `AsyncKiwoomAPI`.
- Limit prices must be on the KRX tick grid: `round_to_tick(price)`.
- Real-time: `ws = api.create_websocket()`, `await ws.connect()`, `ws.on("0B", cb)`, `await ws.subscribe("0B", "005930")`, `await ws.listen()`. `values` keys are Kiwoom FID numbers (`"10"` = current price).

This file is generated from the code by `scripts/gen_docs.py`; the signatures and docstrings below are the library's own.

## KiwoomAPI (sync facade)

### `KiwoomAPI`

```
class KiwoomAPI(app_key: str, app_secret: str, base_url: str | None = None, is_mock: bool = False, rate_limit: float | None = 1.0, rate_burst: int = 2, max_retries: int = 3, retry_backoff: float = 1.1, expiry_margin: float = 60.0, validate_params: bool | str = False, *, timeout: float | httpx.Timeout = 30.0)
```

Unified facade for all Kiwoom REST API endpoints.

Rate limiting (per-TR token bucket, ~1 req/s + burst 2) and automatic 429
retry are enabled by default; pass ``rate_limit=None`` to disable.

The access token is managed for you: it is issued on first use, reissued
before it expires, and reissued again if the API answers 401. Calling
``login()`` explicitly is optional and simply issues the first token.

Args:
    app_key: API app key from Kiwoom developer portal.
    app_secret: API app secret from Kiwoom developer portal.
    base_url: Override API base URL.
    is_mock: Use mock trading server if True.
    rate_limit: Per-TR sustained request rate (req/s). None disables.
    rate_burst: Per-TR burst capacity (max instantaneous requests).
    max_retries: Automatic retries on HTTP 429 / return_code 5.
    retry_backoff: Base seconds to wait before a retry (grows per attempt).
    expiry_margin: Reissue the token this many seconds before it expires.
    validate_params: Check request fields against the TR catalog
        (:mod:`kiwoom_client.spec`) before sending. ``False`` (default) sends
        as-is; ``"warn"`` emits :class:`~kiwoom_client.spec.validation.KiwoomParamWarning`;
        ``"error"``/``True`` raises
        :class:`~kiwoom_client.spec.validation.KiwoomParamError` and sends nothing.
    timeout: HTTP timeout in seconds (or an ``httpx.Timeout``) for API and
        token requests. Defaults to 30s.

### `KiwoomAPI.close`

```
def close() -> None
```

Close all connections.

### `KiwoomAPI.create_websocket`

```
def create_websocket() -> KiwoomWebSocket
```

Create a WebSocket client for real-time data.

Returns:
    KiwoomWebSocket instance configured with current auth.

### `KiwoomAPI.find_stock`

```
def find_stock(query: str, *, markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), limit: int | None = 10, refresh: bool = False, cache_ttl: float | None = None) -> list[dict[str, Any]]
```

Search stocks by (part of) name or code: ``api.find_stock("삼성전자")``.

Best match first — exact code, exact name, name prefix, code prefix,
then substring; case and spaces are ignored. See :meth:`stock_list`
for caching.

### `KiwoomAPI.from_env`

```
def from_env(env_file: str | os.PathLike[str] | None = None, *, is_mock: bool | None = None, **kwargs: Any) -> KiwoomAPI
```

Build a client from ``KIWOOM_APP_KEY`` / ``KIWOOM_APP_SECRET`` / ``KIWOOM_IS_MOCK``.

The names match the MCP server, so one ``.env`` serves both. Process
environment variables win over ``env_file``; an explicit ``is_mock``
argument wins over both. ``KIWOOM_IS_MOCK`` accepts true/false, 1/0,
yes/no, on/off — anything else raises rather than guessing.

If ``KIWOOM_IS_MOCK`` is set nowhere and ``is_mock`` is not passed, the
client connects to the **live** server (``is_mock=False``, the same
default as the constructor and the MCP server) and logs a warning on
the ``kiwoom_client`` logger. Set ``KIWOOM_IS_MOCK=true`` to practise
on the mock server.

Args:
    env_file: Optional path to a ``.env`` file, parsed without extra
        dependencies. Nothing is read from disk unless it is given.
    is_mock: Override the mock flag regardless of the environment.
    **kwargs: Passed through to the constructor (``rate_limit``,
        ``max_retries``, ...).

Raises:
    ValueError: If the key or secret is missing, or ``KIWOOM_IS_MOCK``
        is not a boolean.
    FileNotFoundError: If ``env_file`` is given but does not exist.

### `KiwoomAPI.login`

```
def login() -> dict[str, Any]
```

Authenticate and obtain an access token.

Optional — the first API call issues a token on its own. Call this
when you want to fail fast on bad credentials.

Returns:
    Token response dict from the API.

### `KiwoomAPI.logout`

```
def logout() -> dict[str, Any]
```

Revoke the current access token.

### `KiwoomAPI.stock_code`

```
def stock_code(name: str, *, markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), refresh: bool = False, cache_ttl: float | None = None) -> str
```

The code of the stock named exactly ``name`` (``"삼성전자"`` -> ``"005930"``).

Raises:
    LookupError: If no stock or several stocks have that exact name;
        the message lists close candidates.

### `KiwoomAPI.stock_list`

```
def stock_list(markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), *, refresh: bool = False, cache_ttl: float | None = None) -> list[dict[str, Any]]
```

All listed stocks in ``markets`` (default 코스피+코스닥), cached.

Fetched once per market with 종목정보 리스트 (ka10099, all pages) and
kept on this client. ``refresh=True`` refetches; ``cache_ttl`` (s)
refetches entries older than that. Records are the raw ka10099
``list`` items (``code``, ``name``, ``marketName``, ``state``, ...).

## AsyncKiwoomAPI (asyncio facade)

Same endpoints as `KiwoomAPI`; every call is awaited.

### `AsyncKiwoomAPI`

```
class AsyncKiwoomAPI(app_key: str, app_secret: str, base_url: str | None = None, is_mock: bool = False, rate_limit: float | None = 1.0, rate_burst: int = 2, max_retries: int = 3, retry_backoff: float = 1.1, expiry_margin: float = 60.0, validate_params: bool | str = False, *, timeout: float | httpx.Timeout = 30.0)
```

Asyncio facade for all Kiwoom REST API endpoints.

Identical surface to :class:`KiwoomAPI`, except every endpoint call is
awaited. Calls to *different* TRs run concurrently; the per-TR limiter
still serializes calls to the same TR, matching Kiwoom's own limit.

Args:
    app_key: API app key from Kiwoom developer portal.
    app_secret: API app secret from Kiwoom developer portal.
    base_url: Override API base URL.
    is_mock: Use mock trading server if True.
    rate_limit: Per-TR sustained request rate (req/s). None disables.
    rate_burst: Per-TR burst capacity (max instantaneous requests).
    max_retries: Automatic retries on HTTP 429 / return_code 5.
    retry_backoff: Base seconds to wait before a retry (grows per attempt).
    expiry_margin: Reissue the token this many seconds before it expires.
    validate_params: Check request fields against the TR catalog
        (:mod:`kiwoom_client.spec`) before sending. ``False`` (default) sends
        as-is; ``"warn"`` emits :class:`~kiwoom_client.spec.validation.KiwoomParamWarning`;
        ``"error"``/``True`` raises
        :class:`~kiwoom_client.spec.validation.KiwoomParamError` and sends nothing.
    timeout: HTTP timeout in seconds (or an ``httpx.Timeout``) for API and
        token requests. Defaults to 30s.

### `AsyncKiwoomAPI.close`

```
async def close() -> None
```

Close all connections.

### `AsyncKiwoomAPI.create_websocket`

```
async def create_websocket() -> KiwoomWebSocket
```

Create a WebSocket client for real-time data.

Returns:
    KiwoomWebSocket instance configured with current auth.

### `AsyncKiwoomAPI.find_stock`

```
async def find_stock(query: str, *, markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), limit: int | None = 10, refresh: bool = False, cache_ttl: float | None = None) -> list[dict[str, Any]]
```

Search stocks by name or code — see :meth:`KiwoomAPI.find_stock`.

### `AsyncKiwoomAPI.from_env`

```
def from_env(env_file: str | os.PathLike[str] | None = None, *, is_mock: bool | None = None, **kwargs: Any) -> AsyncKiwoomAPI
```

Build a client from the environment — see :meth:`KiwoomAPI.from_env`.

Same variables, precedence and live-server default (with a warning)
as the sync facade.

### `AsyncKiwoomAPI.login`

```
async def login() -> dict[str, Any]
```

Authenticate and obtain an access token (optional — see KiwoomAPI).

### `AsyncKiwoomAPI.logout`

```
async def logout() -> dict[str, Any]
```

Revoke the current access token.

### `AsyncKiwoomAPI.stock_code`

```
async def stock_code(name: str, *, markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), refresh: bool = False, cache_ttl: float | None = None) -> str
```

Exact name -> code — see :meth:`KiwoomAPI.stock_code`.

### `AsyncKiwoomAPI.stock_list`

```
async def stock_list(markets: Sequence[StockListMarket | str] = (<StockListMarket.KOSPI: '0'>, <StockListMarket.KOSDAQ: '10'>), *, refresh: bool = False, cache_ttl: float | None = None) -> list[dict[str, Any]]
```

All listed stocks in ``markets``, cached — see :meth:`KiwoomAPI.stock_list`.

## Low-level client (`api._client`)

### `api._client.request`

```
def request(resource_url: str, api_id: str, body: dict[str, Any] | None = None, cont_yn: str = 'N', next_key: str = '', extra_headers: dict[str, str] | None = None) -> dict[str, Any]
```

Send a POST request to a Kiwoom REST API endpoint.

Args:
    resource_url: API resource path (e.g., /api/dostk/acnt).
    api_id: API endpoint identifier (e.g., ka10001).
    body: Request body parameters.
    cont_yn: Continuation flag ("N" or "Y").
    next_key: Pagination key for continuation queries.
    extra_headers: Additional headers to include.

Returns:
    Parsed JSON response as a dictionary.

Raises:
    KiwoomAPIError: If the API returns a non-zero return_code.
    httpx.HTTPStatusError: If still rate-limited (429) after retries,
        or still unauthorized (401) after a token refresh.

### `api._client.request_all`

```
def request_all(resource_url: str, api_id: str, body: dict[str, Any] | None = None, data_key: str | None = None, max_pages: int = 100) -> list[dict[str, Any]]
```

Auto-paginate through all pages of a Kiwoom API endpoint.

Args:
    resource_url: API resource path.
    api_id: API endpoint identifier.
    body: Request body parameters.
    data_key: Key in response containing the list data to accumulate.
    max_pages: Safety limit on number of pages to fetch.

Returns:
    Accumulated list of all data items across pages.

## KiwoomWebSocket (`ws = api.create_websocket()`)

### `ws.connect`

```
async def connect() -> None
```

Open the connection and complete the LOGIN handshake.

Raises:
    KiwoomWebSocketError: If the server rejects the token.

### `ws.disconnect`

```
async def disconnect() -> None
```

Close the connection and stop the listener.

### `ws.listen`

```
async def listen() -> None
```

Receive frames and dispatch them until ``disconnect()`` is called.

Answers PING frames, restores subscriptions after a reconnect, and
keeps running when a callback raises.

### `ws.on`

```
def on(data_type: str, callback: Callback) -> None
```

Register a callback for a real-time data type.

The callback receives one entry of the REAL frame's ``data`` list —
a dict carrying ``type``, ``item`` and ``values``.

Args:
    data_type: Real-time data type code (e.g., "0B" for 주식체결).
    callback: Sync or async function called for each matching item.

### `ws.on_message`

```
def on_message(callback: Callback) -> None
```

Register a callback that receives every decoded frame.

### `ws.on_trnm`

```
def on_trnm(trnm: str, callback: Callback) -> None
```

Register a callback for a non-REAL message type (e.g. "CNSRLST").

### `ws.send`

```
async def send(payload: dict[str, Any]) -> None
```

Send a raw protocol message.

Use it with the payloads built by ``api.condition_search``.

Raises:
    RuntimeError: If not connected.

### `ws.subscribe`

```
async def subscribe(types: list[str] | str, items: list[str] | str, grp_no: str = '1', refresh: str = '1') -> None
```

Register real-time data for the given types and items.

Args:
    types: Real-time type code(s), e.g. "0B" or ["0B", "0D"].
    items: Stock code(s), e.g. "005930" or ["005930", "000660"].
    grp_no: Group number. Kiwoom keys registrations by group.
    refresh: "1" keeps existing registrations, "0" replaces them.

### `ws.unsubscribe`

```
async def unsubscribe(types: list[str] | str, items: list[str] | str, grp_no: str = '1', refresh: str = '1') -> None
```

Unregister real-time data for the given types and items.

## KRX tick size

### `add_ticks`

```
def add_ticks(price: Decimal | int | float, ticks: int) -> Decimal
```

Move ``ticks`` valid quotes up (positive) or down (negative) from ``price``.

Band edges are handled: one tick up from 1,999 is 2,000, one tick down
from 2,000 is 1,999 (not 1,995).

>>> add_ticks(49_950, 2)
Decimal('50100')

Args:
    price: A valid quote (see :func:`is_on_tick`).
    ticks: Number of ticks to move; 0 returns ``price``.

Raises:
    ValueError: If ``price`` is not on a tick, or the move would go to
        zero or below.

### `is_on_tick`

```
def is_on_tick(price: Decimal | int | float) -> bool
```

True if ``price`` is a valid KRX quote — positive and a multiple of its tick.

>>> is_on_tick(70100), is_on_tick(70150)
(True, False)

### `round_to_tick`

```
def round_to_tick(price: Decimal | int | float) -> Decimal
```

Round a price down to the nearest valid KRX tick for its band.

Args:
    price: The price to round, in KRW. Must be positive.

Returns:
    `price` rounded down to the nearest multiple of its tick size.

### `round_up_to_tick`

```
def round_up_to_tick(price: Decimal | int | float) -> Decimal
```

Round a price **up** to the nearest valid KRX tick for its band.

The counterpart of :func:`round_to_tick` (which rounds down). Rounding up
can cross into the next band: ``round_up_to_tick(1999.5)`` is ``2000``.

Raises:
    ValueError: If price is not positive.

### `tick_size`

```
def tick_size(price: Decimal | int | float) -> Decimal
```

Return the KRX minimum quote increment (호가가격단위) for a price.

Args:
    price: The price to quote, in KRW. Must be positive.

Returns:
    The minimum tick size (KRW) applicable at that price band.

Raises:
    ValueError: If price is not positive.

### `ticks_between`

```
def ticks_between(start: Decimal | int | float, end: Decimal | int | float) -> int
```

Signed number of ticks from ``start`` to ``end`` across bands.

``add_ticks(start, ticks_between(start, end)) == end`` always holds.
Unlike :func:`ticks_in`, which divides a width by a single band's tick,
this counts each band at its own tick size.

>>> ticks_between(49_900, 50_100)
3

Raises:
    ValueError: If either price is not on a tick.

### `ticks_in`

```
def ticks_in(width: Decimal | int | float, price: Decimal | int | float) -> Decimal
```

How many ticks a price gap ``width`` (KRW) spans at price band ``price``.

Returns the exact (non-rounded) quotient -- callers that need to
distinguish e.g. "2.2 ticks" from "3.0 ticks" (a real difference in stop
noise risk at low price bands) should not round this themselves.

## Response parsing

### `extract_records`

```
def extract_records(response: Any, key: str | None = None) -> tuple[str | None, list[dict[str, Any]]]
```

Locate the list of records inside a Kiwoom response.

Kiwoom names the payload key differently per endpoint (``stk_infr``,
``acnt_evlt_remn_indv_tot``, …), so callers otherwise hunt for it by hand.

Args:
    response: A response dict, or the list returned by ``request_all()``.
    key: Payload key to use. Auto-detected when omitted — the longest
        list of dicts in the response wins.

Returns:
    ``(key, records)``. The key is None when the response was already a
    list or held no record list.

Raises:
    KeyError: If an explicit key is absent from the response.

### `normalize`

```
def normalize(data: Any, exclude: Iterable[str] | None = None) -> Any
```

Recursively convert numeric strings in an API response.

Args:
    data: A response dict, a list of records, or a single value.
    exclude: Field names to leave untouched, on top of the built-in
        identifier/date detection.

Returns:
    A new structure of the same shape; the input is not mutated.

### `to_dataframe`

```
def to_dataframe(response: Any, key: str | None = None, numeric: bool = True) -> Any
```

Turn a Kiwoom response into a pandas DataFrame.

Args:
    response: A response dict, or the list returned by ``request_all()``.
    key: Payload key to use. Auto-detected when omitted.
    numeric: Convert numeric strings to int/float. Identifier and date
        fields stay strings regardless.

Returns:
    A pandas DataFrame — empty if the response held no records.

Raises:
    ImportError: If pandas is not installed.
    KeyError: If an explicit key is absent from the response.

### `to_number`

```
def to_number(value: Any) -> Any
```

Convert a Kiwoom numeric string to int/float, leaving anything else.

Handles a leading ``+``/``-``, comma grouping and surrounding whitespace.
Blank strings become None. Strings with a meaningful leading zero
(``"005930"``) and any non-numeric text are returned unchanged.

Args:
    value: A raw field value of any type.

Returns:
    int, float, None for blanks, or the original value untouched.

### `to_ohlcv`

```
def to_ohlcv(response: Any, key: str | None = None, keep: Iterable[str] = ()) -> Any
```

Turn a chart response into an OHLCV DataFrame indexed by time.

Works for the stock, sector and gold-spot chart TRs (tick, minute, daily,
weekly, monthly, yearly), single page or the list from ``request_all()``.

The result has columns ``open``, ``high``, ``low``, ``close``, ``volume``
and a ``DatetimeIndex`` named ``date`` (daily and longer) or ``datetime``
(intraday), sorted oldest first — Kiwoom sends newest first.

Notes:
    - Prices lose their direction sign (``"-70000"`` -> ``70000``).
    - Sector (업종) index values come as Kiwoom sends them, i.e. with the
      decimal point removed (``"265012"`` for 2650.12).
    - :func:`to_dataframe` is unchanged and still returns every raw field.

Args:
    response: A chart response dict, or the list from ``request_all()``.
    key: Payload key (e.g. ``"stk_dt_pole_chart_qry"``). Auto-detected
        when omitted.
    keep: Extra fields to carry over as columns, numeric-converted with
        :func:`to_number` (e.g. ``["trde_prica"]`` for 거래대금 — its unit
        differs per TR: 백만원 for daily, 원 for weekly/monthly).

Returns:
    A pandas DataFrame; empty (with the OHLCV columns) for no records.

Raises:
    ImportError: If pandas is not installed.
    KeyError: If the records have no time or price fields, i.e. the
        response is not a chart.

## Named codes (`kiwoom_client.codes`)

Named constants for Kiwoom's coded request/response fields.

Kiwoom encodes options as short strings — ``trde_tp="3"`` is a market order,
``stex_tp="3"`` means "KRX+NXT combined", ``mrkt_tp="101"`` is KOSDAQ — and the
same field name means different things in different TRs. These enums give the
common ones a name so a typo becomes an ``AttributeError`` instead of a
rejected (or worse, accepted) order.

Every member is a ``str``, so it can be passed straight into any endpoint:

```text
from kiwoom_client.codes import Exchange, OrderType

api.order.buy_order(
    dmst_stex_tp=Exchange.KRX, stk_cd="005930", ord_qty="10",
    ord_uv="70000", trde_tp=OrderType.LIMIT,
)
```

Only values stated in Kiwoom's official API spec are included, and each enum
lists the TRs it was checked against. A field whose codes differ per TR
(``mrkt_tp`` comes in at least five dialects) gets one enum per dialect.

Sources:
    - 키움 REST API 가이드: https://openapi.kiwoom.com/guide/apiguide
    - 키움 공식 스펙 번들:
      https://github.com/Kiwoom-Securities/Kiwoom-REST-API (``kiwoom/_data/kiwoom_api_spec.json``)

### `AdjustedPrice`

```
class AdjustedPrice(str, Enum)
RAW = "0"
ADJUSTED = "1"
```

수정주가구분 ``upd_stkpc_tp`` for chart TRs (ka10079-ka10083, ka10094).

### `Exchange`

```
class Exchange(str, Enum)
KRX = "KRX"
NXT = "NXT"
SOR = "SOR"
```

국내거래소구분 ``dmst_stex_tp`` for orders.

Checked against kt10000-kt10003 (주문) and kt10006-kt10009 (신용주문).
Account TRs such as kt00004/kt00018 accept only ``KRX``/``NXT``; history
TRs (kt00007, kt00009) additionally take ``"%"`` for all exchanges.
The mock server supports ``KRX`` only.

### `Market`

```
class Market(str, Enum)
ALL = "000"
KOSPI = "001"
KOSDAQ = "101"
```

시장구분 ``mrkt_tp`` in the ``000/001/101`` dialect.

Used by most ranking and stock-info TRs (e.g. ka10016-ka10018,
ka10023-ka10028, ka10054, ka10098). Some of those (ka10020-ka10022,
ka10044, ka10058, ka10069) accept only ``KOSPI``/``KOSDAQ``. Sector TRs
(ka20001…), program-trading TRs (ka90003…) and ka10099 use other codes —
see :class:`StockListMarket` for the last one.

### `OrderType`

```
class OrderType(str, Enum)
LIMIT = "0"
MARKET = "3"
CONDITIONAL_LIMIT = "5"
BEST_LIMIT = "6"
FIRST_LIMIT = "7"
LIMIT_IOC = "10"
MARKET_IOC = "13"
BEST_IOC = "16"
LIMIT_FOK = "20"
MARKET_FOK = "23"
BEST_FOK = "26"
STOP_LIMIT = "28"
MID_PRICE = "29"
MID_PRICE_IOC = "30"
MID_PRICE_FOK = "31"
PRE_MARKET = "61"
AFTER_HOURS_SINGLE = "62"
POST_MARKET = "81"
```

매매구분 ``trde_tp`` for stock orders.

Checked against kt10000 (매수), kt10001 (매도), kt10006 (신용 매수),
kt10007 (신용 매도). Other TRs reuse the name ``trde_tp`` for unrelated
codes (e.g. 순매수/순매도 in ranking TRs) — don't pass these there.

### `PriceChangeSign`

```
class PriceChangeSign(str, Enum)
UPPER_LIMIT = "1"
UP = "2"
UNCHANGED = "3"
LOWER_LIMIT = "4"
DOWN = "5"
```

전일대비기호 ``pred_pre_sig`` in responses (46+ TRs).

### `QueryExchange`

```
class QueryExchange(str, Enum)
KRX = "1"
NXT = "2"
ALL = "3"
```

거래소구분 ``stex_tp`` for market-data queries.

The ``1:KRX, 2:NXT, 3:통합`` dialect used by ~45 query TRs (ranking,
stock-info and sector TRs such as ka10016-ka10037, ka10051, ka20002).
A few TRs (ka10075, ka10076, ka10085) use ``0`` for 통합 instead — check
the TR's spec before using this enum there.

### `StockListMarket`

```
class StockListMarket(str, Enum)
KOSPI = "0"
KOSDAQ = "10"
K_OTC = "30"
KONEX = "50"
ETN = "60"
LOSS_LIMITED_ETN = "70"
GOLD_SPOT = "80"
VOLATILITY_ETN = "90"
INFRA_FUND = "2"
ELW = "3"
MUTUAL_FUND = "4"
WARRANT = "5"
REIT = "6"
WARRANT_CERTIFICATE = "7"
ETF = "8"
HIGH_YIELD_FUND = "9"
```

시장구분 ``mrkt_tp`` for 종목정보 리스트 (ka10099, ``stock_info_list``).

### `exchange_stock_code`

```
def exchange_stock_code(stk_cd: str, exchange: Exchange | str) -> str
```

Return the exchange-specific ``stk_cd`` that quote/chart TRs expect.

Kiwoom's spec: ``KRX:039490, NXT:039490_NX, SOR:039490_AL``. Any existing
suffix on ``stk_cd`` is replaced.

>>> exchange_stock_code("005930", Exchange.NXT)
'005930_NX'

Raises:
    ValueError: If ``exchange`` is not KRX, NXT or SOR.

## Errors (`kiwoom_client.errors`)

Every exception kiwoom-client raises, in one place.

```text
KiwoomError
├── KiwoomAuthError              토큰 발급·폐기 실패 (/oauth2/*)
├── KiwoomWebSocketError         WebSocket 로그인·프로토콜 실패
├── KiwoomParamError             요청 필드 불일치 (validate_params="error", 보내기 전)
└── KiwoomAPIError               return_code != 0
    ├── KiwoomTokenError         토큰 거부 (return_code 3; 8003/8005/8010/8103)
    │   └── KiwoomServerMismatchError  모의/실전 키·토큰 불일치 (8030/8031)
    ├── KiwoomRateLimitError     호출 한도 초과 (return_code 5; 1700-1702)
    ├── KiwoomRequestError       잘못된 요청 파라미터·헤더 (15xx, 1687)
    │   └── KiwoomStockNotFoundError  종목코드 없음 (1901-1903)
    └── KiwoomUnsupportedError   모의투자·법인 미지원 API (8104/8200)
```

The subclasses only *narrow* what was already raised: every one of them is a
``KiwoomAPIError`` with the same ``code``/``message``/``response`` as before,
so existing ``except KiwoomAPIError`` blocks catch them unchanged. The extra
``error_code`` attribute holds the 4-digit code Kiwoom embeds in
``return_msg`` (``"...[8005:Token이 유효하지 않습니다]"``).

HTTP failures that survive the built-in retries (429, 401 after a refresh)
still surface as ``httpx.HTTPStatusError``, as before.

Error codes: 키움 REST API 가이드 "오류코드" (https://openapi.kiwoom.com/guide/apiguide).

- `KiwoomAPIError(KiwoomError)`: Kiwoom API error with return_code and return_msg.
- `KiwoomAuthError(KiwoomError)`: Token issuance or revocation failed.
- `KiwoomError(Exception)`: Base class of every error kiwoom-client raises on purpose.
- `KiwoomParamError(KiwoomError, ValueError)`: ``validate_params="error"`` 에서 요청 바디가 카탈로그와 다를 때. 요청은 나가지 않았다.
- `KiwoomParamWarning(UserWarning)`: ``validate_params="warn"`` 에서 요청 바디가 카탈로그와 맞지 않을 때.
- `KiwoomRateLimitError(KiwoomAPIError)`: Request quota exceeded (``return_code`` 5; 1700/1701/1702), after the automatic backoff retries ran out.
- `KiwoomRequestError(KiwoomAPIError)`: The request itself is malformed — missing or invalid parameters, unknown api-id, bad headers (15xx, 1687).
- `KiwoomServerMismatchError(KiwoomTokenError)`: Mock/live mismatch: a mock key or token used on the live server, or the reverse (8030/8031). Check ``is_mock`` against the kind of key.
- `KiwoomStockNotFoundError(KiwoomRequestError)`: Unknown stock code or market/exchange for it (1901/1902/1903).
- `KiwoomTokenError(KiwoomAPIError)`: The access token was rejected (``return_code`` 3; 8003/8005/8010/8103).
- `KiwoomUnsupportedError(KiwoomAPIError)`: The API is not offered for this account or server — e.g. not available on the mock server (8104) or for corporate customers (8200).
- `KiwoomWebSocketError(KiwoomError)`: WebSocket login or protocol failure.

### `api_error_class`

```
def api_error_class(return_code: Any, message: Any) -> type[KiwoomAPIError]
```

Pick the most specific :class:`KiwoomAPIError` subclass for a payload.

The 4-digit code inside ``return_msg`` wins; ``return_code`` is the
fallback; anything unrecognised is a plain ``KiwoomAPIError``.

### `parse_error_code`

```
def parse_error_code(message: object) -> int | None
```

Pull Kiwoom's 4-digit error code (``[8005:...]``) out of a message.

## TR field catalog (`kiwoom_client.spec`)

### `spec.Field`

```
class Field
```

요청 또는 응답 필드 하나.

### `spec.TRSpec`

```
class TRSpec
```

TR(api_id) 하나의 명세.

### `spec.api_ids`

```
def api_ids() -> list[str]
```

카탈로그의 모든 api_id (정렬).

### `spec.catalog_source`

```
def catalog_source() -> dict[str, Any]
```

카탈로그를 만든 원천 (저장소·경로·고정 커밋).

### `spec.describe`

```
def describe(target: Any) -> str
```

TR 하나의 사람이 읽을 도움말 — 호출 예, 요청 필드(필수 표시), 응답 필드.

``target`` 은 :func:`resolve` 가 받는 것 무엇이든. ``print(spec.describe("ka10001"))``.

### `spec.endpoint_index`

```
def endpoint_index() -> Mapping[tuple[str, str], str]
```

``(모듈 이름, 메서드 이름) → api_id`` — REST 모듈 메서드 전부.

소스를 파싱하지 않고 각 메서드를 기록용 가짜 클라이언트로 한 번씩 불러 얻는다
(네트워크 없음). 조건검색(WebSocket)은 api_id 가 아니라 trnm 이라 뺀다.

### `spec.field_names`

```
def field_names(api_id: str) -> dict[str, str]
```

응답 필드 id → 한글명. 실시간 타입(``"0B"``)이면 FID(``"10"``) → ``"현재가"``.

list 안팎을 가리지 않고 모두 담는다 (같은 id 가 여러 번 나오면 처음 것).
DataFrame 열 이름을 바꿀 때 ``df.rename(columns=spec.field_names("ka10081"))``.

### `spec.for_method`

```
def for_method(module_name: str, method_name: str) -> TRSpec
```

``api.<module_name>.<method_name>`` 이 부르는 TR 의 명세.

### `spec.get`

```
def get(api_id: str) -> TRSpec
```

api_id 로 TR 명세를 얻는다. 없으면 ``KeyError``.

### `spec.label`

```
def label(api_id: str, record: Mapping[str, Any]) -> dict[str, Any]
```

``record`` 의 키를 한글 필드명으로 바꾼 새 dict. 모르는 키는 그대로 둔다.

실시간 콜백의 ``values`` 처럼 키가 FID 인 dict 에 쓴다::

    ws.on("0B", lambda d: print(spec.label("0B", d["values"])))
    # {'체결시간': '165208', '현재가': '-20800', ...}

한글명이 겹치면 뒤에 오는 키를 ``"한글명(id)"`` 로 남겨 값을 잃지 않는다.

### `spec.method_for`

```
def method_for(api_id: str) -> tuple[str, str] | None
```

api_id 를 부르는 ``(모듈 이름, 메서드 이름)`` — 감싼 메서드가 없으면 ``None``.

### `spec.resolve`

```
def resolve(target: Any) -> TRSpec
```

api_id(``"ka10001"``), ``"stock_info.basic_stock_info"``, 또는 바운드 메서드
(``api.stock_info.basic_stock_info``) → TR 명세.

### `spec.search`

```
def search(query: str) -> list[TRSpec]
```

api_id·TR 이름·메뉴에 ``query`` 가 들어간 TR (대소문자 무시).

## REST endpoints (182)

Format: `api_id` `api.<module>.<method>()` — 한글 TR 이름 (English) [POST url]. ⚠️ = places a real order when `is_mock=False`.

### api.account — 계좌 (Account)

- `ka00001` `api.account.account_number_inquiry()` — 계좌번호조회 (Account Number Inquiry) [POST /api/dostk/acnt]
- `ka01690` `api.account.daily_balance_return_rate()` — 일별잔고수익률 (Daily Balance Return Rate) [POST /api/dostk/acnt]
- `ka10072` `api.account.realized_profit_by_date()` — 일자별종목별실현손익요청_일자 (Realized Profit by Date per Stock) [POST /api/dostk/acnt]
- `ka10073` `api.account.realized_profit_by_period()` — 일자별종목별실현손익요청_기간 (Realized Profit by Period per Stock) [POST /api/dostk/acnt]
- `ka10074` `api.account.daily_realized_profit()` — 일별실현손익요청 (Daily Realized Profit) [POST /api/dostk/acnt]
- `ka10075` `api.account.unfilled_orders()` — 미체결요청 (Unfilled Orders) [POST /api/dostk/acnt]
- `ka10076` `api.account.filled_orders()` — 체결요청 (Filled Orders History) [POST /api/dostk/acnt]
- `ka10077` `api.account.today_realized_profit_detail()` — 당일실현손익상세요청 (Today Realized Profit Detail) [POST /api/dostk/acnt]
- `ka10085` `api.account.account_return_rate()` — 계좌수익률요청 (Account Return Rate) [POST /api/dostk/acnt]
- `ka10088` `api.account.unfilled_split_order_detail()` — 미체결 분할주문 상세 (Unfilled Split Order Detail) [POST /api/dostk/acnt]
- `ka10170` `api.account.today_trading_journal()` — 당일매매일지요청 (Today Trading Journal) [POST /api/dostk/acnt]
- `kt00001` `api.account.deposit_detail()` — 예수금상세현황요청 (Deposit Detail Status) [POST /api/dostk/acnt]
- `kt00002` `api.account.daily_estimated_deposit()` — 일별추정예탁자산현황요청 (Daily Estimated Deposit Asset Status) [POST /api/dostk/acnt]
- `kt00003` `api.account.estimated_asset()` — 추정자산조회요청 (Estimated Asset Inquiry) [POST /api/dostk/acnt]
- `kt00004` `api.account.account_evaluation()` — 계좌평가현황요청 (Account Evaluation Status) [POST /api/dostk/acnt]
- `kt00005` `api.account.filled_position()` — 체결잔고요청 (Filled Position Balance) [POST /api/dostk/acnt]
- `kt00007` `api.account.order_execution_detail()` — 계좌별주문체결내역상세요청 (Account Order Execution Detail) [POST /api/dostk/acnt]
- `kt00008` `api.account.next_day_settlement()` — 계좌별익일결제예정내역요청 (Next Day Settlement Schedule) [POST /api/dostk/acnt]
- `kt00009` `api.account.order_execution_status()` — 계좌별주문체결현황요청 (Account Order Execution Status) [POST /api/dostk/acnt]
- `kt00010` `api.account.withdrawable_amount()` — 주문인출가능금액요청 (Withdrawable Order Amount) [POST /api/dostk/acnt]
- `kt00011` `api.account.orderable_qty_by_margin()` — 증거금율별주문가능수량조회요청 (Orderable Quantity by Margin Rate) [POST /api/dostk/acnt]
- `kt00012` `api.account.orderable_qty_by_credit()` — 신용보증금율별주문가능수량조회요청 (Orderable Quantity by Credit Margin Rate) [POST /api/dostk/acnt]
- `kt00013` `api.account.margin_detail()` — 증거금세부내역조회요청 (Margin Detail Inquiry) [POST /api/dostk/acnt]
- `kt00015` `api.account.comprehensive_transaction_history()` — 위탁종합거래내역요청 (Comprehensive Transaction History) [POST /api/dostk/acnt]
- `kt00016` `api.account.daily_return_detail()` — 일별계좌수익률상세현황요청 (Daily Account Return Rate Detail) [POST /api/dostk/acnt]
- `kt00017` `api.account.today_account_status()` — 계좌별당일현황요청 (Today Account Status by Account) [POST /api/dostk/acnt]
- `kt00018` `api.account.evaluation_balance_detail()` — 계좌평가잔고내역요청 (Account Evaluation Balance Detail) [POST /api/dostk/acnt]
- `kt50020` `api.account.gold_spot_balance()` — 금현물 잔고확인 (Gold Spot Balance) [POST /api/dostk/acnt]
- `kt50021` `api.account.gold_spot_deposit()` — 금현물 예수금 (Gold Spot Deposit) [POST /api/dostk/acnt]
- `kt50030` `api.account.gold_spot_order_execution_all()` — 금현물 주문체결전체조회 (Gold Spot All Order Execution) [POST /api/dostk/acnt]
- `kt50031` `api.account.gold_spot_order_execution()` — 금현물 주문체결조회 (Gold Spot Order Execution) [POST /api/dostk/acnt]
- `kt50032` `api.account.gold_spot_transaction_history()` — 금현물 거래내역조회 (Gold Spot Transaction History) [POST /api/dostk/acnt]
- `kt50075` `api.account.gold_spot_unfilled_orders()` — 금현물 미체결조회 (Gold Spot Unfilled Orders) [POST /api/dostk/acnt]

### api.stock_info — 종목정보 (Stock info)

- `ka00198` `api.stock_info.realtime_stock_inquiry_rank()` — 실시간종목조회순위 (Real-time Stock Inquiry Ranking) [POST /api/dostk/stkinfo]
- `ka10001` `api.stock_info.basic_stock_info()` — 종목기본정보요청 (Basic Stock Info) [POST /api/dostk/stkinfo]
- `ka10002` `api.stock_info.stock_trading_agent()` — 종목거래원요청 (Stock Trading Agent) [POST /api/dostk/stkinfo]
- `ka10003` `api.stock_info.execution_info()` — 체결정보요청 (Execution Info) [POST /api/dostk/stkinfo]
- `ka10013` `api.stock_info.credit_trading_trend()` — 신용매매동향요청 (Credit Trading Trend) [POST /api/dostk/stkinfo]
- `ka10015` `api.stock_info.daily_transaction_detail()` — 일별거래상세요청 (Daily Transaction Detail) [POST /api/dostk/stkinfo]
- `ka10016` `api.stock_info.new_high_low()` — 신고저가요청 (New High/Low) [POST /api/dostk/stkinfo]
- `ka10017` `api.stock_info.upper_lower_limit()` — 상하한가요청 (Upper/Lower Limit Price) [POST /api/dostk/stkinfo]
- `ka10018` `api.stock_info.near_high_low()` — 고저근접요청 (Near High/Low) [POST /api/dostk/stkinfo]
- `ka10019` `api.stock_info.rapid_price_change()` — 급등락요청 (Rapid Price Change) [POST /api/dostk/stkinfo]
- `ka10024` `api.stock_info.trading_volume_update()` — 거래량갱신요청 (Trading Volume Update) [POST /api/dostk/stkinfo]
- `ka10025` `api.stock_info.volume_concentration()` — 매물대집중요청 (Volume Concentration) [POST /api/dostk/stkinfo]
- `ka10026` `api.stock_info.high_low_per()` — 고저PER요청 (High/Low PER) [POST /api/dostk/stkinfo]
- `ka10028` `api.stock_info.change_rate_vs_opening()` — 시가대비등락률요청 (Change Rate vs Opening Price) [POST /api/dostk/stkinfo]
- `ka10043` `api.stock_info.trading_agent_supply_demand()` — 거래원매물대분석요청 (Trading Agent Supply/Demand Trend Analysis) [POST /api/dostk/stkinfo]
- `ka10052` `api.stock_info.trading_agent_instant_volume()` — 거래원순간거래량요청 (Trading Agent Instant Volume) [POST /api/dostk/stkinfo]
- `ka10054` `api.stock_info.vi_triggered_stocks()` — 변동성완화장치발동종목요청 (VI Triggered Stocks) [POST /api/dostk/stkinfo]
- `ka10055` `api.stock_info.today_vs_yesterday_volume()` — 당일전일체결량요청 (Today vs Yesterday Execution Volume) [POST /api/dostk/stkinfo]
- `ka10058` `api.stock_info.daily_trading_by_investor()` — 투자자별일별매매종목요청 (Daily Trading by Investor) [POST /api/dostk/stkinfo]
- `ka10059` `api.stock_info.investor_institution_by_stock()` — 투자자기관별종목별요청 (Investor/Institution by Stock) [POST /api/dostk/stkinfo]
- `ka10061` `api.stock_info.investor_institution_aggregate()` — 종목별투자자기관별합계요청 (Investor/Institution by Stock Aggregate) [POST /api/dostk/stkinfo]
- `ka10084` `api.stock_info.today_vs_yesterday_execution()` — 당일전일체결요청 (Today vs Yesterday Execution) [POST /api/dostk/stkinfo]
- `ka10095` `api.stock_info.watchlist_stock_info()` — 관심종목정보요청 (Watchlist Stock Info) [POST /api/dostk/stkinfo]
- `ka10099` `api.stock_info.stock_info_list()` — 종목정보 리스트 (Stock Info List) [POST /api/dostk/stkinfo]
- `ka10100` `api.stock_info.stock_info_inquiry()` — 종목정보 조회 (Stock Info Inquiry) [POST /api/dostk/stkinfo]
- `ka10101` `api.stock_info.industry_code_list()` — 업종코드 리스트 (Industry Code List) [POST /api/dostk/stkinfo]
- `ka10102` `api.stock_info.member_company_list()` — 회원사 리스트 (Member Company List) [POST /api/dostk/stkinfo]
- `ka90003` `api.stock_info.program_buy_top50()` — 프로그램순매수상위50요청 (Program Buy Top 50) [POST /api/dostk/stkinfo]
- `ka90004` `api.stock_info.program_trading_by_stock()` — 종목별프로그램매매현황요청 (Program Trading by Stock) [POST /api/dostk/stkinfo]
- `kt20016` `api.stock_info.margin_loan_available_stocks()` — 신용융자 가능종목요청 (Margin Loan Available Stocks) [POST /api/dostk/stkinfo]
- `kt20017` `api.stock_info.margin_loan_inquiry()` — 신용융자 가능문의 (Margin Loan Inquiry) [POST /api/dostk/stkinfo]

### api.market — 시세 (Market)

- `ka10004` `api.market.stock_quote()` — 주식호가요청 (Stock Quote) [POST /api/dostk/mrkcond]
- `ka10005` `api.market.stock_daily_weekly_monthly()` — 주식일주월시분요청 (Stock Daily/Weekly/Monthly by Time) [POST /api/dostk/mrkcond]
- `ka10006` `api.market.stock_minute_price()` — 주식시분요청 (Stock Minute Price) [POST /api/dostk/mrkcond]
- `ka10007` `api.market.order_book_info()` — 시세표성정보요청 (Order Book Info) [POST /api/dostk/mrkcond]
- `ka10011` `api.market.rights_issue_price()` — 신주인수권전체시세요청 (Rights Issue Price) [POST /api/dostk/mrkcond]
- `ka10044` `api.market.daily_institutional_trading()` — 일별기관매매종목요청 (Daily Institutional Trading by Stock) [POST /api/dostk/mrkcond]
- `ka10045` `api.market.institutional_trading_trend()` — 종목별기관매매추이요청 (Institutional Trading Trend by Stock) [POST /api/dostk/mrkcond]
- `ka10046` `api.market.hourly_execution_strength()` — 체결강도추이시간별요청 (Hourly Execution Strength) [POST /api/dostk/mrkcond]
- `ka10047` `api.market.daily_execution_strength()` — 체결강도추이일별요청 (Daily Execution Strength) [POST /api/dostk/mrkcond]
- `ka10063` `api.market.intraday_investor_trading()` — 장중투자자별매매요청 (Intraday Investor Trading by Time Slot) [POST /api/dostk/mrkcond]
- `ka10066` `api.market.after_hours_investor_trading()` — 장마감후투자자별매매요청 (After-Hours Investor Trading) [POST /api/dostk/mrkcond]
- `ka10078` `api.market.broker_stock_trading_trend()` — 증권사별종목매매동향요청 (Broker Stock Trading Trend) [POST /api/dostk/mrkcond]
- `ka10086` `api.market.daily_stock_price()` — 일자별주가요청 (Daily Stock Price) [POST /api/dostk/mrkcond]
- `ka10087` `api.market.after_hours_single_price()` — 시간외단일가요청 (After-Hours Single Price) [POST /api/dostk/mrkcond]
- `ka50010` `api.market.gold_spot_execution_trend()` — 금현물체결추이 (Gold Spot Execution Trend) [POST /api/dostk/mrkcond]
- `ka50012` `api.market.gold_spot_daily_trend()` — 금현물일별추이 (Gold Spot Daily Trend) [POST /api/dostk/mrkcond]
- `ka50087` `api.market.gold_spot_expected_execution()` — 금현물예상체결 (Gold Spot Expected Execution) [POST /api/dostk/mrkcond]
- `ka50100` `api.market.gold_spot_price_info()` — 금현물 시세정보 (Gold Spot Price Info) [POST /api/dostk/mrkcond]
- `ka50101` `api.market.gold_spot_order_book()` — 금현물 호가 (Gold Spot Order Book) [POST /api/dostk/mrkcond]
- `ka90005` `api.market.program_trading_by_time()` — 프로그램매매추이요청 시간대별 (Program Trading by Time Slot) [POST /api/dostk/mrkcond]
- `ka90006` `api.market.program_arbitrage_balance()` — 프로그램매매차익잔고추이요청 (Program Arbitrage Balance Trend) [POST /api/dostk/mrkcond]
- `ka90007` `api.market.cumulative_program_trading()` — 프로그램매매누적추이요청 (Cumulative Program Trading Trend) [POST /api/dostk/mrkcond]
- `ka90008` `api.market.program_trading_by_stock_time()` — 종목시간별프로그램매매추이요청 (Program Trading by Stock and Time Slot) [POST /api/dostk/mrkcond]
- `ka90010` `api.market.program_trading_by_date()` — 프로그램매매추이요청 일자별 (Program Trading by Date) [POST /api/dostk/mrkcond]
- `ka90013` `api.market.program_trading_by_stock_day()` — 종목일별프로그램매매추이요청 (Program Trading by Stock and Day) [POST /api/dostk/mrkcond]

### api.chart — 차트 (Chart)

- `ka10060` `api.chart.investor_institution_chart()` — 종목별투자자기관별차트요청 (Investor/Institution Chart by Stock) [POST /api/dostk/chart]
- `ka10064` `api.chart.intraday_investor_chart()` — 시간대별투자자매매차트요청 (Intraday Investor Trading Chart by Time Slot) [POST /api/dostk/chart]
- `ka10079` `api.chart.stock_tick_chart()` — 주식틱차트요청 (Stock Tick Chart) [POST /api/dostk/chart]
- `ka10080` `api.chart.stock_minute_chart()` — 주식분봉차트요청 (Stock Minute Chart) [POST /api/dostk/chart]
- `ka10081` `api.chart.stock_daily_chart()` — 주식일봉차트요청 (Stock Daily Chart) [POST /api/dostk/chart]
- `ka10082` `api.chart.stock_weekly_chart()` — 주식주봉차트요청 (Stock Weekly Chart) [POST /api/dostk/chart]
- `ka10083` `api.chart.stock_monthly_chart()` — 주식월봉차트요청 (Stock Monthly Chart) [POST /api/dostk/chart]
- `ka10094` `api.chart.stock_yearly_chart()` — 주식년봉차트요청 (Stock Yearly Chart) [POST /api/dostk/chart]
- `ka20004` `api.chart.industry_tick_chart()` — 업종틱차트요청 (Industry Tick Chart) [POST /api/dostk/chart]
- `ka20005` `api.chart.industry_minute_chart()` — 업종분봉차트요청 (Industry Minute Chart) [POST /api/dostk/chart]
- `ka20006` `api.chart.industry_daily_chart()` — 업종일봉차트요청 (Industry Daily Chart) [POST /api/dostk/chart]
- `ka20007` `api.chart.industry_weekly_chart()` — 업종주봉차트요청 (Industry Weekly Chart) [POST /api/dostk/chart]
- `ka20008` `api.chart.industry_monthly_chart()` — 업종월봉차트요청 (Industry Monthly Chart) [POST /api/dostk/chart]
- `ka20019` `api.chart.industry_yearly_chart()` — 업종년봉차트요청 (Industry Yearly Chart) [POST /api/dostk/chart]
- `ka50079` `api.chart.gold_spot_tick_chart()` — 금현물틱차트조회요청 (Gold Spot Tick Chart) [POST /api/dostk/chart]
- `ka50080` `api.chart.gold_spot_minute_chart()` — 금현물분봉차트조회요청 (Gold Spot Minute Chart) [POST /api/dostk/chart]
- `ka50081` `api.chart.gold_spot_daily_chart()` — 금현물일봉차트조회요청 (Gold Spot Daily Chart) [POST /api/dostk/chart]
- `ka50082` `api.chart.gold_spot_weekly_chart()` — 금현물주봉차트조회요청 (Gold Spot Weekly Chart) [POST /api/dostk/chart]
- `ka50083` `api.chart.gold_spot_monthly_chart()` — 금현물월봉차트조회요청 (Gold Spot Monthly Chart) [POST /api/dostk/chart]
- `ka50091` `api.chart.gold_spot_intraday_tick_chart()` — 금현물당일틱차트조회요청 (Gold Spot Intraday Tick Chart) [POST /api/dostk/chart]
- `ka50092` `api.chart.gold_spot_intraday_minute_chart()` — 금현물당일분봉차트조회요청 (Gold Spot Intraday Minute Chart) [POST /api/dostk/chart]

### api.order — 주문 (Order)

- ⚠️ `kt10000` `api.order.buy_order()` — 주식매수주문 (Stock Buy Order) [POST /api/dostk/ordr]
- ⚠️ `kt10001` `api.order.sell_order()` — 주식매도주문 (Stock Sell Order) [POST /api/dostk/ordr]
- ⚠️ `kt10002` `api.order.modify_order()` — 주식정정주문 (Stock Modify Order) [POST /api/dostk/ordr]
- ⚠️ `kt10003` `api.order.cancel_order()` — 주식취소주문 (Stock Cancel Order) [POST /api/dostk/ordr]
- ⚠️ `kt50000` `api.order.gold_spot_buy_order()` — 금현물 매수주문 (Gold Spot Buy Order) [POST /api/dostk/ordr]
- ⚠️ `kt50001` `api.order.gold_spot_sell_order()` — 금현물 매도주문 (Gold Spot Sell Order) [POST /api/dostk/ordr]
- ⚠️ `kt50002` `api.order.gold_spot_modify_order()` — 금현물 정정주문 (Gold Spot Modify Order) [POST /api/dostk/ordr]
- ⚠️ `kt50003` `api.order.gold_spot_cancel_order()` — 금현물 취소주문 (Gold Spot Cancel Order) [POST /api/dostk/ordr]

### api.credit_order — 신용주문 (Credit order)

- ⚠️ `kt10006` `api.credit_order.margin_buy_order()` — 신용매수주문 (Credit Margin Buy Order) [POST /api/dostk/crdordr]
- ⚠️ `kt10007` `api.credit_order.margin_sell_order()` — 신용매도주문 (Credit Margin Sell Order) [POST /api/dostk/crdordr]
- ⚠️ `kt10008` `api.credit_order.margin_modify_order()` — 신용정정주문 (Credit Margin Modify Order) [POST /api/dostk/crdordr]
- ⚠️ `kt10009` `api.credit_order.margin_cancel_order()` — 신용취소주문 (Credit Margin Cancel Order) [POST /api/dostk/crdordr]

### api.ranking — 순위정보 (Ranking)

- `ka10020` `api.ranking.top_order_book_volume()` — 호가잔량상위요청 (Top Order Book Volume) [POST /api/dostk/rkinfo]
- `ka10021` `api.ranking.sudden_order_book_increase()` — 호가잔량급증요청 (Sudden Order Book Increase) [POST /api/dostk/rkinfo]
- `ka10022` `api.ranking.sudden_order_ratio_increase()` — 잔량율급증요청 (Sudden Order Ratio Increase) [POST /api/dostk/rkinfo]
- `ka10023` `api.ranking.sudden_volume_increase()` — 거래량급증요청 (Sudden Volume Increase) [POST /api/dostk/rkinfo]
- `ka10027` `api.ranking.top_change_rate()` — 전일대비등락률상위요청 (Top Change Rate vs Previous Day) [POST /api/dostk/rkinfo]
- `ka10029` `api.ranking.top_expected_change_rate()` — 예상체결등락률상위요청 (Top Expected Execution Change Rate) [POST /api/dostk/rkinfo]
- `ka10030` `api.ranking.top_volume_today()` — 당일거래량상위요청 (Top Volume Today) [POST /api/dostk/rkinfo]
- `ka10031` `api.ranking.top_volume_yesterday()` — 전일거래량상위요청 (Top Volume Yesterday) [POST /api/dostk/rkinfo]
- `ka10032` `api.ranking.top_trading_value()` — 거래대금상위요청 (Top Trading Value) [POST /api/dostk/rkinfo]
- `ka10033` `api.ranking.top_credit_ratio()` — 신용비율상위요청 (Top Credit Ratio) [POST /api/dostk/rkinfo]
- `ka10034` `api.ranking.top_foreign_trades_by_period()` — 외인기간별매매상위요청 (Top Foreign Trades by Period) [POST /api/dostk/rkinfo]
- `ka10035` `api.ranking.top_foreign_consecutive_buy()` — 외인연속순매매상위요청 (Top Foreign Consecutive Net Buy) [POST /api/dostk/rkinfo]
- `ka10036` `api.ranking.top_foreign_limit_increase()` — 외인한도소진율증가상위 (Top Foreign Limit Exhaustion Rate Increase) [POST /api/dostk/rkinfo]
- `ka10037` `api.ranking.top_foreign_broker_trading()` — 외국계창구매매상위요청 (Top Foreign Holding Broker Trading) [POST /api/dostk/rkinfo]
- `ka10038` `api.ranking.broker_ranking_by_stock()` — 종목별증권사순위요청 (Broker Ranking by Stock) [POST /api/dostk/rkinfo]
- `ka10039` `api.ranking.top_broker_by_stock()` — 증권사별매매상위요청 (Top Broker by Stock) [POST /api/dostk/rkinfo]
- `ka10040` `api.ranking.main_brokers_today()` — 당일주요거래원요청 (Main Brokers Today) [POST /api/dostk/rkinfo]
- `ka10042` `api.ranking.top_net_buying_brokers()` — 순매수거래원순위요청 (Top Net Buying Brokers) [POST /api/dostk/rkinfo]
- `ka10053` `api.ranking.departed_brokers_today()` — 당일상위이탈원요청 (Departed Brokers Today) [POST /api/dostk/rkinfo]
- `ka10062` `api.ranking.same_day_net_buying_rank()` — 동일순매매순위요청 (Same Day Net Buying Rank) [POST /api/dostk/rkinfo]
- `ka10065` `api.ranking.top_intraday_investor_trading()` — 장중투자자별매매상위요청 (Top Intraday Investor Trading by Time) [POST /api/dostk/rkinfo]
- `ka10098` `api.ranking.after_hours_change_rate_rank()` — 시간외단일가등락율순위요청 (After Hours Change Rate Rank) [POST /api/dostk/rkinfo]
- `ka90009` `api.ranking.top_foreign_institution_trades()` — 외국인기관매매상위요청 (Top Foreign Institution Trades) [POST /api/dostk/rkinfo]

### api.sector — 업종 (Sector)

- `ka10010` `api.sector.industry_program_trading()` — 업종프로그램매매요청 (Industry Program Trading) [POST /api/dostk/sect]
- `ka10051` `api.sector.industry_investor_net_buy()` — 업종별투자자순매수요청 (Industry Investor Net Buy) [POST /api/dostk/sect]
- `ka20001` `api.sector.industry_current_price()` — 업종현재가요청 (Industry Current Price) [POST /api/dostk/sect]
- `ka20002` `api.sector.industry_stock_price()` — 업종별주가요청 (Industry Stock Price) [POST /api/dostk/sect]
- `ka20003` `api.sector.all_industry_index()` — 전업종지수요청 (All Industry Index) [POST /api/dostk/sect]
- `ka20009` `api.sector.industry_daily_price()` — 업종현재가일별요청 (Industry Daily Price) [POST /api/dostk/sect]

### api.foreign_institution — 기관/외국인 (Foreign / institution)

- `ka10008` `api.foreign_institution.foreign_trading_trend()` — 주식외국인종목별매매동향 (Foreign Trading Trend by Stock) [POST /api/dostk/frgnistt]
- `ka10009` `api.foreign_institution.institutional_stock()` — 주식기관요청 (Institutional Stock) [POST /api/dostk/frgnistt]
- `ka10131` `api.foreign_institution.consecutive_trading_status()` — 기관외국인연속매매현황요청 (Institution and Foreign Consecutive Trading Status) [POST /api/dostk/frgnistt]
- `ka52301` `api.foreign_institution.gold_spot_investor_status()` — 금현물투자자현황 (Gold Spot Investor Status) [POST /api/dostk/frgnistt]

### api.short_selling — 공매도 (Short selling)

- `ka10014` `api.short_selling.short_selling_trend()` — 공매도추이요청 (Short Selling Trend) [POST /api/dostk/shsa]

### api.slb — 대차거래 (Stock lending & borrowing)

- `ka10068` `api.slb.lending_trend()` — 대차거래추이요청 (Lending Trend) [POST /api/dostk/slb]
- `ka10069` `api.slb.top10_lending()` — 대차거래상위10종목요청 (Top 10 Lending Stocks) [POST /api/dostk/slb]
- `ka20068` `api.slb.lending_trend_by_stock()` — 대차거래추이요청종목별 (Lending Trend by Stock) [POST /api/dostk/slb]
- `ka90012` `api.slb.lending_details()` — 대차거래내역요청 (Lending Details) [POST /api/dostk/slb]

### api.theme — 테마 (Theme)

- `ka90001` `api.theme.theme_group_list()` — 테마그룹별요청 (Theme Group List) [POST /api/dostk/thme]
- `ka90002` `api.theme.theme_component_stocks()` — 테마구성종목요청 (Theme Component Stocks) [POST /api/dostk/thme]

### api.elw — ELW

- `ka10048` `api.elw.daily_sensitivity_indicator()` — ELW일별민감도지표요청 (ELW Daily Sensitivity Indicator) [POST /api/dostk/elw]
- `ka10050` `api.elw.sensitivity_indicator()` — ELW민감도지표요청 (ELW Sensitivity Indicator) [POST /api/dostk/elw]
- `ka30001` `api.elw.price_spike()` — ELW급등락요청 (ELW Price Spike) [POST /api/dostk/elw]
- `ka30002` `api.elw.top_net_buying_by_broker()` — ELW회원사별순매수상위요청 (ELW Top Net Buying by Broker) [POST /api/dostk/elw]
- `ka30003` `api.elw.lp_daily_holding_trend()` — ELW LP일별보유추이요청 (ELW LP Daily Holding Trend) [POST /api/dostk/elw]
- `ka30004` `api.elw.premium_rate()` — ELW괴리율요청 (ELW Premium Rate) [POST /api/dostk/elw]
- `ka30005` `api.elw.condition_search()` — ELW조건검색요청 (ELW Condition Search) [POST /api/dostk/elw]
- `ka30009` `api.elw.change_rate_ranking()` — ELW등락율순위요청 (ELW Change Rate Ranking) [POST /api/dostk/elw]
- `ka30010` `api.elw.order_volume_ranking()` — ELW호가잔량순위요청 (ELW Order Volume Ranking) [POST /api/dostk/elw]
- `ka30011` `api.elw.proximity_rate()` — ELW근접율요청 (ELW Proximity Rate) [POST /api/dostk/elw]
- `ka30012` `api.elw.detailed_stock_info()` — ELW종목상세정보요청 (ELW Detailed Stock Info) [POST /api/dostk/elw]

### api.etf — ETF

- `ka40001` `api.etf.return_rate()` — ETF수익률요청 (ETF Return Rate) [POST /api/dostk/etf]
- `ka40002` `api.etf.stock_info()` — ETF종목정보요청 (ETF Stock Info) [POST /api/dostk/etf]
- `ka40003` `api.etf.daily_trend()` — ETF일별추이요청 (ETF Daily Trend) [POST /api/dostk/etf]
- `ka40004` `api.etf.overall_market_price()` — ETF전체시세요청 (ETF Overall Market Price) [POST /api/dostk/etf]
- `ka40006` `api.etf.time_segment_trend()` — ETF시간대별추이요청 (ETF Time Segment Trend) [POST /api/dostk/etf]
- `ka40007` `api.etf.time_segment_execution()` — ETF시간대별체결요청 (ETF Time Segment Execution) [POST /api/dostk/etf]
- `ka40008` `api.etf.daily_execution()` — ETF일자별체결요청 (ETF Daily Execution) [POST /api/dostk/etf]
- `ka40009` `api.etf.time_nav()` — ETF시간대별NAV요청 (ETF Time NAV) [POST /api/dostk/etf]
- `ka40010` `api.etf.time_trend()` — ETF시간대별추이요청 (ETF Time Trend) [POST /api/dostk/etf]

## Condition search (WebSocket payload builders)

- `CNSRLST` `api.condition_search.condition_list()` — 조건검색 목록조회 (Condition List)
- `CNSRREQ` `api.condition_search.condition_search()` — 조건검색 요청 일반 (Condition Search)
- `CNSRREQ` `api.condition_search.condition_search_realtime()` — 조건검색 요청 실시간 (Condition Search + Realtime)
- `CNSRCLR` `api.condition_search.condition_search_cancel()` — 조건검색 실시간 해제 (Cancel Realtime Condition Search)

## Real-time types (`await ws.subscribe(type, item)`)

- `00` 주문체결
- `04` 잔고
- `0A` 주식기세
- `0B` 주식체결
- `0C` 주식우선호가
- `0D` 주식호가잔량
- `0E` 주식시간외호가
- `0F` 주식당일거래원
- `0G` ETF NAV
- `0H` 주식예상체결
- `0I` 국제금환산가격
- `0J` 업종지수
- `0U` 업종등락
- `0g` 주식종목정보
- `0m` ELW 이론가
- `0s` 장시작시간
- `0u` ELW 지표
- `0w` 종목프로그램매매
- `1h` VI발동/해제
