KIS API First Integration: Environment, Expiry and Business-Error Checks

한국어로 읽기

TECH INSIGHT / EXPLAINED

The first integration target is a verified quote response from the intended environment. Keep application credentials, access tokens, market selection and response validation as four explicit steps.

Three colleagues keep paper and live credentials separate and validate a quote response.
AI-generated educational illustration. Three colleagues keep paper and live credentials separate and validate a quote response.

Local execution of the actual project

These captures show the existing project UI or functions executed locally with non-private sample inputs. Each caption states the scope of the execution.

Observed results from calling the original LLMStockTrading KISClient._parse with synthetic Response objects. HTTP, business-code, and JSON-decoding failures produce different exceptions. No live KIS request, token refresh, or order was executed.
Observed results from calling the original LLMStockTrading KISClient._parse with synthetic Response objects. HTTP, business-code, and JSON-decoding failures produce different exceptions. No live KIS request, token refresh, or order was executed.

Bind credentials to the environment

Use the official KIS portal and sample repository to register access and identify supported account and paper-trading functions. Keep paper and live keys in separate configuration entries. The paper base URL is https://openapivts.koreainvestment.com:29443; live uses https://openapi.koreainvestment.com:9443. Do not fall back automatically from one to the other.

Use a currently supported Python release, an isolated environment and a pinned Requests dependency. Credentials and cached tokens belong in protected storage, not a source file or committed JSON cache. Even token prefixes do not need to be printed.

Cache until expiry, not midnight

The tokenP request uses client_credentials with appkey and appsecret. Store the issued expiry metadata with the token and its environment identity. Reuse while valid with a deliberate refresh margin; calendar date alone is not a validity check. Avoid concurrent workers refreshing the same credential at once.

A failed quote is not automatically an expired token. Distinguish HTTP status from the business error fields and refresh only according to the documented authentication error contract. Observe issuance limits from current documentation rather than a guessed daily allowance.

Request one known market and symbol

For the domestic-stock inquire-price endpoint, the official sample uses FHKST01010100 for both real and demo. Other operations may differ. FID_COND_MRKT_DIV_CODE=J identifies KRX in the current sample; do not treat every market code as interchangeable. Preserve the six-character symbol 005930 as text.

After a request with Bearer authorization, appkey/appsecret headers and a timeout, check HTTP success and rt_cd before reading output. The parser below uses a synthetic response; it does not connect to an account.

from decimal import Decimal
def parse_kis_quote(payload):
    if not isinstance(payload, dict):
        raise ValueError('expected response object')
    if payload.get('rt_cd') != '0':
        raise RuntimeError('KIS business request failed')
    out = payload.get('output')
    if not isinstance(out, dict):
        raise ValueError('missing output object')
    price = Decimal(str(out['stck_prpr']))
    change = Decimal(str(out['prdy_ctrt']))
    if not price.is_finite() or price <= 0 or not change.is_finite():
        raise ValueError('invalid quote values')
    return {'price': price, 'change_pct': change}
sample = {'rt_cd': '0', 'output': {'stck_prpr': '71000', 'prdy_ctrt': '0.85'}}
assert parse_kis_quote(sample)['price'] == Decimal('71000')

Do not depend on an unverified name field

Only consume fields guaranteed by the selected endpoint. Obtain a display name from the documented instrument master or a suitable reference endpoint instead of assuming every quote includes hts_kor_isnm. Handle missing and malformed values explicitly.

Next, save timestamped read-only observations, test the strategy as decisions without orders, and separately verify paper-order state transitions. A mock fill is useful for software testing but cannot establish live fill quality.

Sources and further reading

KIS official repository · Current-price official example · KIS authentication example

Content and examples reviewed: 2026-09-29

댓글