HOME/Articles/

Don3030

Article Outline

Example Python program Don3030.py This program creates a PyQt GUI Python version 3.x or newer. To check the Python version use:

python --version

Modules

  • import sys
  • from PyQt5.QtWidgets import *
  • from PyQt5.QtCore import *
  • from PyQt5 import uic
  • from kiwoomd import *
  • import sqlite3
  • import pandas as pd
  • from pandas import Series,DataFrame
  • import numpy as np
  • from datetime import date,timedelta

Classes

  • class MyWindow(QMainWindow, form_class):

Methods

  • def init(self):
  • def kiwoomconnect(self):
  • def timercall(self):
  • def pushbtevent(self):
  • def action(self):
  • def actioneve(self):
  • def del(self):
  • def initval(self):
  • def initialval(self):
  • def callacc(self):
  • def Kospi200init(self):
  • def inidic(self):
  • def todaycall(self):
  • def bt1(self):
  • def bt4(self):
  • def bt3(self):
  • def bt6(self):
  • def opt04(self):
  • def setTableWidgetData(self):
  • def tr_check(self, sScrNo, sRQName, sTrCode, sRecordName, sPreNext, nDataLength, sErrorCode, sMessage,sSplmMsg):
  • def real_check(self, sRealKey, sRealType, sRealData):
  • def msg_check(self, sScrNo, sRQName, sTrCode, sMsg):
  • def chejan_check(self, sGubun, nItemCnt, sFidList):
  • def timeout(self):
  • def upd(self):
  • def redata(self):

Code

Example Python PyQt program :

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import uic
from kiwoomd import *
import sqlite3
import pandas as pd
from pandas import Series,DataFrame
import numpy as np
from datetime import date,timedelta
con=sqlite3.connect("c:/Users/skehrha/PycharmProjects/StockProject/don30.db")

form_class = uic.loadUiType("don3030.ui")[0]

