[Kium OPEN API] receive stock data

Objective: Reference books that receive stock prices through Kiwoom OPEN API: We have created a program that receives stock prices through the Python stock automatic trading system Kium OPAN API, which is easily copied.The book was coded as it is, and the basic concepts of methods and APITR that appear in the middle were organized through search.The photo below is the final version (of course I plan to code more) and I cut the source code for each method and added an explanationObjective: Reference books that receive stock prices through Kiwoom OPEN API: We have created a program that receives stock prices through the Python stock automatic trading system Kium OPAN API, which is easily copied.The book was coded as it is, and the basic concepts of methods and APITR that appear in the middle were organized through search.The photo below is the final version (of course I plan to code more) and I cut the source code for each method and added an explanationSource Code Description by Methodfrom PyQt5。PyQt5 から Import QAxContainer*.QtWid is imported from PyQt5 * Obtain the .QtCore Import *Import panda as pd import timefrom PyQt5。PyQt5 から Import QAxContainer*.QtWid is imported from PyQt5 * Obtain the .QtCore Import *Import panda as pd import timefrom PyQt5。PyQt5 から Import QAxContainer*.QtWid is imported from PyQt5 * Obtain the .QtCore Import *Import panda as pd import timeclass Kiwidget—The class name is inherited by # class name is Kiwidget.At this time, QAxWidget is connected to the OPEN API.default_init_(s)#QAxWidget_()#QAxWidget_().The QoS for using the QAxWidget_config to call the default_config to call the command (a) the first_ set_set_set_s).set_ac count_number () # account number () # account number.tr_event_loop = QEventLoop()class Kiwoom(QAxWidget): #The class name is Kiwoom and inherits a class called QAxWidget. At this time, the QAxWidget should be connected so that the OPEN API can be used.def__init__(self):initialize super().__init__()#QAxWidget. QAxWidget Ready to Use Self._make_kiwoom_instance()self._set_signal_slots() #Self calling the slot function responsible for handling responses to multiple requests sent by API._comm_connect()#, so you can use it only by calling it. =>>>>>>>><<<<<<<<{\{\{\{\f}}{\{\f}}{\f}}}}{\fnfnfN.get_account_number() #account number save self.tr_event_loop = QEventLoop()def_make_kiwoom_instance(self)—A function self that registers the Kiwoom class so that it can use the API.setControl(“KHOPENAPI.KHOpenAPICtrl.1”) #setControl function is defined in the QAxWidget class inherited when creating the Kiwoom class, and the QAxWidget is included in the PyQt5.QAxContainerdef_make_kiwoom_instance(self)—A function self that registers the Kiwoom class so that it can use the API.setControl(“KHOPENAPI.KHOpenAPICtrl.1”) #setControl function is defined in the QAxWidget class inherited when creating the Kiwoom class, and the QAxWidget is included in the PyQt5.QAxContainerdef_set_signal_slots(self)—A function self that receives requests to send to the #API and registers all slots.OnEventConnect.connect(self._login_slot)#Set_login_slot to receive a response to the login attempt result.On Receive TrData.connect(self._on_receive_tr_data)#Meaning to call the _on_receive_tr_data function when TR query is successful2.In fact, the program does not know when the event will occur, so it is necessary to check if it will continue to occur, but it is generally said that it implements a listener.In 1.CommConnect() below, CommConnect() will generate an OnEventConnect event.The client can provide a client with QAxWidget.AxWidget instance is connected to the QAxWidget instance and the method of operation.If you see the above diagram, the OnEventConnect event is generated in another section of the command, the event will succeed, if the return value of the event.And then the return value to the OnEventConnect.conf.conf.conf.conf._login_slot.def_login_slot(self, err_code):#function iferr_code == to get a response to the login attempt result 0:print(“connected”)else:print(“not connected”)self.login_event_loop.exit() #Waiting for response to login attempt results3. If the OnEventConnect event conversion value mentioned in 2. on the function to obtain a response to the login attempt and enter a value of 0 or negative in err_code, the if statement is used to distinguish whether the login is successful (“not connected”)/failure (“not connected”)default_config_connect (e.g.cfg) After sending a response to the response waiting for the response waiting for the response.Telf, sends a request for login_start_start_start_start_start_start_start_start_logging attempts_login_logCommConnect()The note says “OnEventConnect event occurs if login is successful or unsuccessful”.If “Return Value: 0 – Success, Negative Value Failed” is the result of the dynamic call itself, then the event can be seen as the result of the method execution.Therefore, if the login window is executed through the above method (CommConnect), the event will not occur unless you proceed further.defget_account_number(self, tag=”)ACCNO”): account_list = self.dynamicCall(“GetLoginInfo(QSTring)”, tag) account_number = account_list.split(‘;´) [0][0]print(account_list)return account_numberdefget_account_number(self, tag=”)ACCNO”): account_list = self.dynamicCall(“GetLoginInfo(QSTring)”, tag) account_number = account_list.split(‘;´) [0][0]print(account_list)return account_numberdefget_code_list_by_market(self、market_type): # 시장 내 종목 코드를 얻어오는 함수 code_list = self.dynamicCall(“GetCodeListByMarket(QSTring)”, market_type) code_list = code_list.split(‘;’)[:-1]return code_listdefget_code_list_by_market(self、market_type): # 시장 내 종목 코드를 얻어오는 함수 code_list = self.dynamicCall(“GetCodeListByMarket(QSTring)”, market_type) code_list = code_list.split(‘;’)[:-1]return code_listdefget_master_code_name(self, code): # 종목 코드를 받아 종목명을 반환하는 함수 code_name = self.dynamicCall(“GetMasterCodeName(QSTring)”, code) returns code_namedefget_master_code_name(self, code): # 종목 코드를 받아 종목명을 반환하는 함수 code_name = self.dynamicCall(“GetMasterCodeName(QSTring)”, code) returns code_namedef get_price_data(self, code): self。dynamicCall(“SetInputValue(QSting, QSting)”, “종목코드”, code) self。dynamicCall(“SetInputValue(QSting, QSting)”, “수정주가구분”, “1”) self。dynamicCall(“CommRqData(QSting, QString, int, QString)”,”opt10081_req”, “opt10081”, 0, “0001”) self.Code of code when sending TR requests using tr_device_() # command to the response standby state.exe_() # command.After receiving response to TR ohlcv = self.tr _data while self.has_next_tr_data:self。dynamicCall(“SetInputValue(QString, QString)”, “종목코드”, code) self。dynamicCall(“SetInputValue(QString, QString)”, “수정주가구분”, “1”) self。dynamicCall(“CommRqData(QString, QString, int, QString)”, “opt10081_req”, “opt10081”, 2, “0001”) self.tr_event_loop.exec_()for key, val in self.tr_data.items(): ohlcv[key][-1:] = = val df = pd.DataFrame(ohlcv, columns=[‘open’, ‘high’, ‘low’, ‘close’, ‘volume’], index=ohlcv[‘date’])return df[::-1]4. TR realization (opt10081)In order to transfer the TR Transaction (TR) to Kiwoom Securities’ API server, two methods must be used – SetInputValue specifying attributes – and request CommRqData, which transmits TR to the server with a specified value.When interpreting the above, the dynamic value set method for the dialing event that is read throughout the data that is read-CoS. to read the Transaction method.When you see KACE, you must configure a brand code before calling the opt10081 for the following.Therefore, you configure the Editem and value is set to describe the Editem and value.defget_price_data(self, code): self.dynamicCall(“SetInputValue(QSTing, QSTing)”, “종목코드”, code) self.dynamicCall(“SetInputValue(QSTing, QSting)”, “수정주가구분”, “1”) self.dynamicCall(“CommRqData(QSTing, QSTring、QSTing、QSTring、QSTr、QTR、QTR、IntThe code above is an example.Once the SetInput Value is complete, you can request TR from the server. (Transaction method call in CommRqData) CommRqData requires a total of 4 parameters to be entered, and please refer to the KOA table below for detailsThis response to this server is known that the server is generated.Therefore, the default_set_set_slots (elf) part of the default_s slots (elf) part.OnReceiveTrData.connect(self._on_receive_tr_data) 부분이다.)The response to this request from the server can be seen to generate an On Receive TrData event.Therefore, this time again, the event listener will be created (self in the def_set_signal_slots(self) part coded above).OnReceiveTrData.connect(self._on_receive_tr_data) 부분이다.)def_on_receive_tr_data(self, screen_no, rqname, trcode, record_name, next, unused1, unused2, unused3、 unused4):print(“[Kium]_on_receive_tr_data is call {} / {} / {}.format(screen_no、rqname、trcode) tr__cnt = sel.dynamicCall(“GetRepeat(“RepeatCnt。has_next_tr_data = true else: self.has_next_tr_data = rqname == “opt10081_req”: ohlcv = {‘date’: [], , ‘open’: [ ], ‘high’: [ ], ‘low’: [ ], ‘close’: [ ], ‘volume’: date = self.dynamicCall(“GetCommData(STring, Q, Itr, コマンドデータ(STr、 “일자”) open = self.dynamicCall(“GetCommData(QSTring, QSTring, int, QSTring), trcode, rqname, i, “시가”) high = self.dynamicCall(“GetCommData(QSTring, int、QString)”trcode, rqname”i、 “고가” low = = selfCommData(Qselomming QSTring) inting(Q.dynamicD、 “저가”) close = self.dynamicCall(“GetCommData(QSTring, QSTring, int, QSTring)”, trcode, rqname, i, “현재가”) volume = self.dynamicCall(“GetCommData(QSTring, int.QString) , , trcode、rqname、i、”거래량”) ohlcv[date]。append(date.strip ()) ohlcv[‘open’]。append(int(open))ohlcv[‘high’].append(int(high))ohlcv[‘low’]。ohlcv[‘close’]Add .append (cse) ohlcv[‘volume’]。append(int(volume)) self.tr _data = ohlcv self.tr _event_loop.exit() time。スリープ (0.5)defget_deposit(self): self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 계좌번호, self.account_number) self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 조회구분.dynamicCall(“SetInputValue(QSTring, QSTring), QSTring), QSTring(비밀번호입력매체구분)”조회구분) self、 “opw00001”, 0, “0002”) # 입력값을 설정(SetInputVale)한 후 호출(CommRqData)하는 과정을 거친다 self.tr_event_loop.exec_() # 응답을 대기할 수 있는 상태로 만든들어서 TR 호출을 마무리 해준다.return self.tr_datadefget_deposit(self): self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 계좌번호, self.account_number) self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 조회구분.dynamicCall(“SetInputValue(QSTring, QSTring), QSTring), QSTring(비밀번호입력매체구분)”조회구분) self、 “opw00001”, 0, “0002”) # # 입력값을 설정(SetInputVale)한 후 호출(CommRqData)하는 과정을 거친다 self.tr_event_loop.exec_() # 응답을 대기할 수 있는 상태로 만든들어서 TR 호출을 마무리 해준다.return self.tr_datadefget_deposit(self): self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 계좌번호, self.account_number) self.dynamicCall(“SetInputValue(QSTring, QSTring)”, 조회구분.dynamicCall(“SetInputValue(QSTring, QSTring), QSTring), QSTring(비밀번호입력매체구분)”조회구분) self、 “opw00001”, 0, “0002”) # # 입력값을 설정(SetInputVale)한 후 호출(CommRqData)하는 과정을 거친다 self.tr_event_loop.exec_() # 응답을 대기할 수 있는 상태로 만든들어서 TR 호출을 마무리 해준다.return self.tr_data

error: Content is protected !!