KIS Open API → Vellab Live Trading Integration Playbook (KR Equities)
Date: 2026-02-24 (KST)
TL;DR
If Vellab is moving from research-only into Korean live execution, the first bottleneck is not alpha — it is broker/API reliability and control-plane discipline.
This playbook distills what matters most for a safe first rollout with 한국투자증권(KIS) Open API:
- Implement hard API guardrails first (rate limits, reconnect policy, idempotency)
- Treat live trading as a state machine + reconciliation system, not “call order endpoint and pray”
- Encode KR market/session constraints + legal no-go patterns into pre-trade checks
- Ship in phases (paper shadow → tiny real notional → capped ramp)
1) Verified KIS Operational Constraints (Must Encode in Code)
1.1 Auth + Endpoint Shape
From official KIS sample/auth artifacts:
- REST token endpoint:
POST /oauth2/tokenP - WebSocket approval endpoint:
POST /oauth2/Approval - Production REST domain:
https://openapi.koreainvestment.com:9443 - Paper REST domain:
https://openapivts.koreainvestment.com:29443 - WebSocket endpoints in sample config:
- prod:
ws://ops.koreainvestment.com:21000 - paper:
ws://ops.koreainvestment.com:31000
- prod:
Implementation note: store AppKey/Secret in secret manager only (no git, no plaintext dotfiles in repo).
1.2 Official Rate/Session Limits (공지 기반)
KIS official notice (“API 호출 유량 안내 (REST, 웹소켓) (2025.08.07 기준)”) states:
- REST (real): 20 req/sec
- REST (paper): 2 req/sec
- Token issuance
/oauth2/tokenP: 1 req/sec - WebSocket: 41 realtime registrations per session (combined)
- WebSocket session scope: 1 session per account/appkey
Design implication:
- Build account-scoped limiter buckets
- Keep a separate strict limiter for token issuance
- Track WebSocket subscription budget as first-class state
1.3 Reconnect Abuse Risk (New 2026 notice)
Official 2026-02-24 notice warns: repeated connect/disconnect loops or endless subscribe/unsubscribe loops can cause temporary block of IP + appkey.
Design implication:
- Mandatory reconnect backoff (e.g., exp backoff + jitter)
- Circuit breaker after N failures/min
- Never run blind “while true reconnect now” loops
1.4 Service Lifecycle Constraints (Legacy OpenAPI page still useful)
- API service period shown as 1 year per application
- Potential automatic deactivation after prolonged inactivity (3+ months stated)
- Excessive request load may be blocked
Design implication: build monthly “service liveness check” ops task; never discover expiration during market open.
2) KR Market + Legal Constraints to Encode (Not Optional)
2.1 Session-Time Gating
For KRX equities, baseline windows (as summarized in 생활법령정보):
- Regular session: 09:00–15:30
- Pre-market after-hours window exists
- Post-close windows (including 단일가) exist up to 18:00
Engine impact:
- Strategy must declare allowed session types (
regular,pre,post_single, etc.) - Order-type whitelist must depend on session
- Scheduler should auto-close new entries near strategy-defined cutoff
2.2 Market Abuse Guardrails
Automated systems are still fully subject to 자본시장법 (e.g., 시세조종행위 금지, 제176조).
Practical controls for bots:
- No self-cross style behavior patterns
- No repeated quote/order patterns that can look manipulative
- Cancel/replace burst limits per symbol/time bucket
- Human review hooks for abnormal participation spikes
This must be represented as machine-enforced risk rules, not policy text only.
3) Vellab Reference Architecture for KIS Integration
3.1 Core Components
- Broker Adapter (
broker-kis)- REST client, WS client, auth/token manager
- TR-ID mapping + request builders
- Execution Orchestrator
- parent→child slicing, urgency policy, retry policy
- Risk Gateway
- pre-trade checks (session, max notional, max position, kill-switch state)
- Order State Store
- durable order intents + broker ack/fill events
- Reconciliation Worker
- periodic compare: local state vs broker state (orders, fills, positions, cash)
- Telemetry + Alerting
- latency, reject code distribution, limiter hits, reconnect count, stale stream age
3.2 Minimal Interface Contract
interface BrokerGateway {
placeOrder(intent: OrderIntent): Promise<BrokerAck>
cancelOrder(orderId: string): Promise<CancelAck>
replaceOrder(orderId: string, patch: ReplacePatch): Promise<ReplaceAck>
getOpenOrders(account: string): Promise<BrokerOrder[]>
getPositions(account: string): Promise<Position[]>
streamTicks(symbols: string[], onTick: (t: Tick) => void): Unsubscribe
}
Keep strategy code broker-agnostic. KIS-specific quirks stay in adapter layer.
3.3 Order Lifecycle State Machine
Recommended durable states:
INTENT_CREATED -> SUBMITTED -> ACKED -> PARTIAL_FILLED -> FILLED
with side branches:
REJECTED, CANCEL_PENDING -> CANCELED, EXPIRED, RECONCILE_REQUIRED
Never treat HTTP 200 as final fill truth.
4) Implementation Plan (Phased, Low-Blast-Radius)
Phase 0 — Connectivity + Auth Hardening
- token refresh manager (singleflight lock)
- strict rate limiter buckets (real/paper/token)
- structured error classification (retryable vs fatal)
- WS reconnect policy with backoff + breaker
Exit criteria: 1-week paper soak with zero runaway loops.
Phase 1 — Read-Only Reliability Layer
- account/position/order query endpoints integrated
- reconciliation snapshots persisted
- drift alarms when local != broker
Exit criteria: state drift MTTR < 5 min in test runs.
Phase 2 — Paper Trading Execution
- cash order + cancel path only
- conservative order types first (e.g., limit/market policy subset)
- full audit log per order decision
Exit criteria: 200+ paper orders, deterministic lifecycle integrity.
Phase 3 — Tiny Real Capital Pilot
- small symbol universe
- hard per-order / daily loss caps
- manual approval flag for strategy class changes
Exit criteria: two weeks without unresolved reconcile break.
Phase 4 — Controlled Ramp
- increase notional and symbol count gradually
- keep kill-switch drills scheduled (weekly)
- publish reliability dashboard (p95 ack latency, reject rate, stale-stream incidents)
5) KIS-Specific Engineering Checklist
- Account/appkey scoped REST limiter (20 rps real, 2 rps paper)
- Token limiter (1 rps)
- WS subscription budget tracker (<=41)
- WS anti-thrash reconnect controller
- Idempotency key for order intents (local)
- TR-ID mapping table with tests (real vs mock/paper variants)
- Pre-trade session validator (KR market windows)
- Compliance guards (anti-pattern detection for abusive order behavior)
- Reconciliation cron + auto-ticket creation on mismatch
- Kill-switch: strategy-level + global + account-level
6) Suggested First Vellab Backlog Tickets
feat(api): add broker gateway abstraction + persistence schemafeat(kis): oauth token manager + approval key managerfeat(kis): rate limiter buckets (real/paper/token)feat(kis-ws): resilient stream client with exponential backofffeat(exec): order intent state machine + event logfeat(risk): KR session gate + max loss/day + max order valuefeat(reconcile): broker-vs-local drift checkerfeat(obs): execution reliability dashboard panels
7) References
- KIS Developers intro: https://apiportal.koreainvestment.com/intro
- KIS Open Trading API repo: https://github.com/koreainvestment/open-trading-api
- KIS sample config (
kis_devlp.yaml) and auth code (kis_auth.py) in repo - KIS official notice API rate/session limits (post id):
d0d1a83f-6f8d-4437-9700-6d26702fd989- URL pattern:
/community/<forumId>/post/<postId>
- KIS official notice on websocket infinite-loop blocking:
4f34b068-3203-40fb-8936-c3bad5f154c0
- 한국투자증권 OpenAPI service guide page:
- 생활법령정보 (거래시간/원칙):
- 생활법령정보 (시세조종행위 금지):
One-line takeaway
For KIS live trading, your edge comes from execution reliability + compliance-safe automation discipline before model sophistication.