class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.kiwoomconnect()
        self.timercall()
        self.pushbtevent()
        self.actioneve()
        self.initval()

    def kiwoomconnect(self):
        self.kiwoom = Kiwoom()
        self.kiwoom._comm_connect()
        self.kiwoom.OnReceiveTrData.connect(self.tr_check)
        self.kiwoom.OnReceiveRealData.connect(self.real_check)
        self.kiwoom.OnReceiveMsg.connect(self.msg_check)
        self.kiwoom.OnReceiveChejanData.connect(self.chejan_check)
    def timercall(self):
        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)
    def pushbtevent(self):
        self.pushButton_2.clicked.connect(QCoreApplication.instance().quit)
        self.pushButton.clicked.connect(self.redata)
        self.pushButton_3.clicked.connect(self.bt3)
        self.pushButton_6.clicked.connect(self.bt6)
    def action(self):
        QMessageBox.about(self, "돈벌어보자3030", "연락처 : 010-****-****\n제작자 : 곽성훈")
    def actioneve(self):
        self.actionAbout.triggered.connect(self.action)

    def __del__(self):
        con.commit()
        con.close()

    def initval(self):
        #초기변수 지정
        self.initialval()
        self.callacc()
        self.calltime=[]
        self.Kospi200init()
        self.todaycall()

    def initialval(self):
        self.count = 0
        self.bt33 = 1
        self.bt11 = 0
        self.timee = 0
        self.dla = 0
        self.bt66=0
        self.opt81=0
    def callacc(self):
        accouns_num = int(self.kiwoom._get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom._get_login_info("ACCNO")
        accounts_list = accounts.split(";")[0:accouns_num]
        self.comboBox.addItems(accounts_list)
    def Kospi200init(self):
        self.codekey = pd.read_sql("SELECT * FROM Kospi200", con, index_col=None)
        self.codekey = list(self.codekey['종목코드'])
        self.dic = []
        for i in self.codekey:
            self.dic.append(i + 'u')
            self.dic.append(i + 'd')
            self.dic.append(i + 'p')
            self.dic.append(i + 'v')
        self.inidic()
    def inidic(self):
        self.temrealdata = {}
        self.realdata = {}
        self.temrealdata['time'] = 0
        self.realdata['time']=[]
        self.realdata['time'].append(0)
        for i in self.dic:
            self.realdata[i]=[]
            self.realdata[i].append(0)
            self.temrealdata[i] = 0



    def todaycall(self):
        today = date.today()
        self.todayyymmdd = today.strftime('%Y-%m-%d')


    def bt1(self):
        if self.count<5:
            self.kiwoom.call_opw00011()
            self.calltime.append(self.stime)
            self.bt11+=1
            self.count+=1
        if self.count<5:
            self.kiwoom.call_opw00018()
            self.calltime.append(self.stime)
            self.bt11 += 1
            self.count+=1
        if self.count<5:
            self.kiwoom.call_opt10085()
            self.calltime.append(self.stime)
            self.bt11 += 1
            self.count += 1

    def bt4(self):
        self.df = pd.read_sql("SELECT * FROM Kospi200", con, index_col=None)
        self.d1 = self.df['종목코드']
        self.d2 = self.df['index']
        self.d3 = []
        for i in self.d1:
            self.d3.append(self.kiwoom._get_master_last_price(i))

        dfg = {'index': self.d2, '종목코드': self.d1, '전일가': self.d3}
        dfg = pd.DataFrame(dfg, columns=['종목코드', '전일가'], index=self.d2)
        dfg.to_sql('KOSPI200전일가', con, if_exists='replace')
    def bt3(self):
        if self.bt33==1:
            self.kiwoom.res_set_real2("1001")
            self.listWidget.addItem("KOSPI200 연결1")
            self.bt33=2
            self.pushButton_3.setText("KOSPI200 연결2")
        elif self.bt33==2:
            self.kiwoom.res_set_real3("1002")
            self.listWidget.addItem("KOSPI200 연결2")
            self.bt33 = 3
            self.pushButton_3.setText("KOSPI200 연결3")
        elif self.bt33==3:
            self.kiwoom.res_set_real4("1003")
            self.listWidget.addItem("KOSPI200 연결완료")
            self.bt33 = 4
            self.pushButton_3.setText("해제하기")
        elif self.bt33==4:
            self.kiwoom._set_real_remove("ALL","ALL")
            self.listWidget.addItem("실시간연결 해제완료")
            self.bt33=1
            self.pushButton_3.setText("실시간연결")
    def bt6(self):
        if self.bt66==0:
            self.setGeometry(500,320,820,420)
            self.tableWidget = QTableWidget(self)
            self.tableWidget.setRowCount(self.kiwoom.opt85_r+1)
            self.tableWidget.setColumnCount(5)
            self.setTableWidgetData()
            self.tableWidget.resize(400, 420)
            self.tableWidget.move(420,0)
            self.tableWidget.resizeColumnsToContents()
            self.tableWidget.resizeRowsToContents()
            self.tableWidget.show()
            self.bt66+=1
        elif self.bt66==1:
            self.setGeometry(750, 320, 420, 420)
            self.tableWidget.close()
            self.bt66 += -1


    def opt04(self):
        if self.opt81==1:
            self.kiwoom.call_opt10081("229200")
            self.opt81=1
        else:
            self.kiwoom.call_opt10081("250780")

    def setTableWidgetData(self):
        w_5=0
        col_headers=['종목명','매입가','현재가','수량','수익률']
        self.tableWidget.setHorizontalHeaderLabels(col_headers)
        for j in range(0,self.kiwoom.opt85_r):
            item1=QTableWidgetItem(self.kiwoom._get_master_code_name(self.kiwoom.opt85_1[j]))
            w_1=int(self.kiwoom.opt85_2[j])
            item2 = QTableWidgetItem(str(w_1))
            w_2=int(self.kiwoom.opt85_4[j])
            item3 = QTableWidgetItem(str(w_2))
            w_3=int(self.kiwoom.opt85_3[j])
            item4 = QTableWidgetItem(str(w_3))
            w_4=int(10000*(int(self.kiwoom.opt85_4[j]) - int(self.kiwoom.opt85_2[j]))/int(self.kiwoom.opt85_2[j]))/100
            item5 = QTableWidgetItem(str(w_4)+'%')
            item1.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
            item2.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
            item3.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
            item4.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
            item5.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
            self.tableWidget.setItem(j+1, 0, item1)
            self.tableWidget.setItem(j+1, 1, item2)
            self.tableWidget.setItem(j+1, 2, item3)
            self.tableWidget.setItem(j+1, 3, item4)
            self.tableWidget.setItem(j+1, 4, item5)
            w_5=w_5+(w_2-w_1)*w_3
        item_1=QTableWidgetItem('총계: '+str(w_5)+'원')
        item_1.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
        self.tableWidget.setItem(0, 0, item_1)





    def tr_check(self, sScrNo, sRQName, sTrCode, sRecordName, sPreNext, nDataLength, sErrorCode, sMessage,sSplmMsg):
        print(sRQName)
        if sRQName=="opw00011_req":
            self.pmoney=self.kiwoom.res_opw00011(sRQName,sTrCode)
            self.lineEdit_2.setText(self.pmoney)
            if self.lineEdit.text()=="":
                self.lineEdit.setText(self.pmoney)
            else:
                self.tmoney=int(self.pmoney)+int(self.kiwoom.nowasset)
                self.tmoney=str(self.tmoney)
                self.lineEdit.setText(self.tmoney)
        elif sRQName=="opw00018_req":
            self.kiwoom.res_opw00018(sRQName, sTrCode)
            self.lineEdit_5.setText(self.kiwoom.buyasset)
            self.lineEdit_6.setText(self.kiwoom.nowasset)
            if self.lineEdit.text()=="":
                self.lineEdit.setText(self.kiwoom.nowasset)
            else:
                self.tmoney = int(self.pmoney) + int(self.kiwoom.nowasset)
                self.tmoney = str(self.tmoney)
                self.lineEdit.setText(self.tmoney)
        elif sRQName == "opt10085_req":
            self.kiwoom.res_opt10085(sRQName, sTrCode)
        elif sRQName == "opt10004_req":
            self.kiwoom.res_opt10004(sRQName, sTrCode)
        elif sRQName == "opt10081_req":
            self.kiwoom.res_opt10081(sRQName, sTrCode)
            self.op={}
            self.op['시가']=self.kiwoom.opt81_1
            self.op['고가']=self.kiwoom.opt81_2
            self.op['저가']=self.kiwoom.opt81_3
            self.op['종가']=self.kiwoom.opt81_4
            self.op['거래량']=self.kiwoom.opt81_5
            self.op['일자']=self.kiwoom.opt81_6
            op_ = pd.DataFrame(self.op, columns=['시가','고가','저가','종가','거래량'], index=self.op['일자'])
            op_.to_sql('콜풋비교6', con, if_exists='append')





    def real_check(self, sRealKey, sRealType, sRealData):
        if self.kiwoom._get_comm_real_data(sRealKey, 20)!="":
            if self.kiwoom._get_comm_real_data(sRealKey, 20)!=0:
                self.temrealdata['time'] = self.kiwoom._get_comm_real_data(sRealKey, 20)
        for i in self.codekey:
            if i==sRealKey:
                if self.kiwoom._get_comm_real_data(sRealKey, 27)!="":
                    self.temrealdata[i + 'u'] = abs(int(self.kiwoom._get_comm_real_data(sRealKey, 27)))
                if self.kiwoom._get_comm_real_data(sRealKey, 28) != "":
                    self.temrealdata[i + 'd'] = abs(int(self.kiwoom._get_comm_real_data(sRealKey, 28)))
                if self.kiwoom._get_comm_real_data(sRealKey, 23) != "":
                    self.temrealdata[i + 'p'] = abs(int(self.kiwoom._get_comm_real_data(sRealKey, 23)))
                if self.kiwoom._get_comm_real_data(sRealKey, 13) != "":
                    self.temrealdata[i + 'v'] = abs(int(self.kiwoom._get_comm_real_data(sRealKey, 13)))   #거래량 값이 없을떄 처리
                self.realdata['time']=[]
                self.realdata[i + 'u']=[]
                self.realdata[i + 'd']=[]
                self.realdata[i + 'p'] = []
                self.realdata[i + 'v'] = []
                self.realdata['time'].append(self.temrealdata['time'])
                self.realdata[i+'u'].append(self.temrealdata[i + 'u'])
                self.realdata[i+'d'] .append(self.temrealdata[i + 'd'])
                self.realdata[i+'p'] .append(self.temrealdata[i + 'p'])
                self.realdata[i+'v'] .append(self.temrealdata[i + 'v'])

    def msg_check(self, sScrNo, sRQName, sTrCode, sMsg):
        pass
    def chejan_check(self, sGubun, nItemCnt, sFidList):
        pass
# 이벤트 처리하는곳



    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time
        state = self.kiwoom._get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"
        self.statusbar.showMessage(state_msg + " | " + time_msg+" | "+self.todayyymmdd+" | "+"돈벌어보자3030_ver_1.5")
        self.stime = 1000*(current_time.hour() * 3600 + current_time.minute() * 60 + current_time.second())+current_time.msec()
        self.tcalltime=self.calltime
        for i in self.calltime:
            if i+1000<self.stime:
                self.count+=-1
        if self.count<=0:
            self.count=0
            self.calltime = []
        else:
            self.calltime=self.tcalltime[len(self.tcalltime)-self.count:len(self.tcalltime)]
        self.upd()


    def upd(self):
        self.redata()
        if self.bt11 < 3:
            self.bt1()
    def redata(self):
        retypedata=pd.DataFrame(self.realdata,columns=self.dic,index=self.realdata['time'])
        retypedata.to_sql('KOSPI200'+self.todayyymmdd,con,if_exists='append')


if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()