[파이썬 / 증권사 API활용](7) 조건식 불러오기
난 애초에 조건식을 확인하려고 했을때 키움API에서 조건식 등록도 가능한 것으로 알고 있었다.
그런데 알고보니 조건식은 키움 HTS에서 직접 등록을 하고
OpenAPI에서는 그에 따른 조건식을 가져오고 결과를 불러오는 것만 존재하는 것으로 보인다. (결국 내 오해..)
그럼 조건식 가져오기 위한 OpenAPI 함수를 한번 보면 다음과 같다.
GetConditionLoad() 함수는 HTS 계좌 정보에 저장된 사용자 조건검색을 요청하는 함수다.
요청이 성공되면 발생되는 이벤트 함수가 OnReceiveConditionVer() 함수다.
GetConditionNameList() 함수는 설명에도 나와 있지만 조건식의 고유번호, 조건식 이름을 한쌍으로 문자열을 제공한다.
그리고 이 함수는 OnReceiveConditionVer() 이벤트에서 사용을 해야한다.
이어서 SendCondition() 함수는 조건 검색에서의 결과값 요청하는 함수이다.
SendCondition() 함수에 결과로 OnReceiveCondition() 이벤트가 발생하고 이로 조건 검색의 결과값을 확인할 수 있다.
그럼 먼저 Kiwoom.py 코드를 보자.
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QAxContainer import *
import pythoncom
class OpenApi:
def __init__(self):
self.woom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
self.woom.OnEventConnect.connect(self.OnEventConnect)
self.woom.OnReceiveTrData.connect(self.OnReceiveTrData)
self.woom.OnReceiveConditionVer.connect(self.OnReceiveConditionVer)
self.woom.OnReceiveRealCondition.connect(self.OnReceiveRealCondition)
self.woom.OnReceiveTrCondition.connect(self.OnReceiveTrCondition)
self.login = False
self.tr = False
self.kospiCodeList = []
self.kospiNameList = []
def CommConnect(self):
self.woom.dynamicCall("CommConnect()")
self.login_loop = QEventLoop()
self.login_loop.exec()
# self.woom.dynamicCall("KOA_Functions(QString, QString)", "ShowAccountWindow", "")
def OnEventConnect(self, err_code):
print("Connect = OK")
self.login_loop.exit()
def GetMasterCodeName(self, code):
name = self.woom.dynamicCall("GetMasterCodeName(QString)", code)
return name
def GetCodeListByMarket(self, market):
codelist = self.woom.dynamicCall("GetCodeListByMarket(QString)", market)
return codelist
def SetInputValue(self, id, value):
self.woom.dynamicCall("SetInputValue(QString, QString)", id, value)
def CommRqData(self, rqname, trcode, next, screen):
self.tr = False
self.woom.dynamicCall("CommRqData(QString, QString, int, QString)", rqname, trcode, next, screen)
while self.tr is False:
pythoncom.PumpWaitingMessages()
def GetCommData(self, trcode, record, index, item):
data = self.woom.dynamicCall("GetCommData(QString, QString, int, QString)", trcode, record, index, item)
return data.strip()
def OnReceiveTrData(self, screen, rqname, trcode, record, next):
print(screen, rqname, trcode, record, next)
self.tr = True
name = self.GetCommData(trcode, record, next, "종목명")
sPrice = self.GetCommData(trcode, record, next, "시가")
nPrice = self.GetCommData(trcode, record, next, "현재가")
volume = self.GetCommData(trcode, record, next, "거래량")
print("종목명 : ", name)
print("시가 : ", sPrice)
print("현재가 : ", nPrice)
print("거래량 : ", volume)
def GetConditionLoad(self):
self.woom.dynamicCall("GetConditionLoad()")
self.login_loop = QEventLoop()
self.login_loop.exec()
def GetConditionNameList(self):
data = self.woom.dynamicCall("GetConditionNameList()")
conditions = data.split(';')[:-1]
for condition in conditions:
index, name = condition.split('^')
print(index, name)
def SendCondition(self, screen, condName, condIndex, search):
ret = self.woom.dynamicCall("SendCondition(QString, QString, int, int)", screen, condName, condIndex, search)
self.login_loop = QEventLoop()
self.login_loop.exec()
def OnReceiveConditionVer(self, ret, msg):
print(ret, msg)
data = self.woom.dynamicCall("GetConditionNameList()")
conditions = data.split(';')[:-1]
for condition in conditions:
index, name = condition.split('^')
print(index, name)
self.login_loop.exit()
def OnReceiveRealCondition(self, code, type, condName, condIndex):
print(condName, code, type)
def OnReceiveTrCondition(self, screen, code, condName, next):
codeList = code.split(';')
for result in codeList:
print(result)
self.login_loop.exit()
def GetAllCodeName(self):
self.kospiCodeList = self.GetCodeListByMarket(0)
self.kospiCodeList = self.kospiCodeList.split(';')
self.kospiNameList = []
for code in self.kospiCodeList:
name = self.GetMasterCodeName(code)
self.kospiNameList.append(code + " : " + name)
for item in self.kospiNameList:
print(item)
self.login_loop 관련 메소드들의 경우 서버로 요청 함수를 보내고 기다리지 않고 다음 요청을 다시 하면 Receive 이벤트들이 들어오지 않아서 확인을 위해서 일단 작성했는데 추후에는 다른 방법으로 수정을 해야할 것 같다.
이번에는 실행파일인 Stock.py 코드를 보자.
import sys
from PyQt5.QtWidgets import *
from Kiwoom import OpenApi
import pythoncom
class App(QWidget):
def __init__(self):
super().__init__()
kiwoom = OpenApi()
kiwoom.CommConnect()
kiwoom.GetAllCodeName()
kiwoom.SetInputValue("종목코드", "005930")
kiwoom.CommRqData("opt10001", "opt10001", 0, "0101")
kiwoom.GetConditionLoad()
kiwoom.SendCondition("0150", "A", 0, 0)
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = App()
# app.exec_()
그럼 결과를 보자.
결과를 보듯이 종목 코드로 숫자가 길게 나온다.
이제 코드를 이용해서 구매를 진행하면 기본적인 자동 구매 요청은 될 것 같다.
근데 조건식은 어떤 걸 이용하지?? ㅎㅎㅎ