API Reference
kiwoom
Bot
Kiwoom REST API를 이용해 전략을 실행하는 최상위 클래스입니다.
사용자가 API 세부 동작을 알지 못해도 전략 수행에 집중할 수 있도록 합니다.
Source code in kiwoom/bot.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
api
instance-attribute
api = api if api else API(host, appkey, secretkey)
debug
debug(debugging=True)
디버깅 모드 활성화 / 비활성화. 디버깅 모드에서는 Http 요청과 응답이 출력됩니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
debugging
|
bool
|
디버깅 모드 활성화 여부 |
True
|
Source code in kiwoom/bot.py
52 53 54 55 56 57 58 59 60 | |
token
token()
연결이 되었다면, 키움 REST API 토큰을 반환합니다.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
token |
Source code in kiwoom/bot.py
62 63 64 65 66 67 68 69 | |
connect
async
connect()
키움 REST API HTTP 서버 및 Websocket 서버에 접속합니다.
Source code in kiwoom/bot.py
71 72 73 74 75 76 | |
close
async
close()
키움 REST API HTTP 서버 및 Websocket 서버 연결을 해제합니다.
Source code in kiwoom/bot.py
78 79 80 81 82 | |
stock_list
async
stock_list(market, ats=True)
주어진 market 코드에 해당하는 주식 종목코드 목록을 반환합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
market
|
str
|
{ 'KOSPI': '0', 'KOSDAQ': '10', 'ELW': '3', '뮤추얼펀드': '4', '신주인수권': '5', '리츠': '6', 'ETF': '8', '하이일드펀드': '9', 'K-OTC': '30', 'KONEX': '50', 'ETN': '60', 'NXT': 'NXT'} |
required |
ats
|
bool
|
대체거래소 반영한 통합코드 여부 (ex. '005930_AL') |
True
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: 종목코드 리스트 |
Source code in kiwoom/bot.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
sector_list
async
sector_list(market)
주어진 market 코드에 해당하는 업종코드 목록을 반환합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
market
|
str
|
{ '0': 'KOSPI', '1': 'KOSDAQ', '2': 'KOSPI200', '4': 'KOSPI100(150)', '7': 'KRX100'} |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: 업종코드 리스트 |
Source code in kiwoom/bot.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
candle
async
candle(code, period, ctype, start=None, end=None)
주어진 코드, 기간, 종목/업종 유형에 해당하는 캔들차트 데이터를 반환합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
종목코드 / 업종코드 |
required |
period
|
str
|
캔들 기간유형 {"tick", "min", "day"} |
required |
ctype
|
str
|
종목 / 업종유형 {"stock", "sector"} |
required |
start
|
str
|
시작일자 in YYYYMMDD format |
None
|
end
|
str
|
종료일자 in YYYYMMDD format |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame |
DataFrame
|
Pandas 캔들차트 데이터프레임 |
Source code in kiwoom/bot.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
trade
async
trade(start, end='')
주어진 시작일자와 종료일자에 해당하는 체결내역을 키움증권 '0343' 계좌 체결내역 화면과 동일한 구성으로 반환합니다. 데이터 조회 제한으로 최근 2개월 데이터만 조회할 수 있습니다.
체결내역 데이터는 알파노트를 통해 간편하게 진입/청산 시각화 및 성과 지표들을 확인할 수 있습니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str
|
시작일자 in YYYYMMDD format |
required |
end
|
str
|
종료일자 in YYYYMMDD format |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
DataFrame |
DataFrame
|
키움증권 '0343' 화면 'Excel 내보내기' 형식 |
Source code in kiwoom/bot.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
run
async
run()
전략 로직을 구현하고 실행합니다.
Source code in kiwoom/bot.py
173 174 175 176 177 | |
API
Bases: Client
Kiwoom REST API 서버와 직접 요청과 응답을 주고받는 클래스입니다.
데이터 조회, 주문 요청 등 저수준 통신을 담당하며, 직접 API 스펙을 구현하여 활용합니다.
Source code in kiwoom/api.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
queue
instance-attribute
queue = Queue(maxsize=WEBSOCKET_QUEUE_MAX_SIZE)
socket
instance-attribute
socket = Socket(url=wss_url, queue=queue)
connect
async
connect()
키움 REST API HTTP 서버와 Websocket 서버에 접속하고 토큰을 발급받습니다.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
토큰을 발급받지 못한 경우 |
Exception
|
예상하지 못한 에러 |
Source code in kiwoom/api.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | |
close
async
close()
키움 REST API 서버와 연결을 해제하고 리소스를 정리합니다.
Source code in kiwoom/api.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
stock_list
async
stock_list(market)
주어진 market 코드에 대해 'ka10099' API 요청을 하고 응답을 반환합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
market
|
str
|
조회할 주식 시장코드 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
종목코드 목록이 없을 경우 |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
종목코드 목록을 포함하는 응답 |
Source code in kiwoom/api.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | |
sector_list
async
sector_list(market)
주어진 market 코드에 대해 'ka10101' API 요청을 하고 응답을 반환합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
market
|
str
|
조회할 주식 시장코드 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
업종코드 목록이 없을 경우 |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
업종코드 목록을 포함하는 응답 |
Source code in kiwoom/api.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
candle
async
candle(code, period, ctype, start=None, end=None)
주어진 코드, 기간, 종목/업종 유형에 해당하는 API 요청을 하고 응답을 반환합니다.
"stock": {"tick": "ka10079", "min": "ka10080", "day": "ka10081"}
"sector": {"tick": "ka20004", "min": "ka20005", "day": "ka20006"}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
종목코드 / 업종코드 |
required |
period
|
str
|
캔들 기간유형, {"tick", "min", "day"}. |
required |
ctype
|
str
|
종목 / 업종 유형, {"stock", "sector"}. |
required |
start
|
str
|
시작일자 in YYYYMMDD format. |
None
|
end
|
str
|
종료일자 in YYYYMMDD format. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
유효하지 않은 'ctype' 또는 'period' |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
캔들 데이터를 포함하는 json 응답 |
Source code in kiwoom/api.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
trade
async
trade(start, end='')
주어진 시작일자와 종료일자에 해당하는 체결내역을 키움증권 '0343' 계좌 체결내역 화면과 동일한 구성으로 반환합니다. 데이터 조회 제한으로 최근 2개월 데이터만 조회할 수 있습니다.
체결내역 데이터는 알파노트를 통해 간편하게 진입/청산 시각화 및 성과 지표들을 확인할 수 있습니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
str
|
시작일자 in YYYYMMDD format |
required |
end
|
str
|
종료일자 in YYYYMMDD format |
''
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
list[dict]: 체결내역 데이터를 포함하는 json 응답 리스트 |
Source code in kiwoom/api.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | |
add_callback_on_real_data
add_callback_on_real_data(real_type, callback)
실시간 데이터 수신 시 호출될 콜백 함수를 추가합니다. (trnm이 'REAL'인 경우)
- callback 함수는 서버 응답 string 그대로를 인자로 받습니다.
- real_type을 'PING' 또는 'LOGIN'으로 설정하면 기본 콜백 함수를 덮어씁니다.
콜백 함수는 비동기 콜백 함수를 추가하는 것을 권장합니다. 비동기 및 동기 콜백 함수 모두 루프를 블로킹하지 않도록 백그라운드에서 실행됩니다. 따라서 데이터 처리 완료 순서가 반드시 데이터 수신 순서에 따라 실행되지 않을 수 있습니다.
ex) tick 체결 데이터 (type 'OB')가 수신될 때마다 데이터 출력하기
> fn = lambda raw: print(raw)
> add_callback_on_real_data(real_type='OB', callback=fn)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
real_type
|
str
|
키움 REST API에 정의된 실시간 데이터 타입 |
required |
callback
|
Callable
|
raw 스트링을 인자로 받는 콜백 함수 |
required |
Source code in kiwoom/api.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
register_tick
async
register_tick(grp_no, codes, refresh='1')
주어진 그룹번호와 종목 코드에 대해 주식체결 데이터를 등록합니다. (타입 '0B')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grp_no
|
str
|
그룹번호 |
required |
codes
|
list[str]
|
종목코드 리스트 |
required |
refresh
|
str
|
기존등록유지여부 (기존유지:'1', 신규등록:'0'). |
'1'
|
Source code in kiwoom/api.py
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |
register_hoga
async
register_hoga(grp_no, codes, refresh='1')
주어진 그룹번호와 종목 코드에 대해 주식호가잔량 데이터를 등록합니다. (타입 '0D')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grp_no
|
str
|
그룹번호 |
required |
codes
|
list[str]
|
종목코드 리스트 |
required |
refresh
|
str
|
기존등록유지여부 (기존유지:'1', 신규등록:'0'). |
'1'
|
Source code in kiwoom/api.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | |
remove_register
async
remove_register(grp_no, codes, type)
주어진 그룹번호와 실시간 데이터 타입에 대해 등록된 데이터를 제거합니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grp_no
|
str
|
그룹번호 |
required |
type
|
str | list[str]
|
실시간 데이터 타입 ex) '0B', '0D', 'DD' |
required |
Source code in kiwoom/api.py
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
http
Client
Source code in kiwoom/http/client.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
host
instance-attribute
host = host
debugging
instance-attribute
debugging = False
connect
async
connect(appkey, secretkey)
Connect to Kiwoom REST API server and receive token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
appkey
|
str
|
file path or raw appkey |
required |
secretkey
|
str
|
file path or raw secretkey |
required |
Source code in kiwoom/http/client.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
close
async
close()
Close HTTP session.
Source code in kiwoom/http/client.py
105 106 107 108 109 110 111 112 113 114 | |
token
token()
Returns token if available, otherwise empty string.
Raises:
| Type | Description |
|---|---|
ValueError
|
Invalid token. |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
token |
Source code in kiwoom/http/client.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
headers
headers(api_id, cont_yn='N', next_key='', headers=None)
Generate headers for the request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_id
|
str
|
api_id in Kiwoom API |
required |
cont_yn
|
str
|
cont_yn in Kiwoom API |
'N'
|
next_key
|
str
|
next_key in Kiwoom API |
''
|
headers
|
dict | None
|
headers to be updated with |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: headers |
Source code in kiwoom/http/client.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
ready
async
ready()
Wait until request limit is lifted and connection is established.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Connection timeout. |
Source code in kiwoom/http/client.py
159 160 161 162 163 164 165 166 167 168 169 170 171 | |
post
async
post(endpoint, api_id, headers=None, data=None)
Post request to the server, but using client.request function is recommended. Request limit and connection status are checked globally and automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
endpoint to Kiwoom REST API server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. |
None
|
data
|
dict | None
|
data to be sent in json format |
None
|
Returns:
| Type | Description |
|---|---|
ClientResponse
|
aiohttp.ClientResponse: async response from the server, but this will be converted to kiwoom.http.response.Response by debugger. |
Source code in kiwoom/http/client.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
request
async
request(endpoint, api_id, headers=None, data=None)
Requests to the server and returns response with error handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
endpoint of the server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. Defaults to None. |
None
|
data
|
dict | None
|
data of the request. Defaults to None. |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
RuntimeError when return_code is not in [0, 3, 20] |
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
response wrapped by kiwoom.http.response.Response |
Source code in kiwoom/http/client.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
request_until
async
request_until(should_continue, endpoint, api_id, headers=None, data=None)
Request until 'cont-yn' in response header is 'Y', and should_continue(body) evaluates to True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
should_continue
|
Callable
|
callable that takes body(dict) and returns boolean value to request again or not |
required |
endpoint
|
str
|
endpoint of the server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. Defaults to None. |
None
|
data
|
dict | None
|
data of the request. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
response body |
Source code in kiwoom/http/client.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
Response
Response wrapper for aiohttp.ClientResponse
Source code in kiwoom/http/response.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
url
instance-attribute
url = url
status
instance-attribute
status = status
headers
instance-attribute
headers = headers
body
instance-attribute
body = body
json
json()
Returns already parsed body.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
body in json format |
Source code in kiwoom/http/response.py
22 23 24 25 26 27 28 29 | |
Socket
Source code in kiwoom/http/socket.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
REAL
class-attribute
instance-attribute
REAL = 'wss://api.kiwoom.com:10000'
MOCK
class-attribute
instance-attribute
MOCK = 'wss://mockapi.kiwoom.com:10000'
ENDPOINT
class-attribute
instance-attribute
ENDPOINT = '/api/dostk/websocket'
url
instance-attribute
url = url
connect
async
connect(session, token)
Connect to Kiwoom websocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
ClientSession
|
aiohttp ClientSession from API.connect() |
required |
token
|
str
|
token for authentication |
required |
Source code in kiwoom/http/socket.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
close
async
close()
Close the websocket and the task.
Source code in kiwoom/http/socket.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
send
async
send(msg)
Send data to Kiwoom websocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str | dict
|
msg should be in json format |
required |
Source code in kiwoom/http/socket.py
91 92 93 94 95 96 97 98 99 100 101 | |
recv
async
recv()
Receive data from Kiwoom websocket server and return data. If message type is not str, close the websocket and raise RuntimeError.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Websocket Connection Error |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
received json formatted data from websocket |
Source code in kiwoom/http/socket.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
run
async
run()
Receive data from websocket and put data to the queue. If WEBSOCKET_QUEUE_MAX_SIZE is set and queue gets full, then backpressure will be applied to the websocket. Run this task in background with asyncio.create_task().
Source code in kiwoom/http/socket.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
client
Client
Source code in kiwoom/http/client.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
host
instance-attribute
host = host
debugging
instance-attribute
debugging = False
connect
async
connect(appkey, secretkey)
Connect to Kiwoom REST API server and receive token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
appkey
|
str
|
file path or raw appkey |
required |
secretkey
|
str
|
file path or raw secretkey |
required |
Source code in kiwoom/http/client.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
close
async
close()
Close HTTP session.
Source code in kiwoom/http/client.py
105 106 107 108 109 110 111 112 113 114 | |
token
token()
Returns token if available, otherwise empty string.
Raises:
| Type | Description |
|---|---|
ValueError
|
Invalid token. |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
token |
Source code in kiwoom/http/client.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
headers
headers(api_id, cont_yn='N', next_key='', headers=None)
Generate headers for the request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_id
|
str
|
api_id in Kiwoom API |
required |
cont_yn
|
str
|
cont_yn in Kiwoom API |
'N'
|
next_key
|
str
|
next_key in Kiwoom API |
''
|
headers
|
dict | None
|
headers to be updated with |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
dict[str, str]: headers |
Source code in kiwoom/http/client.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
ready
async
ready()
Wait until request limit is lifted and connection is established.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Connection timeout. |
Source code in kiwoom/http/client.py
159 160 161 162 163 164 165 166 167 168 169 170 171 | |
post
async
post(endpoint, api_id, headers=None, data=None)
Post request to the server, but using client.request function is recommended. Request limit and connection status are checked globally and automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
endpoint to Kiwoom REST API server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. |
None
|
data
|
dict | None
|
data to be sent in json format |
None
|
Returns:
| Type | Description |
|---|---|
ClientResponse
|
aiohttp.ClientResponse: async response from the server, but this will be converted to kiwoom.http.response.Response by debugger. |
Source code in kiwoom/http/client.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
request
async
request(endpoint, api_id, headers=None, data=None)
Requests to the server and returns response with error handling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
endpoint of the server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. Defaults to None. |
None
|
data
|
dict | None
|
data of the request. Defaults to None. |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
RuntimeError when return_code is not in [0, 3, 20] |
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
response wrapped by kiwoom.http.response.Response |
Source code in kiwoom/http/client.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
request_until
async
request_until(should_continue, endpoint, api_id, headers=None, data=None)
Request until 'cont-yn' in response header is 'Y', and should_continue(body) evaluates to True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
should_continue
|
Callable
|
callable that takes body(dict) and returns boolean value to request again or not |
required |
endpoint
|
str
|
endpoint of the server |
required |
api_id
|
str
|
api id |
required |
headers
|
dict | None
|
headers of the request. Defaults to None. |
None
|
data
|
dict | None
|
data of the request. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
response body |
Source code in kiwoom/http/client.py
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
debug
dumps
dumps(api, endpoint, api_id, headers, data, res)
Dump request and response to string for debugging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api
|
Client
|
Client instance |
required |
endpoint
|
str
|
endpoint |
required |
api_id
|
str
|
api id |
required |
headers
|
dict
|
headers |
required |
data
|
dict
|
data |
required |
res
|
Response
|
wrapped response |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
description |
Source code in kiwoom/http/debug.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
debugger
debugger(fn)
Debugger decorator for Client.post method. Even though debugging is disabled, it will print if error occurs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
function
|
function to be decorated |
required |
Raises:
| Type | Description |
|---|---|
err
|
propagate HTTPException from original function |
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Callable
|
wrapped response |
Source code in kiwoom/http/debug.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
response
Response
Response wrapper for aiohttp.ClientResponse
Source code in kiwoom/http/response.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
url
instance-attribute
url = url
status
instance-attribute
status = status
headers
instance-attribute
headers = headers
body
instance-attribute
body = body
json
json()
Returns already parsed body.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
body in json format |
Source code in kiwoom/http/response.py
22 23 24 25 26 27 28 29 | |
socket
Socket
Source code in kiwoom/http/socket.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
REAL
class-attribute
instance-attribute
REAL = 'wss://api.kiwoom.com:10000'
MOCK
class-attribute
instance-attribute
MOCK = 'wss://mockapi.kiwoom.com:10000'
ENDPOINT
class-attribute
instance-attribute
ENDPOINT = '/api/dostk/websocket'
url
instance-attribute
url = url
connect
async
connect(session, token)
Connect to Kiwoom websocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
ClientSession
|
aiohttp ClientSession from API.connect() |
required |
token
|
str
|
token for authentication |
required |
Source code in kiwoom/http/socket.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
close
async
close()
Close the websocket and the task.
Source code in kiwoom/http/socket.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
send
async
send(msg)
Send data to Kiwoom websocket server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg
|
str | dict
|
msg should be in json format |
required |
Source code in kiwoom/http/socket.py
91 92 93 94 95 96 97 98 99 100 101 | |
recv
async
recv()
Receive data from Kiwoom websocket server and return data. If message type is not str, close the websocket and raise RuntimeError.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Websocket Connection Error |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
received json formatted data from websocket |
Source code in kiwoom/http/socket.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
run
async
run()
Receive data from websocket and put data to the queue. If WEBSOCKET_QUEUE_MAX_SIZE is set and queue gets full, then backpressure will be applied to the websocket. Run this task in background with asyncio.create_task().
Source code in kiwoom/http/socket.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
utils
RateLimiter
Source code in kiwoom/http/utils.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
acquire
async
acquire()
Source code in kiwoom/http/utils.py
23 24 25 26 27 28 29 30 31 32 | |
wrap_async_callback
wrap_async_callback(semaphore, callback)
Wrap async callback to run in async context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
semaphore
|
Semaphore
|
semaphore to limit the number of callbacks |
required |
callback
|
Callable
|
callback to be wrapped |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
wrapped callback |
Source code in kiwoom/http/utils.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
wrap_sync_callback
wrap_sync_callback(semaphore, callback)
Wrap sync callback to run in async context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
semaphore
|
Semaphore
|
semaphore to limit the number of callbacks |
required |
callback
|
Callable
|
callback to be wrapped |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
wrapped callback |
Source code in kiwoom/http/utils.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
cancel
async
cancel(task)
Cancel a task if it exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
Task | None
|
task to be cancelled |
required |
Source code in kiwoom/http/utils.py
73 74 75 76 77 78 79 80 81 82 83 | |