카테고리 없음

키움증권 REST API 쉽게 활용하기

herbtonic 2025. 5. 4. 10:12

지난 3월 19일 키움증권에서 REST API를 새롭게 Open했습니다. 기존 Open API는 COM으로만 제공되어 너무 답답했는데, 이제는 REST API를 통해 외부에서 자유롭게 호출이 가능합니다. 잠깐 둘러봤는데, 분봉차트는

틱범위 1:1분, 3:3분, 5:5분, 10:10분, 15:15분, 30:30분, 45:45분, 60:60분 으로 제공해 주고 있어요.

 

이번 포스트에서는 가볍게 Python으로 키움증권 Open API 사용하는 방법을 소개합니다. 

 

1. 키움 REST API 사용 신청

     키움증권 REST API 홈 ( 키움 REST API ) 에 접속 후 우측상단 API 사용신청을 클릭하신 후 약관 동의 후 신청하시면 됩니다.

 

     추가로, 계좌 APP Key 관리에서 본인 단말의 공인 IP를 추가해 주시면 됩니다.

 

     APP키와 Secret Key를 Down받아서 안전한 곳에 보관하시기 바랍니다.

 

2. 접근 Token 발급

     키움증권 API가이드 문서에 자세한 설명과 샘플코드가 잘 나와 있으니, 참고하시면 됩니다. 가이드에 따라 Access Token을 받아 보겠습니다. 아래 Sample 코드에 본인이 발급받은 App Key와 Secret Key를 입력하고 실행하면 Token을 받을 수 있습니다.

"단말기 인식 실패 오류" 발생할 경우 위에서 설명드린 대로 본인의 공인 IP를 추가해 주시면됩니다.

import requests
import json

# 접근토큰 발급
def fn_au10001(data):
# 1. 요청할 API URL
#host = 'https://mockapi.kiwoom.com' # 모의투자
host = 'https://api.kiwoom.com' # 실전투자
endpoint = '/oauth2/token'
url =  host + endpoint

# 2. header 데이터
headers = {
    'Content-Type': 'application/json;charset=UTF-8', # 컨텐츠타입
}

# 3. http POST 요청
response = requests.post(url, headers=headers, json=data)

# 4. 응답 상태 코드와 데이터 출력
print('Code:', response.status_code)
print('Header:', json.dumps({key: response.headers.get(key) for key in ['next-key', 'cont-yn', 'api-id']}, indent=4, ensure_ascii=False))
print('Body:', json.dumps(response.json(), indent=4, ensure_ascii=False))  # JSON 응답을 파싱하여 출력

# 실행 구간
if __name__ == '__main__':
# 1. 요청 데이터
params = {
    'grant_type': 'client_credentials',  # grant_type
    'appkey': '나의 App Key',  # 앱키
    'secretkey': '나의 Secret Key',  # 시크릿키
}

# 2. API 실행
fn_au10001(data=params)

 

 

3. 삼성전자 30분봉 차트 조회

키움증권 제공 Sample 코드에 위에서 발급받은 Access Token을 입력하고, params에 stk_cd : 005930, tic_scope : 30 으로 설정 후 실행합니다.

import requests
import json

# 주식분봉차트조회요청
def fn_ka10080(token, data, cont_yn='N', next_key=''):
# 1. 요청할 API URL
#host = 'https://mockapi.kiwoom.com' # 모의투자
host = 'https://api.kiwoom.com' # 실전투자
endpoint = '/api/dostk/chart'
url =  host + endpoint

# 2. header 데이터
headers = {
    'Content-Type': 'application/json;charset=UTF-8', # 컨텐츠타입
    'authorization': f'Bearer {token}', # 접근토큰
    'cont-yn': cont_yn, # 연속조회여부
    'next-key': next_key, # 연속조회키
    'api-id': 'ka10080', # TR명
}

# 3. http POST 요청
response = requests.post(url, headers=headers, json=data)

# 4. 응답 상태 코드와 데이터 출력
print('Code:', response.status_code)
print('Header:', json.dumps({key: response.headers.get(key) for key in ['next-key', 'cont-yn', 'api-id']}, indent=4, ensure_ascii=False))
print('Body:', json.dumps(response.json(), indent=4, ensure_ascii=False))  # JSON 응답을 파싱하여 출력

# 실행 구간
if __name__ == '__main__':
# 1. 토큰 설정
MY_ACCESS_TOKEN = '발급받은 Access Token'# 접근토큰

# 2. 요청 데이터
params = {
    'stk_cd': '005930', # 종목코드 거래소별 종목코드 (KRX:039490,NXT:039490_NX,SOR:039490_AL)
    'tic_scope': '30', # 틱범위 1:1분, 3:3분, 5:5분, 10:10분, 15:15분, 30:30분, 45:45분, 60:60분
    'upd_stkpc_tp': '1', # 수정주가구분 0 or 1
}

# 3. API 실행
fn_ka10080(token=MY_ACCESS_TOKEN, data=params)

# next-key, cont-yn 값이 있을 경우
# fn_ka10080(token=MY_ACCESS_TOKEN, data=params, cont_yn='Y', next_key='nextkey..')

 

 

아래와 같은 JSON Response를 받아오는 것을 확인합니다.

{
    "cur_prc": "+53300",
    "trde_qty": "2768537",
    "cntr_tm": "20250204093000",
    "open_pric": "+53200",
    "high_pric": "+53500",
    "low_pric": "+53100",
    "upd_stkpc_tp": "",
    "upd_rt": "",
    "bic_inds_tp": "",
    "sm_inds_tp": "",
    "stk_infr": "",
    "upd_stkpc_event": "",
    "pred_close_pric": ""
},
{
    "cur_prc": "+53200",
    "trde_qty": "9768260",
    "cntr_tm": "20250204090000",
    "open_pric": "+51600",
    "high_pric": "+53500",
    "low_pric": "+51500",
    "upd_stkpc_tp": "",
    "upd_rt": "",
    "bic_inds_tp": "",
    "sm_inds_tp": "",
    "stk_infr": "",
    "upd_stkpc_event": "",
    "pred_close_pric": ""
},
{
    "cur_prc": "-51000",
    "trde_qty": "1941011",
    "cntr_tm": "20250203153000",
    "open_pric": "-51000",
    "high_pric": "-51000",
    "low_pric": "-51000",
    "upd_stkpc_tp": "",
    "upd_rt": "",
    "bic_inds_tp": "",
    "sm_inds_tp": "",
    "stk_infr": "",
    "upd_stkpc_event": "",
    "pred_close_pric": ""
},