금융퀀트/(퀀트)증권사API활용(키움)
[키움API]python API로그인(Qt Designer 사용)
문송한투자자
2023. 11. 24. 05:51
반응형
mainform 띄우기
python 파일에서 Qt Designer로 만든 form을 띄우려면 PyQt5의 uic라는 라이브러리를 import 해 줘야 한다. form 파일의 경로를 지정하고, 그 경로를 이용해서 QMainWindow를 상속한 UI를 로드하는 클래스를 만들어 주면 된다. 이를 코드로 구현하면 아래와 같다.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QAxContainer import *
from PyQt5 import uic
#UI파일 연결
form_class = uic.loadUiType("UI 파일의 경로 입력")[0]
# PyQt5의 QMainWindow 클래스와 UI 폼 클래스를 상속받은 사용자 지정 클래스 정의
class KiwoomAPIform(QMainWindow, form_class):
def __init__(self):
# 부모 클래스의 초기화 메서드 호출
super().__init__()
# UI 폼을 현재 창에 설정
self.setupUi(self)
# 창의 제목 설정
self.setWindowTitle("KiwoomTest")
# 메인 코드
if __name__ == "__main__":
# PyQt5 어플리케이션 생성
app = QApplication(sys.argv)
# KiwoomAPIform 클래스의 인스턴스 생성
window = KiwoomAPIform()
# 창을 화면에 표시
window.show()
# 어플리케이션 실행 및 이벤트 루프 시작
sys.exit(app.exec_())
위 코드에 form_class 경로를 [키움API]python 메인 화면 만들기(Qt Designer 사용)에서 저장한 파일의 경로를 지정하면 해당 폼을 아래 그림과 같이 불러올 수 있다.
API로그인 구현하기
키움 API 로그인은 [키움API]python API 로그인에서 구현한 기능을 로그인 버튼에 붙여준다고 생각하면 된다. 로그인 버튼의 구성은 아래 그림과 같이 간단하게 나타낼 수 있다.
키움 API의 CommConnect 함수를 호출해서 로그인을 하고 OnEventConnect를 가져와서 결과를 확인하는 간단한 구조이다. 이를 코드로 나타내면 아래와 같다.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QAxContainer import *
from PyQt5 import uic
#UI파일 연결
form_class = uic.loadUiType("UI 파일의 경로 입력")[0]
# PyQt5의 QMainWindow 클래스와 UI 폼 클래스를 상속받은 사용자 지정 클래스 정의
class KiwoomAPIform(QMainWindow, form_class):
def __init__(self):
# 부모 클래스의 초기화 메서드 호출
super().__init__()
# UI 폼을 현재 창에 설정
self.setupUi(self)
# 창의 제목 설정
self.setWindowTitle("KiwoomTest")
# 키움 API Active X 호출
self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
# 로그인 버튼 클릭 시 작동 함수 정의(UI 생성시 오브젝트 명이 "btn_login"이어야 함)
self.btn_login.clicked.connect(self.btn_loginFunc)
# "btn_login"버튼 클릭시 호출되는 함수
def btn_loginFunc(self):
# 아래에서 정의한 CommConnect함수: 키움API로 "CommConnect()"요청을 하는 함수
self.CommConnect()
# OnEventConnect 이벤트 발생시 connect 를 통해서 호출되는 콜백 함수
def login_callback(err_code):
# 아래에서 정의한 ConnectEvent 함수: err_code를 받아서 문자로 반환
result = self.ConnectEvent(err_code)
# 아래에서 정의한 drawresult 함수: result 데이터를 받아서 화면 txt_result에 뿌림
self.drawresult(result)
# OnEventConnect 이벤트 발생시 connect 를 통해서 login_callback 호출
self.ocx.OnEventConnect.connect(login_callback)
# drawresult 함수
def drawresult(self, data: object):
# 화면에서 "txt_result"라는 오브젝트를 찾은 뒤 txt_result로 객체화
txt_result = self.findChild(QTextEdit, "txt_result")
# txt_result에 data를 받아서 data를 set 함
txt_result.setPlainText(str(data))
# CommConnect 함수
def CommConnect(self):
# 키움 API를 호출하여 CommConnect() 메소드 사용
self.ocx.dynamicCall("CommConnect()")
# Connect Event 함수
def ConnectEvent(self, err_code):
# 받은 err_code 가 0 일 때 "Login Success!!" 생성 그 외 "Login Failed"
if err_code == 0:
return "Login Success!!"
else:
return "Login Failed"
if __name__ == "__main__":
# PyQt5 어플리케이션 생성
app = QApplication(sys.argv)
# KiwoomAPIform 클래스의 인스턴스 생성
window = KiwoomAPIform()
# 창을 화면에 표시
window.show()
# 어플리케이션 실행 및 이벤트 루프 시작
sys.exit(app.exec_())
코드를 제대로 동작시키기 위해 가장 중요한 점은 Qt Designer 로 만든 UI를 불러오는 form_class의 경로가 정확해야 한다는 것이다. 그리고 화면상 텍스트 상자 객체는 txt_result라는 이름으로 버튼은 btn_login이라는 이름으로 정의되어 있어야 한다.
반응형