본문 바로가기
파이썬 & 키움API/파이썬 키움API 설정 팁

키움api 계좌정보 가져오기

by mybutiworld 2025. 1. 25.
반응형

import win32com.client
import time

# 키움 OpenAPI+를 Python에 연결
class Kiwoom:
    def __init__(self):
        self.ocx = win32com.client.Dispatch("KHOPENAPI.KHOpenAPICtrl.1")
        self.ocx.OnEventConnect = self._handler_login

    def comm_connect(self):
        self.ocx.CommConnect()
        while self.ocx.GetConnectState() == 0:
            time.sleep(1)

    def _handler_login(self, err_code):
        if err_code == 0:
            print("로그인 성공")
        else:
            print("로그인 실패")

    # 계좌 정보 가져오기
    def get_account_info(self):
        account_list = self.ocx.GetLoginInfo("ACCNO")
        accounts = account_list.split(';')[:-1]  # 마지막 ; 제거
        return accounts

# 인스턴스 생성 및 로그인 실행
kiwoom = Kiwoom()
kiwoom.comm_connect()

# 계좌 정보 가져오기
accounts = kiwoom.get_account_info()
print("연결된 계좌 목록:", accounts)

반응형