Esempio n. 1
0
    def __init__(self, view):

        self.user = None
        self.view = view

        # Logger 초기화
        logHandler = LogHandler(self.view)
        logHandler.setLevel(logging.DEBUG)
        logger.addHandler(logHandler)

        # 키움증권API OCX Instance 생성
        self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")

        # event handler 등록
        self.kiwoom.OnEventConnect[int].connect(self.OnEventConnect)
        self.kiwoom.OnReceiveTrData[str, str, str, str, str, int, str, str,
                                    str].connect(self.OnReceiveTrData)
        self.kiwoom.OnReceiveRealData[str, str,
                                      str].connect(self.OnReceiveRealData)
        self.kiwoom.OnReceiveMsg[str, str, str, str].connect(self.OnReceiveMsg)
        self.kiwoom.OnReceiveChejanData[str, int,
                                        str].connect(self.OnReceiveChejanData)
        self.kiwoom.OnReceiveRealCondition[str, str, str, str].connect(
            self.OnReceiveRealCondition)
        self.kiwoom.OnReceiveTrCondition[str, str, str, int, int].connect(
            self.OnReceiveTrCondition)
        self.kiwoom.OnReceiveConditionVer[int, str].connect(
            self.OnReceiveConditionVer)
Esempio n. 2
0
    def __init__(self, parent=None, flags=Qt.WindowFlags(), db_obj=None):
        super().__init__(parent=parent, flags=flags, db_obj=db_obj)
        self._kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        # login 화면 표시
        # self._check_login()

        # Menu Action 기능정의
        # self.actionAddStudent.triggered.connect(self.slot_open_input_student)
        # self.actionManageStudent.triggered.connect(self.slot_open_manage_student)
        # self.actionExit.triggered.connect(QCoreApplication.quit)
        #
        # self.actionAdd_CSAT_Score.triggered.connect(self.slot_open_input_csat)
        # self.actionAdd_HSS_Score.triggered.connect(self.slot_open_input_hss)
        #
        # self.actionAddEarlyDecision.triggered.connect(self.slot_open_early_decision)
        # self.actionEarlyPassPresent.triggered.connect(self.slot_open_early_passpresent)
        # self.actionAddRegularDecision.triggered.connect(self.slot_open_regular_decision)
        # self.actionRegularPassPresent.triggered.connect(self.slot_open_regular_passpresent)

        # slot & connect
        # self.btnSearch.clicked.connect(self.slot_search_present)
        # self.btnOpenDlgStudent.clicked.connect(self.slot_open_dlg_student)
        # self.btnOpenDlgEntrace.clicked.connect(self.slot_open_dlg_entrace)
        self.pushButton.clicked.connect(self._slot_login)
        self.pushButton_2.clicked.connect(self._slot_get_status)
        self.pushButton_3.clicked.connect(self._slot_get_baseinfo)

        # OPEN API+ Event 설정
        # 통신 연결 상태 변경시 이벤트
        self._kiwoom.OnEventConnect.connect(self._event_connect)
        self._kiwoom.OnReceiveTrData.connect(self._event_receive_trdata)
Esempio n. 3
0
 def connectServer(self):
     msg = QMessageBox.information(self, '알림', "서버에 연결되어 있지 않습니다. 연결하시겠습니까?", QMessageBox.Yes|QMessageBox.No)
     if msg == QMessageBox.Yes:
         self.connect = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
         self.connect.dynamicCall("CommConnect()")
     elif msg == QMessageBox.No:
         return
Esempio n. 4
0
    def __init__(self):
        super().__init__()

        self.IndiTR = QAxWidget("GIEXPERTCONTROL.GiExpertControlCtrl.1")
        self.IndiTR.ReceiveData.connect(self.OnReceiveData)
        self.IndiTR.ReceiveSysMsg.connect(self.OnReceiveSysMsg)

        self.IndiReal = QAxWidget("GIEXPERTCONTROL.GiExpertControlCtrl.1")
        self.IndiReal.ReceiveRTData.connect(self.OnReceiveRealData)

        # Loop 변수 : 비동기 방식으로 동작되는 이벤트를 동기화 
        self.logingLoop = None
        self.requestLoop = None
        self.orderLoop = None
        self.conditionLoop = None

        # 서버구분 
        self.serverStatus = None

        # 연속조회 구분 
        self.isNext = 0
        self.rqidD = {}

        # logging 
        self.homepath = os.environ.get("userprofile")
        self.logger = Logger(path=self.log_path, name="SH Indi")

        # 메세지 처리 
        self.msg = ""
 def initUi(self):
     self.createGridGroupBox()
     self.undercamera()
     self.resize(1500,900)
     self.timer_camera = QtCore.QTimer() # 定時器
     self.timer_picture = QtCore.QTimer() # 定時器
     self.timer_crop = QtCore.QTimer() # 定時器
     self.timer_deception = QtCore.QTimer() # 定時器
     self.cap = cv2.VideoCapture() # 準備獲取圖像
     self.CAM_NUM = 0    
     mainLayout = QHBoxLayout() 
     vboxLayout = QVBoxLayout()
     self.label_face = QLabel()
     vboxLayout.addWidget(self.label_face)
     self.label_face.setFixedSize(680,455)
     self.axWidget = QAxWidget()
     self.axWidget.setFixedSize(750, 900)
     vboxLayout.addLayout(self.finallayout)
     mainLayout.addWidget(self.axWidget)
     mainLayout.addLayout(vboxLayout)
     mainLayout.addWidget(self.gridGroupBox)
     self.setLayout(mainLayout)
     self.setWindowIcon(QtGui.QIcon("man.png"))
     self.setWindowTitle('Main Window')
     self.button_open_camera_click()
     self.timer_camera.timeout.connect(self.show_camera)
     self.Oneshots()
     path = 'D:\\Swift Desktop\\Yi-Ting_CV  (2018).docx'                            
     self.openOffice(path,'Word.Application')
Esempio n. 6
0
    def __init__(self):
        self.__kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.__event_loop = QEventLoop()

        self.__kiwoom.OnEventConnect.connect(self.__login_slot)
        self.__kiwoom.OnReceiveConditionVer.connect(self.__condition_ver_slot)
        self.__kiwoom.OnReceiveTrCondition.connect(self.__send_condition_slot)
Esempio n. 7
0
    def createKiwoomInstance(self):
        """
        키움 API 를 쓰기 위한 Instance 생성

        :return:
        """
        self.kiwoom_api = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
Esempio n. 8
0
 def __init__(self):
     # QAxWidget Instance
     self.OCXconn = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
     # Event Listener
     self.OCXconn.OnEventConnect.connect(self.connEvent)
     self.OCXconn.OnReceiveTrData.connect(self.trEvent)
     #self.OCXconn.OnReceiveRealData.connect(self.getRealTimeData)
     self.saveType = 'e'
Esempio n. 9
0
 def server_connect(self):
     try:
         self.connect = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
         self.connect.dynamicCall("CommConnect()")
         self.connect.OnEventConnect.connect(self.event_connect)
     except AttributeError as e:
         QMessageBox.critical(self, 'Program execution error!', "실행에 실패했습니다! 32비트 가상환경을 설정 후 실행해 주세요!", QMessageBox.Ok)
         exit(-10)
Esempio n. 10
0
 def __init__(self, *args, **kwargs):
     super(AxWidget, self).__init__(*args, **kwargs)
     self.resize(800, 600)
     layout = QVBoxLayout(self)
     self.axWidget = QAxWidget(self)
     layout.addWidget(self.axWidget)
     layout.addWidget(
         QPushButton('选择excel,word,pdf文件', self, clicked=self.onOpenFile))
Esempio n. 11
0
    def __init__(self):
        """메인 객체
        """
        super().__init__()

        # 키움 시그널 연결
        self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.kiwoom.OnEventConnect.connect(self.kiwoom_OnEventConnect)
        self.kiwoom.OnReceiveTrData.connect(self.kiwoom_OnReceiveTrData)
        self.kiwoom.OnReceiveRealData.connect(self.kiwoom_OnReceiveRealData)
        self.kiwoom.OnReceiveConditionVer.connect(
            self.kiwoom_OnReceiveConditionVer)
        self.kiwoom.OnReceiveTrCondition.connect(
            self.kiwoom_OnReceiveTrCondition)
        self.kiwoom.OnReceiveRealCondition.connect(
            self.kiwoom_OnReceiveRealCondition)
        self.kiwoom.OnReceiveChejanData.connect(
            self.kiwoom_OnReceiveChejanData)
        self.kiwoom.OnReceiveMsg.connect(self.kiwoom_OnReceiveMsg)

        # 데이터
        self.set_stock2monitor = set()  # {종목코드}
        self.set_stock_ordered = set()  # {종목코드}

        # {종목코드: 종목기본정보}
        self.dict_stock = {}

        # {종목코드: 보유종목기본정보}
        # 보유종목기본정보: ["종목코드", "종목명", "현재가", "매입가", "보유수량"]
        self.dict_holding = {}

        # 차트
        self.dict_chart_minute = {}  # {종목코드: 분봉차트}
        self.dict_chart_day = {}  # {종목코드: 일봉차트}
        self.dict_chart_week = {}  # {종목코드: 주봉차트}
        self.dict_chart_month = {}  # {종목코드: 월봉차트}
        self.int_주문가능금액 = 0

        # 파라미터
        self.dict_param = {}

        # 콜백
        self.dict_callback = {}

        # 요청 쓰레드
        self.request_thread_worker = RequestThreadWorker(self)
        self.request_thread = QThread()
        self.request_thread_worker.moveToThread(self.request_thread)
        self.request_thread.started.connect(self.request_thread_worker.run)
        self.request_thread.start()
Esempio n. 12
0
    def __init__(self):
        super(api, self).__init__()
        self.app = QApplication(sys.argv)

        self.ocx = QAxWidget("KFOPENAPI.KFOpenAPICtrl.1")
        self.ocx.OnEventConnect[int].connect(self.OnEventConnect)
        self.ocx.OnReceiveTrData[str, str, str, str, str].connect(self.OnReceiveTrData)
        self.ocx.OnReceiveRealData[str, str, str].connect(self.OnReceiveRealData)
        
        print("데이터를 읽어올 시작일을 입력하세요. ex)20170125")
        self.start_date = input()
        print(self.start_date)
        if self.connect() == 0:
            self.app.exec_()
Esempio n. 13
0
 def create_activex_widget(self, parent: QWidget = None) -> QtAds.CDockWidget:
     widget = QAxWidget("{6bf52a52-394a-11d3-b153-00c04f79faa6}", parent)
     dock_widget = QtAds.CDockWidget("Active X {}".format(_State.activex_count))
     _State.activex_count += 1
     dock_widget.setWidget(widget)
     self.menuView.addAction(dock_widget.toggleViewAction())
     return dock_widget
Esempio n. 14
0
    def __init__(self):
        '''메인 객체
        '''
        super().__init__()

        # 키움 시그널 연결
        if self.kiwoom is None:
            self.kiwoom = QAxWidget('KHOPENAPI.KHOpenAPICtrl.1')
            self.kiwoom.OnEventConnect.connect(self.kiwoom_OnEventConnect)
            self.kiwoom.OnReceiveTrData.connect(self.kiwoom_OnReceiveTrData)
            self.kiwoom.OnReceiveRealData.connect(
                self.kiwoom_OnReceiveRealData)
            self.kiwoom.OnReceiveConditionVer.connect(
                self.kiwoom_OnReceiveConditionVer)
            self.kiwoom.OnReceiveTrCondition.connect(
                self.kiwoom_OnReceiveTrCondition)
            self.kiwoom.OnReceiveRealCondition.connect(
                self.kiwoom_OnReceiveRealCondition)
            self.kiwoom.OnReceiveChejanData.connect(
                self.kiwoom_OnReceiveChejanData)
            self.kiwoom.OnReceiveMsg.connect(self.kiwoom_OnReceiveMsg)

        # 데이터
        self.set_stock2monitor = set()  # {종목코드}
        self.set_stock_ordered = set()  # {종목코드}

        # {종목코드: 종목기본정보}
        self.dict_stock = {}

        # {종목코드: 보유종목기본정보}
        # 보유종목기본정보: ['종목코드', '종목명', '현재가', '매입가', '보유수량']
        self.dict_holding = {}

        # 차트
        self.dict_chart_minute = {}  # {종목코드: 분봉차트}
        self.dict_chart_day = {}  # {종목코드: 일봉차트}
        self.dict_chart_week = {}  # {종목코드: 주봉차트}
        self.dict_chart_month = {}  # {종목코드: 월봉차트}
        self.int_주문가능금액 = 0

        # 파라미터
        self.dict_param = {}

        # 콜백
        self.dict_callback = {}

        logger.info('키움증권 API 객체 준비 완료')
Esempio n. 15
0
    def __init__(self):
        """자동투자시스템 메인 클래스
        """
        # 요청 쓰레드
        self.request_thread_worker = RequestThreadWorker()
        self.request_thread = QThread()
        self.request_thread_worker.moveToThread(self.request_thread)
        self.request_thread.started.connect(self.request_thread_worker.run)
        self.request_thread.start()

        self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.kiwoom.OnEventConnect.connect(
            self.kiwoom_OnEventConnect)  # 로그인 결과를 받을 콜백함수 연결
        self.kiwoom.OnReceiveChejanData.connect(
            self.kiwoom_OnReceiveChejanData)

        self.order_loop = None
Esempio n. 16
0
    def __init__(self):  # MyWindow 클래스의 초기화 함수(생성자)
        super().__init__()  # 부모클래스 QMainWindow 클래스의 초기화 함수(생성자)를 호출
        self.setupUi(self)  # ui 파일 화면 출력

        self.kiwoom = QAxWidget(
            "KHOPENAPI.KHOpenAPICtrl.1"
        )  # 키움증권 Open API+의 ProgID를 사용하여 생성된 QAxWidget을 kiwoom 변수에 할당

        self.lineEditCode.setDisabled(True)  # 종목코드 입력란을 비활성화 상태로 변경
        self.btnSearch.setDisabled(True)  # 조회 버튼을 비활성화 상태로 변경
        self.pteLog.setDisabled(True)  # plainTextEdit를 비활성화 상태로 변경

        self.btnLogin.clicked.connect(
            self.btn_login
        )  # ui 파일을 생성할때 작성한 로그인 버튼의 objectName 으로 클릭 이벤트가 발생할 경우 btn_login 함수를 호출
        self.kiwoom.OnEventConnect.connect(
            self.event_connect)  # 키움 서버 접속 관련 이벤트가 발생할 경우 event_connect 함수 호출
Esempio n. 17
0
 def __init__(self):
     super().__init__()
     self.api = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
     self.api.OnEventConnect[int].connect(self._OnEventConnect)
     self.api.OnReceiveMsg[str, str, str, str].connect(self._OnReceiveMsg)
     self.api.OnReceiveTrData[str, str, str, str, str, int, str, str,
                              str].connect(self._OnReceiveTrData)
     self.api.OnReceiveRealData[str, str,
                                str].connect(self._OnReceiveRealData)
     self.api.OnReceiveChejanData[str, int,
                                  str].connect(self._OnReceiveChejanData)
     self.api.OnReceiveConditionVer[int, str].connect(
         self._OnReceiveConditionVer)
     self.api.OnReceiveTrCondition[str, str, str, int,
                                   int].connect(self._OnReceiveTrCondition)
     self.api.OnReceiveRealCondition[str, str, str, str].connect(
         self._OnReceiveRealCondition)
Esempio n. 18
0
    def __init__(self, k_queue):
        super().__init__()
        self.S_SCREEN_NO = "0001"
        self.MARKET_LIST = {
            0: '장내',
            3: 'ELW',
            4: '뮤추얼펀드',
            5: '신주인수권',
            6: '리츠',
            8: 'ETF',
            9: '하이일드펀드',
            10: '코스닥',
            30: '제3시장'
        }
        self.ORDER_TYPE = {1: '신규매수', 2: '신규매도', 3: '매수취소', 4: '매도취소'}
        self.HOGA = {'00': '지정가', '03': '시장가'}

        self.q = k_queue
        self.qs = {
            'OnReceiveTrData': queue.Queue(),
            'OnReceiveRealData': queue.Queue(),
            'OnReceiveMsg': queue.Queue(),
            'OnReceiveChejanData': queue.Queue(),
            'OnEventConnect': queue.Queue(),
            'OnReceiveRealCondition': queue.Queue(),
            'OnReceiveTrCondition': queue.Queue(),
            'OnReceiveConditionVer': queue.Queue()
        }
        self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.ocx.OnReceiveTrData[str, str, str, str, str, int, str, str,
                                 str].connect(self.OnReceiveTrData)
        self.ocx.OnReceiveRealData[str, str,
                                   str].connect(self.OnReceiveRealData)
        self.ocx.OnReceiveMsg[str, str, str, str].connect(self.OnReceiveMsg)
        self.ocx.OnReceiveChejanData[str, int,
                                     str].connect(self.OnReceiveChejanData)
        self.ocx.OnEventConnect[int].connect(self.OnEventConnect)
        self.ocx.OnReceiveRealCondition[str, str, str, str].connect(
            self.OnReceiveRealCondition)
        self.ocx.OnReceiveTrCondition[str, str, str, int,
                                      int].connect(self.OnReceiveTrCondition)
        self.ocx.OnReceiveConditionVer[int,
                                       str].connect(self.OnReceiveConditionVer)
        atexit.register(self.quit)
Esempio n. 19
0
    def initUI(self):
        titleheight = 20

        self.resize(720, titleheight + 448)
        self.setWindowIcon(QIcon('./client/icon.ico'))
        self.setWindowTitle('我的热点新闻客户端')
        self.setWindowFlags(Qt.FramelessWindowHint | self.windowFlags())
        self.setCentralWidget(QWidget(self))

        self.vlayout = QVBoxLayout(self.centralWidget())
        self.vlayout.setContentsMargins(0, 0, 0, 0)
        self.vlayout.setSpacing(0)

        titlewidget = QWidget(self.centralWidget())
        titlewidget.setFixedWidth(self.width())
        titlewidget.setFixedHeight(titleheight)

        self.hlayout = QHBoxLayout(titlewidget)
        self.hlayout.setContentsMargins(0, 0, 0, 0)
        self.hlayout.setSpacing(0)
        self.vlayout.addWidget(titlewidget)

        self.hlayout.addStretch()

        self.buttonminimize = QPushButton(titlewidget)
        self.buttonminimize.setToolTip("Minimize")
        self.buttonminimize.clicked.connect(self.onClicked)
        self.hlayout.addWidget(self.buttonminimize, 0,
                               Qt.AlignRight | Qt.AlignTop)

        self.buttonclose = QPushButton(titlewidget)
        self.buttonclose.setToolTip("Close")
        self.buttonclose.clicked.connect(self.onClicked)
        self.hlayout.addWidget(self.buttonclose, 0,
                               Qt.AlignRight | Qt.AlignTop)

        self.webview = QAxWidget(self.centralWidget())
        self.webview.setControl("{8856F961-340A-11D0-A96B-00C04FD705A2}")
        self.webview.setProperty("DisplayAlerts", False)
        self.webview.setProperty("DisplayScrollBars", True)
        self.webview.dynamicCall("Navigate(const QString&)",
                                 "http://127.0.0.1:81/kingsoft/default")
        self.vlayout.addWidget(self.webview)
Esempio n. 20
0
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle("PyStock")
        self.setGeometry(300, 300, 300, 400)

        self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.kiwoom.OnReceiveTrData.connect(self.OnReceiveTrData)

        btn1 = QPushButton("Log In", self)
        btn1.move(20, 20)
        btn1.clicked.connect(self.btn_clicked)

        btn2 = QPushButton("Get Info", self)
        btn2.move(20, 70)
        btn2.clicked.connect(self.btn_clicked2)

        btn3 = QPushButton("connect state", self)
        btn3.move(20, 120)
        btn3.clicked.connect(self.btn_clicked3)
Esempio n. 21
0
    def __init__(self, agent):
        super().__init__()

        self.agent = agent

        if sys.platform == 'win32':
            from PyQt5.QAxContainer import QAxWidget
            self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        else:
            self.kiwoom = None

        if self.kiwoom:
            self.kiwoom.OnEventConnect.connect(self.OnEventConnect)
            self.kiwoom.OnReceiveMsg.connect(self.OnReceiveMsg)
            self.kiwoom.OnReceiveTrData.connect(self.OnReceiveTrData)
            self.kiwoom.OnReceiveConditionVer.connect(
                self.OnReceiveConditionVer)
        else:
            self.OnEventConnectSignal.connect(self.OnEventConnect)
Esempio n. 22
0
 def __init__(self, view):
     super().__init__()
     self.view = view
     self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
     self.ocx.OnEventConnect[int].connect(self._OnEventConnect)
     self.ocx.OnReceiveMsg[str, str, str, str].connect(self._OnReceiveMsg)
     self.ocx.OnReceiveTrData[str, str, str, str, str, int, str, str, str].connect(self._OnReceiveTrData)
     self.ocx.OnReceiveRealData[str, str, str].connect(self._OnReceiveRealData)
     self.ocx.OnReceiveChejanData[str, int, str].connect(self._OnReceiveChejanData)
     self.ocx.OnReceiveConditionVer[int, str].connect(self._OnReceiveConditionVer)
     self.ocx.OnReceiveTrCondition[str, str, str, int, int].connect(self._OnReceiveTrCondition)
     self.ocx.OnReceiveRealCondition[str, str, str, str].connect(self._OnReceiveRealCondition)
Esempio n. 23
0
class Main():
    __kiwoom = None
    __event_loop = None
    __condition_list = []
    __condition_stock_list = []

    def __init__(self):
        self.__kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.__event_loop = QEventLoop()

        self.__kiwoom.OnEventConnect.connect(self.__login_slot)
        self.__kiwoom.OnReceiveConditionVer.connect(self.__condition_ver_slot)
        self.__kiwoom.OnReceiveTrCondition.connect(self.__send_condition_slot)

    def login(self):
        self.__kiwoom.dynamicCall("CommConnect()")
        self.__event_loop.exec_()

    def get_condition_list(self):
        self.__kiwoom.dynamicCall("GetConditionLoad()")
        self.__event_loop.exec_()
        return self.__condition_list

    def print_condition_list(self, cond):
        self.__kiwoom.dynamicCall("SendCondition(QString, QString, int, int)", "2000", cond[1], cond[0], 0)
        self.__event_loop.exec_()

        print("{} 조건식의 검색 결과".format(cond[1]))
        i = 1
        for stock in self.__condition_stock_list:
            print("{} ".format(stock), end="")
            if i % 10 == 0:
                print()
            i += 1

    def __condition_ver_slot(self, lRet, sMsg):
        condition_name_list: str
        condition_name_list = self.__kiwoom.dynamicCall("GetConditionNameList()")
        '''
        condition_name_list
        =
        인덱스^조건식이름;인덱스^조건식이름;
        '''

        for cond_index_name in condition_name_list[:-1].split(";"):
            self.__condition_list.append(cond_index_name.split("^"))

        self.__event_loop.exit()

    def __login_slot(self, errNo):
        self.__event_loop.exit()

    def __send_condition_slot(self, sScrNo, strCodeList, strConditionName, nIndex, nNext):
        self.__condition_stock_list = strCodeList.split(";")
        self.__event_loop.exit()
Esempio n. 24
0
    def __init__(self, k_queue):
        super().__init__()
        self.S_SCREEN_NO = "0001"
        self.MARKET_LIST = {
            0: '장내',
            3: 'ELW',
            4: '뮤추얼펀드',
            5: '신주인수권',
            6: '리츠',
            8: 'ETF',
            9: '하이일드펀드',
            10: '코스닥',
            30: '제3시장'
        }
        self.ORDER_TYPE = {
            1: '신규매수',
            2: '신규매도',
            3: '매수취소',
            4: '매도취소'
        }
        self.HOGA = {
            '00': '지정가',
            '03': '시장가'
        }

        self.q = k_queue
        self.qs = {
            'OnReceiveTrData': queue.Queue(),
            'OnReceiveRealData': queue.Queue(),
            'OnReceiveMsg': queue.Queue(),
            'OnReceiveChejanData': queue.Queue(),
            'OnEventConnect': queue.Queue(),
            'OnReceiveRealCondition': queue.Queue(),
            'OnReceiveTrCondition': queue.Queue(),
            'OnReceiveConditionVer': queue.Queue()
        }
        self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.ocx.OnReceiveTrData[str, str, str, str, str, int, str, str, str].connect(self.OnReceiveTrData)
        self.ocx.OnReceiveRealData[str, str, str].connect(self.OnReceiveRealData)
        self.ocx.OnReceiveMsg[str, str, str, str].connect(self.OnReceiveMsg)
        self.ocx.OnReceiveChejanData[str, int, str].connect(self.OnReceiveChejanData)
        self.ocx.OnEventConnect[int].connect(self.OnEventConnect)
        self.ocx.OnReceiveRealCondition[str, str, str, str].connect(self.OnReceiveRealCondition)
        self.ocx.OnReceiveTrCondition[str, str, str, int, int].connect(self.OnReceiveTrCondition)
        self.ocx.OnReceiveConditionVer[int, str].connect(self.OnReceiveConditionVer)
        atexit.register(self.quit)
Esempio n. 25
0
    def __init__(self, *args, **kwargs):
        super_args = args
        super_kwargs = kwargs

        clsid_or_progid = self.CLSID

        if len(args) > 0 and isinstance(args[0], str):
            super_args = args[1:]
            clsid_or_progid = args[0]
        elif self.CONTROL_NAME_KWARG_KEY in kwargs:
            super_kwargs = {
                k: v
                for k, v in kwargs if k != self.CONTROL_NAME_KWARG_KEY
            }
            clsid_or_progid = kwargs[self.CONTROL_NAME_KWARG_KEY]

        super().__init__(*super_args, **super_kwargs)

        self._ax = QAxWidget(clsid_or_progid, self)
        self._ax_wrapped = KiwoomOpenApiControlWrapper(self)
        self._signals = {}
        self._event_logger = KiwoomOpenApiLoggingEventHandler(self)

        for event_name in [
                name for name in dir(KiwoomOpenApiEventHandlerFunctions)
                if name.startswith('On')
        ]:
            # 아래처럼 중간의 프록시 객체 (KiwoomOpenApiSignalConnector) 를 넣지
            # 않으면 외부에서 동적으로 connect 를 할 수가 없어보임 (하더라도
            # 제대로 이벤트를 받지 못함)
            connector = KiwoomOpenApiSignalConnector()
            connector.connect(getattr(self._event_logger, event_name))
            getattr(self._ax, event_name).connect(connector)
            self._signals[event_name] = connector
            # 아래는 기존에 시도해서 실패한 구현 (제대로 이벤트를 받지 못함)
            """
            connector = getattr(self._ax, event_name)
            connector.connect(getattr(self._event_logger, event_name))
            self._signals[event_name] = connector
            """

        self._ax.exception.connect(self._onException)
Esempio n. 26
0
class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setWindowTitle("PyStock")
        self.setGeometry(300, 300, 300, 400)

        self.kiwoom = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.kiwoom.OnReceiveTrData.connect(self.OnReceiveTrData)

        btn1 = QPushButton("Log In", self)
        btn1.move(20, 20)
        btn1.clicked.connect(self.btn_clicked)

        btn2 = QPushButton("Get Info", self)
        btn2.move(20, 70)
        btn2.clicked.connect(self.btn_clicked2)

        btn3 = QPushButton("connect state", self)
        btn3.move(20, 120)
        btn3.clicked.connect(self.btn_clicked3)

    def OnReceiveTrData(self, sScrNo, sRQName, sTRCode, sRecordName, sPreNext, nDataLength, sErrorCode, sMessage, sSPlmMsg):
        if sRQName == "주식기본정보":
            cnt = self.kiwoom.dynamicCall('GetRepeatCnt(QString, QString)', sTRCode, sRQName)
            name = self.kiwoom.dynamicCall('GetCommData(QString, QString, int, QString)', sTRCode, sRQName, 0, "종목명")
            cur_price = self.kiwoom.dynamicCall('GetCommData(QString, QString, int, QString)', sTRCode, sRQName, 0, "현재가")
            print(name.strip())
            print(cur_price.strip())


    def btn_clicked(self):
        ret = self.kiwoom.dynamicCall("CommConnect()")

    def btn_clicked2(self):
        ret = self.kiwoom.dynamicCall('SetInputValue(QString, QString)', "종목코드", "000660")
        ret = self.kiwoom.dynamicCall('CommRqData(QString, QString, int, QString)', "주식기본정보", "OPT10001", 0, "0101")

    def btn_clicked3(self):
        if self.kiwoom.dynamicCall('GetConnectState()') == 0:
            print("Not connected")
        else:
            print("Connnected")
Esempio n. 27
0
import sys

from PyQt5.QtWidgets import QApplication
from PyQt5.QAxContainer import QAxWidget

app = QApplication(sys.argv)
control = QAxWidget('{A1574A0D-6BFA-4BD7-9020-DED88711818D}')

print(control.dynamicCall('GetAPIModulePath()'))
Esempio n. 28
0
import sys

from PyQt5.QAxContainer import QAxWidget
from PyQt5.QtCore import QEventLoop
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)
control = QAxWidget("{A1574A0D-6BFA-4BD7-9020-DED88711818D}")

loop = QEventLoop()


def comm_connect():
    err = control.dynamicCall("CommConnect()")
    if err < 0:
        raise ValueError(err)
    loop.exec_()


def on_event_connect(errcode):
    if errcode < 0:
        raise ValueError(errcode)
    if errcode == 0:
        print("Connected!")
    control.OnEventConnect.disconnect(on_event_connect)
    loop.exit()


control.OnEventConnect.connect(on_event_connect)

comm_connect()
Esempio n. 29
0
 def __init__(self):
     super().__init__()
     self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
     self.fsm = QStateMachine()
     self.createState()
Esempio n. 30
0
class Kiwoom(QObject):
    fireEvent = pyqtSignal(str, str)
    loginEvent = pyqtSignal(str, str)

    def __init__(self, view):
        super().__init__()
        self.view = view
        self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.ocx.OnEventConnect[int].connect(self._OnEventConnect)
        self.ocx.OnReceiveMsg[str, str, str, str].connect(self._OnReceiveMsg)
        self.ocx.OnReceiveTrData[str, str, str, str, str, int, str, str, str].connect(self._OnReceiveTrData)
        self.ocx.OnReceiveRealData[str, str, str].connect(self._OnReceiveRealData)
        self.ocx.OnReceiveChejanData[str, int, str].connect(self._OnReceiveChejanData)
        self.ocx.OnReceiveConditionVer[int, str].connect(self._OnReceiveConditionVer)
        self.ocx.OnReceiveTrCondition[str, str, str, int, int].connect(self._OnReceiveTrCondition)
        self.ocx.OnReceiveRealCondition[str, str, str, str].connect(self._OnReceiveRealCondition)
        
           
    @pyqtSlot()
    def quit(self):
        self.commTerminate()
        QApplication.quit()

    # 에러코드의 메시지를 출력한다.
    @pyqtSlot(int, result=str)
    def parseErrorCode(self, errCode):
        return util.parseErrorCode(errCode)


    # 통신 연결 상태 변경시 이벤트
    # nErrCode가 0이면 로그인 성공, 음수면 실패
    def _OnEventConnect(self, errCode):
        #self.view.fireEvent("eventConnect.kiwoom", errCode)
        data = json.dumps(errCode, ensure_ascii=False)
        self.loginEvent.emit("eventConnect.kiwoom", data)

    # 수신 메시지 이벤트
    def _OnReceiveMsg(self, scrNo, rQName, trCode, msg):
        data = json.dumps({
            "scrNo" : scrNo,
            "rQName" : rQName,
            "trCode": trCode,
            "msg" : msg
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveMsg.kiwoom", str(data))

    # Tran 수신시 이벤트
    def _OnReceiveTrData(self, scrNo, rQName , trCode, recordName, prevNext, dataLength, errorCode, message, splmMsg):
        # nDataLength – 1.0.0.1 버전 이후 사용하지 않음.
        # sErrorCode – 1.0.0.1 버전 이후 사용하지 않음.
        # sMessage – 1.0.0.1 버전 이후 사용하지 않음.
        # sSplmMsg - 1.0.0.1 버전 이후 사용하지 않음.
        data = json.dumps({
            "scrNo" : scrNo,
            "rQName" : rQName,
            "trCode": trCode,
            "recordName": recordName,
            "prevNext": prevNext
            # "dataLength": dataLength,
            # "errorCode" : errorCode,
            # "message" : message,
            # "splmMsg" : splmMsg
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveTrData.kiwoom", data)

    # 실시간 시세 이벤트
    def _OnReceiveRealData(self, jongmokCode, realType, realData):
        data = json.dumps({
            "jongmokCode" : jongmokCode,
            "realType" : realType,
            "realData": realData
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveRealData.kiwoom", data)

    # 체결데이터를 받은 시점을 알려준다.
    # sGubun – 0:주문체결통보, 1:잔고통보, 3:특이신호
    # sFidList – 데이터 구분은 ‘;’ 이다.
    def _OnReceiveChejanData(self, gubun, itemCnt, fidList):
        data = json.dumps({
            "gubun" : gubun,
            "itemCnt" : itemCnt,
            "fidList": fidList
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveChejanData.kiwoom", data)

    # 로컬에 사용자조건식 저장 성공여부 응답 이벤트
    def _OnReceiveConditionVer(self, ret, msg):
        data = json.dumps({
            "ret" : ret,
            "msg" : msg
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveConditionVer.kiwoom", data)

    # 조건검색 조회응답으로 종목리스트를 구분자(“;”)로 붙어서 받는 시점.
    # LPCTSTR sScrNo : 종목코드
    # LPCTSTR strCodeList : 종목리스트(“;”로 구분)
    # LPCTSTR strConditionName : 조건명
    # int nIndex : 조건명 인덱스
    # int nNext : 연속조회(2:연속조회, 0:연속조회없음)
    def _OnReceiveTrCondition(self, scrNo, codeList, conditionName, index, next):
        data = json.dumps({
            "scrNo" : scrNo,
            "codeList" : codeList,
            "conditionName" : conditionName,
            "index" : index,
            "next" : next,
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveTrCondition.kiwoom",data)

    # 편입, 이탈 종목이 실시간으로 들어옵니다.
    # strCode : 종목코드
    # strType : 편입(“I”), 이탈(“D”)
    # strConditionName : 조건명
    # strConditionIndex : 조건명 인덱스
    def _OnReceiveRealCondition(self, code, type, conditionName, conditionIndex):
        data = json.dumps({
            "code" : code,
            "type" : type,
            "conditionName" : conditionName,
            "conditionIndex" : conditionIndex
        }, ensure_ascii=False)
        self.fireEvent.emit("receiveRealCondition.kiwoom", data)

    # 로그인
    # 0 - 성공, 음수값은 실패
    @pyqtSlot(result=int)
    def commConnect(self):
        return self.ocx.dynamicCall("CommConnect()")

    # 로그인 상태 확인
    # 0:미연결, 1:연결완료, 그외는 에러
    @pyqtSlot(result=int)
    def getConnectState(self):
        return self.ocx.dynamicCall("GetConnectState()")

    # 로그 아웃
    @pyqtSlot()
    def commTerminate(self):
        self.ocx.dynamicCall("CommTerminate()")

    # 로그인한 사용자 정보를 반환한다.
    # “ACCOUNT_CNT” – 전체 계좌 개수를 반환한다.
    # "ACCNO" – 전체 계좌를 반환한다. 계좌별 구분은 ‘;’이다.
    # “USER_ID” - 사용자 ID를 반환한다.
    # “USER_NAME” – 사용자명을 반환한다.
    # “KEY_BSECGB” – 키보드보안 해지여부. 0:정상, 1:해지
    # “FIREW_SECGB” – 방화벽 설정 여부. 0:미설정, 1:설정, 2:해지
    @pyqtSlot(str,result=str)
    def getLoginInfo(self, tag):
        return self.ocx.dynamicCall("GetLoginInfo(QString)",[tag])

    # Tran 입력 값을 서버통신 전에 입력값일 저장한다.
    @pyqtSlot(str, str)
    def setInputValue(self, id, value):
        self.ocx.dynamicCall("SetInputValue(QString, QString)", id, value)

    # 통신 데이터를 송신한다.
    # 0이면 정상
    # OP_ERR_SISE_OVERFLOW – 과도한 시세조회로 인한 통신불가
    # OP_ERR_RQ_STRUCT_FAIL – 입력 구조체 생성 실패
    # OP_ERR_RQ_STRING_FAIL – 요청전문 작성 실패
    # OP_ERR_NONE – 정상처리
    @pyqtSlot(str, str, int, str, result=int)
    def commRqData(self, rQName, trCode, prevNext, screenNo):
        return self.ocx.dynamicCall("CommRqData(QString, QString, int, QString)", rQName, trCode, prevNext, screenNo)

    # 수신 받은 데이터의 반복 개수를 반환한다.
    @pyqtSlot(str, str, result=int)
    def getRepeatCnt(self, trCode, recordName):
        return self.ocx.dynamicCall("GetRepeatCnt(QString, QString)", trCode, recordName)

    # Tran 데이터, 실시간 데이터, 체결잔고 데이터를 반환한다.
    # 1. Tran 데이터
    # 2. 실시간 데이터
    # 3. 체결 데이터
    @pyqtSlot(str, str, str, int, str, result=str)
    def commGetData(self, jongmokCode, realType, fieldName, index, innerFieldName):
        return self.ocx.dynamicCall("CommGetData(QString, QString, QString, int, QString)", jongmokCode, realType, fieldName, index, innerFieldName).strip()

    # 1. Tran 데이터
    # sJongmokCode : Tran명
    # sRealType : 사용안함
    # sFieldName : 레코드명
    # nIndex : 반복인덱스
    # sInnerFieldName: 아이템명
    @pyqtSlot(str, str, int, str, result=str)
    def plusGetTrData(self, jongmokCode, fieldName, index, innerFieldName):
        return self.commGetData(jongmokCode, "", fieldName, index, innerFieldName)

    # 2. 실시간 데이터
    # sJongmokCode : Key Code
    # sRealType : Real Type
    # sFieldName : Item Index (FID)
    # nIndex : 사용안함
    # sInnerFieldName:사용안함
    @pyqtSlot(str, str, str, result=str)
    def plusGetRealData(self, jongmokCode, realType, fieldName):
        return self.commGetData(jongmokCode, realType, fieldName, 0, "")

    # 3. 체결 데이터
    # sJongmokCode : 체결구분
    # sRealType : “-1”
    # sFieldName : 사용안함
    # nIndex : ItemIndex
    # sInnerFieldName:사용안함
    @pyqtSlot(str, int, result=str)
    def plusGetTradeData(self, jongmokCode, index):
        return self.commGetData(jongmokCode, "-1", "", index, "")

    # 주식 주문을 서버로 전송한다.
    # sRQName - 사용자 구분 요청 명
    # sScreenNo - 화면번호[4]
    # sAccNo - 계좌번호[10]
    # nOrderType - 주문유형 (1:신규매수, 2:신규매도, 3:매수취소, 4:매도취소, 5:매수정정, 6:매도정정)
    # sCode, - 주식종목코드
    # nQty – 주문수량
    # nPrice – 주문단가
    # sHogaGb - 거래구분
    # sHogaGb – 00:지정가, 03:시장가, 05:조건부지정가, 06:최유리지정가, 07:최우선지정가, 10:지정가IOC, 13:시장가IOC, 16:최유리IOC, 20:지정가FOK, 23:시장가FOK, 26:최유리FOK, 61:장전시간외종가, 62:시간외단일가, 81:장후시간외종가
    # ※ 시장가, 최유리지정가, 최우선지정가, 시장가IOC, 최유리IOC, 시장가FOK, 최유리FOK, 장전시간외, 장후시간외 주문시 주문가격을 입력하지 않습니다.
    # ex)
    # 지정가 매수 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 1, “000660”, 10, 48500, “00”, “”);
    # 시장가 매수 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 1, “000660”, 10, 0, “03”, “”);
    # 매수 정정 - openApi.SendOrder(“RQ_1”,“0101”, “5015123410”, 5, “000660”, 10, 49500, “00”, “1”);
    # 매수 취소 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 3, “000660”, 10, “00”, “2”);
    # sOrgOrderNo – 원주문번호
    @pyqtSlot(str, str, str, int, str, int, int, str, str, result=int)
    def sendOrder(self, rQName, screenNo, accNo, orderType, code, qty, price, hogaGb, orgOrderNo ):
        return self.ocx.dynamicCall("SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)", rQName, screenNo, accNo, orderType, code, qty, price, hogaGb, orgOrderNo)

    # 체결잔고 데이터를 반환한다.
    @pyqtSlot(int, result=str)
    def getChejanData(self, fid):
        return self.ocx.dynamicCall("GetChejanData(int)", fid)

    # 서버에 저장된 사용자 조건식을 가져온다.
    @pyqtSlot(result=int)
    def getConditionLoad(self):
        return self.ocx.dynamicCall("GetConditionLoad()")

    # 조건검색 조건명 리스트를 받아온다.
    # 조건명 리스트(인덱스^조건명)
    # 조건명 리스트를 구분(“;”)하여 받아온다
    @pyqtSlot(result=str)
    def getConditionNameList(self):
        return self.ocx.dynamicCall("GetConditionNameList()")

    # 조건검색 종목조회TR송신한다.
    # LPCTSTR strScrNo : 화면번호
    # LPCTSTR strConditionName : 조건명
    # int nIndex : 조건명인덱스
    # int nSearch : 조회구분(0:일반조회, 1:실시간조회, 2:연속조회)
    # 1:실시간조회의 화면 개수의 최대는 10개
    @pyqtSlot(str, str, int, int)
    def sendCondition(self, scrNo, conditionName, index, search):
        self.ocx.dynamicCall("SendCondition(QString,QString, int, int)", scrNo, conditionName, index, search)

    # 실시간 조건검색을 중지합니다.
    # ※ 화면당 실시간 조건검색은 최대 10개로 제한되어 있어서 더 이상 실시간 조건검색을 원하지 않는 조건은 중지해야만 카운트 되지 않습니다.
    @pyqtSlot(str, str, int)
    def sendConditionStop(self, scrNo, conditionName, index):
        self.ocx.dynamicCall("SendConditionStop(QString, QString, int)", scrNo, conditionName, index)


    # 복수종목조회 Tran을 서버로 송신한다.
    # OP_ERR_RQ_STRING – 요청 전문 작성 실패
    # OP_ERR_NONE - 정상처리
    #
    # sArrCode – 종목간 구분은 ‘;’이다.
    # nTypeFlag – 0:주식관심종목정보, 3:선물옵션관심종목정보
    # @pyqtSlot(str, bool, int, int, str, str)
    # def commKwRqData(self, arrCode, next, codeCount, typeFlag, rQName, screenNo):
    # 	self.ocx.dynamicCall("CommKwRqData(QString, QBoolean, int, int, QString, QString)", arrCode, next, codeCount, typeFlag, rQName, screenNo)

    # 실시간 등록을 한다.
    # strScreenNo : 화면번호
    # strCodeList : 종목코드리스트(ex: 039490;005930;…)
    # strFidList : FID번호(ex:9001;10;13;…)
    # 	9001 – 종목코드
    # 	10 - 현재가
    # 	13 - 누적거래량
    # strOptType : 타입(“0”, “1”)
    # 타입 “0”은 항상 마지막에 등록한 종목들만 실시간등록이 됩니다.
    # 타입 “1”은 이전에 실시간 등록한 종목들과 함께 실시간을 받고 싶은 종목을 추가로 등록할 때 사용합니다.
    # ※ 종목, FID는 각각 한번에 실시간 등록 할 수 있는 개수는 100개 입니다.
    @pyqtSlot(str, str, str, str)
    def setRealReg(self, screenNo, codeList, fidList, optType):
        self.ocx.dynamicCall("SetRealReg(QString, QString, QString, QString)", screenNo, codeList, fidList, realType)

    # 종목별 실시간 해제
    # strScrNo : 화면번호
    # strDelCode : 실시간 해제할 종목코드
    # -화면별 실시간해제
    # 여러 화면번호로 걸린 실시간을 해제하려면 파라메터의 화면번호와 종목코드에 “ALL”로 입력하여 호출하시면 됩니다.
    # SetRealRemove(“ALL”, “ALL”);
    # 개별화면별로 실시간 해제 하시려면 파라메터에서 화면번호는 실시간해제할
    # 화면번호와 종목코드에는 “ALL”로 해주시면 됩니다.
    # SetRealRemove(“0001”, “ALL”);
    # -화면의 종목별 실시간해제
    # 화면의 종목별로 실시간 해제하려면 파라메터에 해당화면번호와 해제할
    # 종목코드를 입력하시면 됩니다.
    # SetRealRemove(“0001”, “039490”);
    @pyqtSlot(str, str)
    def setRealRemove(self, scrNo, delCode):
        self.ocx.dynamicCall("SetRealRemove(QString, QString)", scrNo, delCode)

    # 차트 조회한 데이터 전부를 배열로 받아온다.
    # LPCTSTR strTrCode : 조회한TR코드
    # LPCTSTR strRecordName: 조회한 TR명
    # ※항목의 위치는 KOA Studio의 TR목록 순서로 데이터를 가져옵니다.
    # 예로 OPT10080을 살펴보면 OUTPUT의 멀티데이터의 항목처럼 현재가, 거래량, 체결시간등 순으로 항목의 위치가 0부터 1씩 증가합니다.
    @pyqtSlot(str, str, result=str)
    def getCommDataEx(self, trCode, recordName):
        return json.dumps(self.ocx.dynamicCall("GetCommDataEx(QString, QString)", trCode, recordName))

    # 리얼 시세를 끊는다.
    # 화면 내 모든 리얼데이터 요청을 제거한다.
    # 화면을 종료할 때 반드시 위 함수를 호출해야 한다.
    # Ex) openApi.DisconnectRealData(“0101”);
    @pyqtSlot(str)
    def disconnectRealData(self, scnNo):
        self.ocx.dynamicCall("DisconnectRealData(QString)", scnNo)
Esempio n. 31
0
class Interview(QWidget):
    def __init__(self):
        super(Interview,self).__init__()
        global model2
        model2 = keras.models.load_model('my_model1.h5')
        self.initUi()

    def initUi(self):
        self.createGridGroupBox()
        self.undercamera()
        self.resize(1500,900)
        self.timer_camera = QtCore.QTimer() # 定時器
        self.timer_picture = QtCore.QTimer() # 定時器
        self.timer_crop = QtCore.QTimer() # 定時器
        self.timer_deception = QtCore.QTimer() # 定時器
        self.cap = cv2.VideoCapture() # 準備獲取圖像
        self.CAM_NUM = 0    
        mainLayout = QHBoxLayout() 
        vboxLayout = QVBoxLayout()
        self.label_face = QLabel()
        vboxLayout.addWidget(self.label_face)
        self.label_face.setFixedSize(680,455)
        self.axWidget = QAxWidget()
        self.axWidget.setFixedSize(750, 900)
        vboxLayout.addLayout(self.finallayout)
        mainLayout.addWidget(self.axWidget)
        mainLayout.addLayout(vboxLayout)
        mainLayout.addWidget(self.gridGroupBox)
        self.setLayout(mainLayout)
        self.setWindowIcon(QtGui.QIcon("man.png"))
        self.setWindowTitle('Main Window')
        self.button_open_camera_click()
        self.timer_camera.timeout.connect(self.show_camera)
        self.Oneshots()
        path = 'D:\\Swift Desktop\\Yi-Ting_CV  (2018).docx'                            
        self.openOffice(path,'Word.Application')
        
    def createGridGroupBox(self):
        self.gridGroupBox = QGroupBox("")
        self.groupBox = QGroupBox("")
        self.layout = QGridLayout()
        font = QtGui.QFont('微軟正黑',15)
        font2 = QtGui.QFont('微軟正黑',10)
        nameLabel = QLabel("I.五大人格分析:")
        nameLabel.setFont(font)
        nameLabel_1 = QLabel("外向性:")
        nameLabel_1.setFont(font2)
        nameLabel_2 = QLabel("情緒不穩定性:")
        nameLabel_2.setFont(font2)
        nameLabel_3 = QLabel("親和性:")
        nameLabel_3.setFont(font2)
        nameLabel_4 = QLabel("盡責性:")
        nameLabel_4.setFont(font2)
        nameLabel_5 = QLabel("經驗開放性:")
        nameLabel_5.setFont(font2)
        setting = QPushButton("設定")
        setting.setIcon(QIcon("setting.png"))
        self.fig = plt.figure(facecolor='none')      
        self.canvas = FigureCanvas(self.fig)
        plt.close()   
        button_plot = QPushButton("人格分析")
        self.layout.addWidget(self.canvas,7,0,1,6)
        self.layout.addWidget(button_plot,8,5)
        self.layout.setSpacing(5)
        self.layout.addWidget(setting,0,0,1,6)
        self.layout.addWidget(nameLabel,1,0,1,2)
        self.layout.addWidget(nameLabel_1,2,0,1,2)
        self.layout.addWidget(nameLabel_2,3,0,1,2)
        self.layout.addWidget(nameLabel_3,4,0,1,2)
        self.layout.addWidget(nameLabel_4,5,0,1,2)
        self.layout.addWidget(nameLabel_5,6,0,1,2)
        self.gridGroupBox.setLayout(self.layout)
        setting.clicked.connect(self.settingwidgets)
        button_plot.clicked.connect(self.personality)
        
        
    def undercamera(self):
        self.finallayout = QGridLayout()
        Done = QPushButton("計算匹配度")
        Done.clicked.connect(self.match)
        self.Grade = QLineEdit("")
        self.Grade.setFrame(False)       
        self.Grade.returnPressed.connect(self.check)
        ansLabel = QLabel("回答分數(0-100):")
        font = QtGui.QFont('微軟正黑',15)
        ansLabel.setFont(font)       
        finalLabel = QLabel("匹配度:")
        finalLabel.setFont(font)     
        font2 = QtGui.QFont('微軟正黑',80)
        TrueLabel = QLabel("II.真實度判定:")
        TrueLabel.setFont(font)
        font3 = QtGui.QFont('微軟正黑體',13)
        self.predictLabel = QLabel()
        self.predictLabel.setFont(font3)
        self.finallayout.addWidget(self.predictLabel,1,0,1,2)
        self.finallayout.addWidget(TrueLabel,0,0,1,2)
        self.finallayout.addWidget(ansLabel,2,0)
        self.finallayout.addWidget(self.Grade,2,1)
        self.finallayout.addWidget(finalLabel,0,3,1,2) 
        self.finallayout.addWidget(Done,8,5)
        self.i = 0
        self.total = 0
        
    def check(self):
        txt = self.Grade.text()
        font = QtGui.QFont('微軟正黑',15)
        value_lst = []
        self.i += 1
        if (txt != 0):
            value_lst.append(txt)
            self.Grade.clear()
            print (value_lst)
            grade = int(value_lst[0])
            self.total += grade
            print (self.total)
            num = QLabel(value_lst[0])
            num.setFont(font)
            quesnum = QLabel(str(self.i)+'.')
            quesnum.setFont(font)
            self.finallayout.addWidget(quesnum,2+self.i,0)
            self.finallayout.addWidget(num,2+self.i,1)
            self.averge = self.total/self.i
            print (self.averge)
    

    def button_open_camera_click(self):
        if self.timer_camera.isActive() == False:
            flag = self.cap.open(self.CAM_NUM)
            if flag == False:
                msg = QMessageBox.warning(
                    self, u"Warning", u"請檢測相機與電腦是否連接正確",
                    buttons=QMessageBox.Ok,
                    defaultButton=QMessageBox.Ok)
            else:
                self.timer_camera.start(0.1)



    def show_camera(self):
        flag, self.image = self.cap.read()

        self.image=cv2.flip(self.image, 1) # 左右翻轉
        show = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)

        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
        self.label_face.setPixmap(QtGui.QPixmap.fromImage(showImage))
        self.label_face.setScaledContents(True)
    
    #第一部分拍照        
    def Onetake(self):
        now_time = time.strftime('%m-%d-%H-%M-%S',time.localtime(time.time()))
        path = "D:\\Aubrey_file\\Main\\Personality"
        if not os.path.isdir(path):
            os.mkdir(path)
        cv2.imwrite(path+'\\pic_'+str(now_time)+'.jpg',self.image)
        
            
    def Oneshots(self):
        c = 1
        if self.cap.isOpened():
            rval,frame = self.cap.read()
        else:
            rval = False
            print("read error")
        while rval:
            if(c <= 20):
                self.timer_crop.start(1000)
                self.timer_crop.timeout.connect(self.Onetake)
                c = c + 1
            else:
                break
    
    #第二部分拍照
    def takePhoto(self):
        now_time = time.strftime('%m-%d-%H-%M-%S',time.localtime(time.time()))
        folderpath = 'D:\\Aubrey_file\\Main\\Capture'
        list = os.listdir(folderpath) # dir is your directory path
        number_files = len(list)
        if (number_files <=14):
                cv2.imwrite(os.path.join(folderpath , 'pic_' + str(now_time) + '.jpg'), self.image)
        else:
                self.autocrop(folderpath)

            
    def anaoshots(self):
        if self.cap.isOpened():
            rval,frame = self.cap.read()
            self.calldeception()
            c = 1
            while rval:
                    if(c <= 15):
                            self.timer_picture.start(1000)
                            self.timer_picture.timeout.connect(self.takePhoto)
                            c = c + 1
                    else:
                            break
        else:
            rval = False
            print("read error")
        
                
          
    def calldeception(self):
        c = 1
        global vgg_model_new
        vgg_model_new = keras.models.load_model('vgg_feature.h5')
        if(c <= 20):
                self.timer_deception.start(20000)
                self.timer_deception.timeout.connect(self.deception)
                c = c + 1
            
            
    def autocrop(self, path):
        temp = path    #截圖先存這
        cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done1"   #autocrop過的圖
        list = os.listdir(cnt_path) # dir is your directory path
        number_files = len(list)
        if (number_files <=14):
                img_path = "D:\\Aubrey_file\\Main\\Done\\Done1"
        else:
                cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done2"   #autocrop過的圖
                list = os.listdir(cnt_path) # dir is your directory path
                number_files = len(list)
                if (number_files <=14):
                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done2'
                else:
                        cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done3"   #autocrop過的圖
                        list = os.listdir(cnt_path) # dir is your directory path
                        number_files = len(list)
                        if (number_files <=14):
                                img_path = 'D:\\Aubrey_file\\Main\\Done\\Done3'
                        else:
                                cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done4"   #autocrop過的圖
                                list = os.listdir(cnt_path) # dir is your directory path
                                number_files = len(list)
                                if (number_files <=14):
                                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done4'
                                else:
                                        cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done5"   #autocrop過的圖
                                        list = os.listdir(cnt_path) # dir is your directory path
                                        number_files = len(list)
                                        if (number_files <=14):
                                                img_path = 'D:\\Aubrey_file\\Main\\Done\\Done5'
                                        else:
                                                cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done6"   #autocrop過的圖
                                                list = os.listdir(cnt_path) # dir is your directory path
                                                number_files = len(list)
                                                if (number_files <=14):
                                                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done6'
                                                else:
                                                        cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done7"   #autocrop過的圖
                                                        list = os.listdir(cnt_path) # dir is your directory path
                                                        number_files = len(list)
                                                        if (number_files <=14):
                                                                img_path = 'D:\\Aubrey_file\\Main\\Done\\Done7'
                                                        else:
                                                                cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done8"   #autocrop過的圖
                                                                list = os.listdir(cnt_path) # dir is your directory path
                                                                number_files = len(list)
                                                                if (number_files <=14):
                                                                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done8' 
                                                                else:
                                                                        cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done9"   #autocrop過的圖
                                                                        list = os.listdir(cnt_path) # dir is your directory path
                                                                        number_files = len(list)
                                                                        if (number_files <=14):
                                                                                img_path = 'D:\\Aubrey_file\\Main\\Done\\Done9'
                                                                        else:
                                                                                cnt_path = "D:\\Aubrey_file\\Main\\Done\\Done10"   #autocrop過的圖
                                                                                list = os.listdir(cnt_path) # dir is your directory path
                                                                                number_files = len(list)
                                                                                if (number_files <=14):
                                                                                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done10'
        reject = "D:\\Aubrey_file\\Main\\Reject"   #偵測不到臉的圖
        command = "autocrop -i {} -o {} -r {} -w 224 -H 224".format(temp,img_path,reject)
        subprocess.call(command, shell=True)
        
        
    def close(self):
        if self.timer_camera.isActive() != False:
            ok = QPushButton()
            cacel = QPushButton()

            msg = QMessageBox(QMessageBox.Warning, u"關閉", u"是否關閉!")

            msg.addButton(ok,QMessageBox.ActionRole)
            msg.addButton(cacel, QMessageBox.RejectRole)
            ok.setText(u'確定')
            cacel.setText(u'取消')

            if msg.exec_() != QMessageBox.RejectRole:

                if self.cap.isOpened():
                    self.cap.release()
                if self.timer_camera.isActive():
                    self.timer_camera.stop()
                    self.timer_picture.stop()
                    self.timer_deception.stop()
                    
            
        
    def openOffice(self, path, app):
        if not self.axWidget.setControl(app):
            return QMessageBox.critical(self, '錯誤', '没有安装  %s' % app)
        self.axWidget.dynamicCall(
            'SetVisible (bool Visible)', 'false')  # 不显示窗体
        self.axWidget.setProperty('DisplayAlerts', False)
        self.axWidget.setControl(path)
        self.axWidget.show()
        
    def about(self):     
        msgBox = QMessageBox(QMessageBox.NoIcon, 'Final','匹配度:80')
        msgBox.setIcon(1)
        msgBox.exec()
        
    def settingwidgets(self):
        self.dia = Set()
        self.dia.show()
        
    def MyFigure(self):
        angles = np.linspace(0, 2 * np.pi, 5, endpoint=False)
        angles = np.concatenate((angles, [angles[0]]))
        ax = self.fig.add_subplot(111, polar=True,) 
        data = [(prediction[0][0]*2), (prediction[0][1]*2), (prediction[0][2]*2), (prediction[0][3]*2), (prediction[0][4]*2), (prediction[0][0]*2)]
        # 绘制三个五边形
        floor = 0
        ceil = 2
        labels = np.array(['Extraversion', 'Neuroticism', 'Agreeableness', 'Conscientiousness', 'Openness to Experience'])
        # 绘制五边形的循环
        for i in np.arange(floor, ceil + 0.5 ,0.5):
            ax.plot(angles, [i] * (6), '-', lw= 0.5, color='black')
        for i in range(5):
            ax.plot([angles[i], angles[i]], [floor, ceil], '-',lw=0.5, color='black')
         # 绘制雷达图
        ax.plot(angles, data, 'b-', lw=2, alpha=0.35)
        ax.fill(angles, data, facecolor='b', alpha=0.25)
    
        ax.set_thetagrids(angles * 180 / np.pi, labels)
        ax.spines['polar'].set_visible(False)#不显示极坐标最外的圆形
        ax.set_theta_zero_location('N')#设置极坐标的起点(即0度)在正上方向
        ax.grid(False)# 不显示分隔线
        ax.set_yticks([]) # 不显示坐标间隔
        self.canvas.draw()  
         
    #part1
    def personality(self):
            self.timer_crop.stop()
            self.anaoshots()
            init_op = tf.initialize_all_variables()
            with tf.Session() as sess:
                    labels = ["ValueExtraversion","ValueNeuroticism","ValueAgreeableness","ValueConscientiousness","ValueOpenness"]
                    sess.run(init_op)
  
                    def load_model():
                            # Load graph and parameters, etc.
                            global imgs, output
                            modelpath = 'D:\\Aubrey_file\\Main\\model1'
                            saver= tf.train.import_meta_graph(modelpath + '\\model_full.meta')
                            saver.restore(sess, tf.train.latest_checkpoint(modelpath))
                            graph = tf.get_default_graph()
                            # Get tensor names
                            imgs = graph.get_tensor_by_name("image_placeholder:0")
                            output = graph.get_tensor_by_name("output:0")
                            #print(output)
                    def load_image(addr):
                            img = np.array(Image.open(addr).resize((224,224), Image.ANTIALIAS))
                            img = img.astype(np.uint8)
                            return img
  
                    def predict(img):
                            global imgs, prediction
                            feed_dict ={imgs: [img]}
                            prediction = sess.run(output,feed_dict=feed_dict)
                            return prediction
                    
                    global array_of_addr
                    array_of_addr = []
                    # this function is for read image,the input is directory name
                    directory_name = 'D:\\Aubrey_file\\Main\\Personality'
                    for filename in os.listdir(directory_name):
                            array_of_addr.append(directory_name + "\\" + filename)
                    for i in array_of_addr:
                            testdata = load_image(i)
                    load_model()
                    print("finish loading!")
                    global prediction
                    prediction = predict(testdata)
                    print(prediction)
                    print("ValueExtraversion: %.3f" %(prediction[0][0]))
                    print("ValueNeuroticism: %.3f" %(prediction[0][1]))
                    print("ValueAgreeableness: %.3f"  %(prediction[0][2]))
                    print("ValueConscientiousness: %.3f" %(prediction[0][3]))
                    print("ValueOpenness: %.3f"  %(prediction[0][4]))
            font2 = QtGui.QFont('微軟正黑',10)        
            scoreLabel_1 = QLabel(str(round(prediction[0][0], 3)))
            scoreLabel_1.setFont(font2)
            self.layout.addWidget(scoreLabel_1,2,2,1,2)
            scoreLabel_2 = QLabel(str(round(prediction[0][1], 3)))
            scoreLabel_2.setFont(font2)
            self.layout.addWidget(scoreLabel_2,3,2,1,2)
            scoreLabel_3 = QLabel(str(round(prediction[0][2], 3)))
            scoreLabel_3.setFont(font2)
            self.layout.addWidget(scoreLabel_3,4,2,1,2)
            scoreLabel_4 = QLabel(str(round(prediction[0][3], 3)))
            scoreLabel_4.setFont(font2)
            self.layout.addWidget(scoreLabel_4,5,2,1,2)
            scoreLabel_5 = QLabel(str(round(prediction[0][4], 3)))
            scoreLabel_5.setFont(font2)
            self.layout.addWidget(scoreLabel_5,6,2,1,2)
            self.MyFigure()
    """
    def personality(self):
            self.timer_crop.stop()
            self.anaoshots()
            self.person = Personality()
            font2 = QtGui.QFont('微軟正黑',10) 
            scoreLabel_1 = QLabel(str(round(prediction[0][0], 3)))
            scoreLabel_1.setFont(font2)
            self.layout.addWidget(scoreLabel_1,2,2,1,2)
            scoreLabel_2 = QLabel(str(round(prediction[0][1], 3)))
            scoreLabel_2.setFont(font2)
            self.layout.addWidget(scoreLabel_2,3,2,1,2)
            scoreLabel_3 = QLabel(str(round(prediction[0][2], 3)))
            scoreLabel_3.setFont(font2)
            self.layout.addWidget(scoreLabel_3,4,2,1,2)
            scoreLabel_4 = QLabel(str(round(prediction[0][3], 3)))
            scoreLabel_4.setFont(font2)
            self.layout.addWidget(scoreLabel_4,5,2,1,2)
            scoreLabel_5 = QLabel(str(round(prediction[0][4], 3)))
            scoreLabel_5.setFont(font2)
            self.layout.addWidget(scoreLabel_5,6,2,1,2)
            self.MyFigure()
    """        
                 
    #part2
    def deception(self):
        for i in range(1, 10):
                if os.path.isfile('D:\\Aubrey_file\\Main\\Deception\\' +str(i)+'.txt'):
                        i = i + 1
                else:
                        img_path = 'D:\\Aubrey_file\\Main\\Done\\Done' +str(i)
                        df = testt.extract_metadata(img_path)
                        df.loc[:,'path'] = df.path.apply(lambda path: os.path.join(img_path, path))
                        test = testt.to_tensors(df) 
                        test_features = testt.features_extractor(test , vgg_model_new)
                        test_features = np.reshape(test_features, (test_features.shape[0], 1, test_features.shape[1]))
                               
                        custom = model2.predict_classes(test_features)
                        d = 0
                        t = 0
                        for c in custom:
                                if c ==0:
                                        d = d + 1
                                else:
                                        t = t + 1
                        percent = round((t / 15)*100, 2)
                        txt_path = 'D:\\Aubrey_file\\Main\\Deception\\' +str(i)+'.txt'
                        f = open(txt_path, 'w')
                        self.new = str(percent)
                        self.predictLabel.setText('Truthful '+self.new+'%')      
                        
    def match(self):
        self.extroversion_w = int(extroversion)
        self.agreeableness_w = int(agreeableness)
        self.neuroticism_w = int(neuroticism)
        self.conscientiousness_w = int(conscientiousness)
        self.openness_w = int(openness_to_experience)
        self.weight1 = int(part1)/100
        self.weight2 = int(part2)/100
        #小數點那些是人格的分數,我先寫死
        traitscore = self.extroversion_w*(round(prediction[0][0], 1)) + self.agreeableness_w*(round(prediction[0][1], 1)) + self.neuroticism_w*(round(prediction[0][2], 1)) + self.conscientiousness_w*(round(prediction[0][3], 1)) + self.openness_w*(round(prediction[0][4], 1))
        trait = traitscore*self.weight1
        print(trait)
        quesscore = self.averge*self.weight2
        match = trait + quesscore
        print (int(match))
        matchint = int(match)
        final = QLabel(str(matchint))
        font2 = QtGui.QFont('微軟正黑',80)
        final.setFont(font2)
        self.finallayout.addWidget(final,2,3,6,3)
        self.close()
Esempio n. 32
0
class Interview(QWidget):
    def __init__(self):
        super(Interview, self).__init__()
        global modelpath, saver, model2, vgg_model_new
        modelpath = 'D:\\Aubrey_file\\Main\\model1'
        saver = tf.train.import_meta_graph(modelpath + '\\model_full.meta')
        model2 = keras.models.load_model('my_model.h5')
        init_op = tf.initialize_all_variables()
        global sess
        sess = tf.Session()
        labels = [
            "ValueExtraversion", "ValueNeuroticism", "ValueAgreeableness",
            "ValueConscientiousness", "ValueOpenness"
        ]
        sess.run(init_op)
        # Load graph and parameters, etc.
        global imgs, output

        saver.restore(sess, tf.train.latest_checkpoint(modelpath))
        graph = tf.get_default_graph()
        # Get tensor names
        imgs = graph.get_tensor_by_name("image_placeholder:0")
        output = graph.get_tensor_by_name("output:0")
        #print(output)
        self.initUi()
        global camera
        camera = Camera()
        camera.show()

    def initUi(self):
        self.createGridGroupBox()
        self.undercamera()
        self.resize(1500, 900)
        self.setGeometry(20, 50, 1500, 900)
        #self.timer_camera = QtCore.QTimer() # 定時器
        #self.timer_picture = QtCore.QTimer() # 定時器
        #self.timer_crop = QtCore.QTimer() # 定時器
        #self.timer_deception = QtCore.QTimer() # 定時器
        global timer_deception
        timer_deception = QtCore.QTimer()
        """
        self.cap = cv2.VideoCapture() # 準備獲取圖像
        self.CAM_NUM = 0 """
        mainLayout = QHBoxLayout()
        vboxLayout = QVBoxLayout()
        """
        self.label_face = QLabel()
        vboxLayout.addWidget(self.label_face)
        self.label_face.setFixedSize(680,455)"""
        self.grey_area = QLabel()
        vboxLayout.addWidget(self.grey_area)
        self.grey_area.setFixedSize(680, 455)

        self.axWidget = QAxWidget()
        self.axWidget.setFixedSize(750, 900)
        vboxLayout.addLayout(self.finallayout)
        mainLayout.addWidget(self.axWidget)
        mainLayout.addLayout(vboxLayout)
        mainLayout.addWidget(self.gridGroupBox)
        self.setLayout(mainLayout)
        self.setWindowIcon(QtGui.QIcon("man.png"))
        self.setWindowTitle('Main Window')
        """
        self.button_open_camera_click()
        self.timer_camera.timeout.connect(self.show_camera)
        self.Oneshots()"""
        path = 'D:\\Swift Desktop\\Yi-Ting_CV  (2018).docx'
        self.openOffice(path, 'Word.Application')

    def createGridGroupBox(self):
        self.gridGroupBox = QGroupBox("")
        self.groupBox = QGroupBox("")
        self.layout = QGridLayout()
        font = QtGui.QFont('微軟正黑', 16)
        font.setBold(True)
        font2 = QtGui.QFont('微軟正黑', 13)
        nameLabel = QLabel("I.五大人格分析:")
        nameLabel.setFont(font)
        nameLabel_1 = QLabel("外向性:")
        nameLabel_1.setFont(font2)
        nameLabel_2 = QLabel("情緒不穩定性:")
        nameLabel_2.setFont(font2)
        nameLabel_3 = QLabel("親和性:")
        nameLabel_3.setFont(font2)
        nameLabel_4 = QLabel("盡責性:")
        nameLabel_4.setFont(font2)
        nameLabel_5 = QLabel("經驗開放性:")
        nameLabel_5.setFont(font2)
        setting = QPushButton("設定")
        setting.setIcon(QIcon("setting.png"))
        self.fig = plt.figure(facecolor='none')
        self.canvas = FigureCanvas(self.fig)
        plt.close()
        button_plot = QPushButton("人格分析")
        self.layout.addWidget(self.canvas, 7, 0, 1, 6)
        self.layout.addWidget(button_plot, 8, 5)
        self.layout.setSpacing(5)
        self.layout.addWidget(setting, 0, 0, 1, 6)
        self.layout.addWidget(nameLabel, 1, 0, 1, 2)
        self.layout.addWidget(nameLabel_1, 2, 0, 1, 2)
        self.layout.addWidget(nameLabel_2, 3, 0, 1, 2)
        self.layout.addWidget(nameLabel_3, 4, 0, 1, 2)
        self.layout.addWidget(nameLabel_4, 5, 0, 1, 2)
        self.layout.addWidget(nameLabel_5, 6, 0, 1, 2)
        self.gridGroupBox.setLayout(self.layout)
        setting.clicked.connect(self.settingwidgets)
        button_plot.clicked.connect(self.personality)

    def undercamera(self):
        self.finallayout = QGridLayout()
        Done = QPushButton("計算匹配度")
        Done.clicked.connect(self.match)
        self.Grade = QLineEdit("")
        self.Grade.setFrame(False)
        self.Grade.returnPressed.connect(self.check)
        ansLabel = QLabel("回答分數(0-100):")
        font = QtGui.QFont('微軟正黑', 16)
        font1 = QtGui.QFont('微軟正黑', 16)
        font1.setBold(True)
        ansLabel.setFont(font)
        finalLabel = QLabel("匹配度:")
        finalLabel.setFont(font)
        font2 = QtGui.QFont('微軟正黑', 80)
        TrueLabel = QLabel("II.真實度判定:")
        TrueLabel.setFont(font1)
        font3 = QtGui.QFont('微軟正黑體', 13)
        self.predictLabel = QLabel()
        self.predictLabel.setFont(font3)
        self.finallayout.addWidget(self.predictLabel, 1, 0, 1, 2)
        self.finallayout.addWidget(TrueLabel, 0, 0, 1, 2)
        self.finallayout.addWidget(ansLabel, 2, 0)
        self.finallayout.addWidget(self.Grade, 2, 1)
        self.finallayout.addWidget(finalLabel, 0, 3, 1, 2)
        self.finallayout.addWidget(Done, 8, 5)
        self.i = 0
        self.total = 0

    def check(self):
        txt = self.Grade.text()
        font = QtGui.QFont('微軟正黑', 16)
        value_lst = []
        self.i += 1
        if (txt != 0):
            value_lst.append(txt)
            self.Grade.clear()
            print(value_lst)
            grade = int(value_lst[0])
            self.total += grade
            print(self.total)
            num = QLabel(value_lst[0])
            num.setFont(font)
            quesnum = QLabel(str(self.i) + '.')
            quesnum.setFont(font)
            self.finallayout.addWidget(quesnum, 2 + self.i, 0)
            self.finallayout.addWidget(num, 2 + self.i, 1)
            self.averge = self.total / self.i
            print(self.averge)

    def calldeception(self):
        c = 1
        if (c <= 20):
            timer_deception.start(20000)
            timer_deception.timeout.connect(self.deception)
            c = c + 1

    def openOffice(self, path, app):
        if not self.axWidget.setControl(app):
            return QMessageBox.critical(self, '錯誤', '没有安装  %s' % app)
        self.axWidget.dynamicCall('SetVisible (bool Visible)',
                                  'false')  # 不显示窗体
        self.axWidget.setProperty('DisplayAlerts', False)
        self.axWidget.setControl(path)
        self.axWidget.show()

    def about(self):
        msgBox = QMessageBox(QMessageBox.NoIcon, 'Final', '匹配度:80')
        msgBox.setIcon(1)
        msgBox.exec()

    def settingwidgets(self):
        self.dia = Set()
        self.dia.show()

    def MyFigure(self):
        angles = np.linspace(0, 2 * np.pi, 5, endpoint=False)
        angles = np.concatenate((angles, [angles[0]]))
        ax = self.fig.add_subplot(
            111,
            polar=True,
        )
        data = [(prediction[0][0] * 2), (prediction[0][1] * 2),
                (prediction[0][2] * 2), (prediction[0][3] * 2),
                (prediction[0][4] * 2), (prediction[0][0] * 2)]
        # 绘制三个五边形
        floor = 0
        ceil = 2
        labels = np.array([
            'Extraversion', 'Neuroticism', 'Agreeableness',
            'Conscientiousness', 'Openness to Experience'
        ])
        # 绘制五边形的循环
        for i in np.arange(floor, ceil + 0.5, 0.5):
            ax.plot(angles, [i] * (6), '-', lw=0.5, color='black')
        for i in range(5):
            ax.plot([angles[i], angles[i]], [floor, ceil],
                    '-',
                    lw=0.5,
                    color='black')
        # 绘制雷达图
        ax.plot(angles, data, 'b-', lw=2, alpha=0.35)
        ax.fill(angles, data, facecolor='b', alpha=0.25)

        ax.set_thetagrids(angles * 180 / np.pi, labels)
        ax.spines['polar'].set_visible(False)  #不显示极坐标最外的圆形
        ax.set_theta_zero_location('N')  #设置极坐标的起点(即0度)在正上方向
        ax.grid(False)  # 不显示分隔线
        ax.set_yticks([])  # 不显示坐标间隔
        self.canvas.draw()

    def loading(self):
        self.msgBox = QMessageBox(QMessageBox.NoIcon, 'Loading', '人格特質分析中...')
        self.msgBox.setGeometry(800, 580, 0, 0)
        self.msgBox.setIcon(1)
        self.msgBox.setStandardButtons(QMessageBox.Ok)
        self.msgBox.button(QMessageBox.Ok).animateClick(10 * 1000)
        self.msgBox.exec()

    #part1
    def personality(self):
        self.loading()
        camera.anaoshots()

        def load_image(addr):
            img = np.array(
                Image.open(addr).resize((224, 224), Image.ANTIALIAS))
            img = img.astype(np.uint8)
            return img

        def predict(img):
            global imgs, prediction
            feed_dict = {imgs: [img]}
            prediction = sess.run(output, feed_dict=feed_dict)
            return prediction

        global array_of_addr
        array_of_addr = []
        # this function is for read image,the input is directory name
        directory_name = 'D:\\Aubrey_file\\Main\\Personality'
        for filename in os.listdir(directory_name):
            array_of_addr.append(directory_name + "\\" + filename)
            for i in array_of_addr:
                testdata = load_image(i)
        print("finish loading!")
        global prediction
        prediction = predict(testdata)
        print(prediction)
        print("ValueExtraversion: %.3f" % (prediction[0][0]))
        print("ValueNeuroticism: %.3f" % (prediction[0][1]))
        print("ValueAgreeableness: %.3f" % (prediction[0][2]))
        print("ValueConscientiousness: %.3f" % (prediction[0][3]))
        print("ValueOpenness: %.3f" % (prediction[0][4]))
        font2 = QtGui.QFont('微軟正黑', 13)
        scoreLabel_1 = QLabel(str(round(prediction[0][0], 3)))
        scoreLabel_1.setFont(font2)
        self.layout.addWidget(scoreLabel_1, 2, 2, 1, 2)
        scoreLabel_2 = QLabel(str(round(prediction[0][1], 3)))
        scoreLabel_2.setFont(font2)
        self.layout.addWidget(scoreLabel_2, 3, 2, 1, 2)
        scoreLabel_3 = QLabel(str(round(prediction[0][2], 3)))
        scoreLabel_3.setFont(font2)
        self.layout.addWidget(scoreLabel_3, 4, 2, 1, 2)
        scoreLabel_4 = QLabel(str(round(prediction[0][3], 3)))
        scoreLabel_4.setFont(font2)
        self.layout.addWidget(scoreLabel_4, 5, 2, 1, 2)
        scoreLabel_5 = QLabel(str(round(prediction[0][4], 3)))
        scoreLabel_5.setFont(font2)
        self.layout.addWidget(scoreLabel_5, 6, 2, 1, 2)
        self.MyFigure()
        self.calldeception()

    #part2
    def deception(self):
        for i in range(1, 10):
            if os.path.isfile('D:\\Aubrey_file\\Main\\Deception\\' + str(i) +
                              '.txt'):
                i = i + 1
            else:
                img_path = 'D:\\Aubrey_file\\Main\\Done\\Done' + str(i)
                images_features = []
                for img in os.listdir(img_path):
                    img = img_path + '\\' + img
                    img = image.load_img(img, target_size=(150, 150))
                    img = np.expand_dims(img, axis=0)
                    images_features.append(img)
                images_features = np.vstack(images_features)

                custom = model2.predict_classes(images_features)
                d = 0
                t = 0
                for c in custom:
                    if c == 0:
                        d = d + 1
                    else:
                        t = t + 1
                percent = round((t / 15) * 100, 2)
                txt_path = 'D:\\Aubrey_file\\Main\\Deception\\' + str(
                    i) + '.txt'
                f = open(txt_path, 'w')
                self.new = str(percent)
                self.predictLabel.setText('Truthful ' + self.new + '%')

    def match(self):
        self.extroversion_w = int(extroversion)
        self.agreeableness_w = int(agreeableness)
        self.neuroticism_w = int(neuroticism)
        self.conscientiousness_w = int(conscientiousness)
        self.openness_w = int(openness_to_experience)
        self.weight1 = int(part1) / 100
        self.weight2 = int(part2) / 100
        #小數點那些是人格的分數,我先寫死
        traitscore = self.extroversion_w * (round(
            prediction[0][0], 1)) + self.agreeableness_w * (round(
                prediction[0][1], 1)) + self.neuroticism_w * (round(
                    prediction[0][2], 1)) + self.conscientiousness_w * (round(
                        prediction[0][3], 1)) + self.openness_w * (round(
                            prediction[0][4], 1))
        trait = traitscore * self.weight1
        print(trait)
        quesscore = self.averge * self.weight2
        match = trait + quesscore
        print(int(match))
        matchint = int(match)
        final = QLabel(str(matchint))
        font2 = QtGui.QFont('微軟正黑', 80)
        final.setFont(font2)
        self.finallayout.addWidget(final, 2, 3, 6, 3)
        camera.close()
        conn = MySQLdb.connect(host="127.0.0.1",
                               user="******",
                               passwd="",
                               db="interview",
                               charset="utf8")
        cursor = conn.cursor()  #傳回 Cursor 物件
        matchstr = str(matchint)
        cursor.execute("UPDATE candidate SET score = '" + matchstr +
                       "' WHERE name = '曾怡瑄'")
        conn.commit()
Esempio n. 33
0
class AxWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super(AxWidget, self).__init__(*args, **kwargs)
        self.resize(800, 600)
        layout = QVBoxLayout(self)
        self.axWidget = QAxWidget(self)
        layout.addWidget(self.axWidget)
        layout.addWidget(
            QPushButton('选择excel,word,pdf文件', self, clicked=self.onOpenFile))

    def onOpenFile(self):
        path, _ = QFileDialog.getOpenFileName(
            self, '请选择文件', '',
            'excel(*.xlsx *.xls);;word(*.docx *.doc);;pdf(*.pdf)')
        if not path:
            return
        if _.find('*.doc'):
            return self.openOffice(path, 'Word.Application')
        if _.find('*.xls'):
            return self.openOffice(path, 'Excel.Application')
        if _.find('*.pdf'):
            return self.openPdf(path)

    def openOffice(self, path, app):
        self.axWidget.clear()
        if not self.axWidget.setControl(app):
            return QMessageBox.critical(self, '错误', '没有安装  %s' % app)
        self.axWidget.dynamicCall('SetVisible (bool Visible)',
                                  'false')  # 不显示窗体
        self.axWidget.setProperty('DisplayAlerts', False)
        self.axWidget.setControl(path)

    def openPdf(self, path):
        self.axWidget.clear()
        if not self.axWidget.setControl('Adobe PDF Reader'):
            return QMessageBox.critical(self, '错误', '没有安装 Adobe PDF Reader')
        self.axWidget.dynamicCall('LoadFile(const QString&)', path)

    def closeEvent(self, event):
        self.axWidget.close()
        self.axWidget.clear()
        self.layout().removeWidget(self.axWidget)
        del self.axWidget
        super(AxWidget, self).closeEvent(event)
Esempio n. 34
0
class Kiwoom():
    def __init__(self, k_queue):
        super().__init__()
        self.S_SCREEN_NO = "0001"
        self.MARKET_LIST = {
            0: '장내',
            3: 'ELW',
            4: '뮤추얼펀드',
            5: '신주인수권',
            6: '리츠',
            8: 'ETF',
            9: '하이일드펀드',
            10: '코스닥',
            30: '제3시장'
        }
        self.ORDER_TYPE = {
            1: '신규매수',
            2: '신규매도',
            3: '매수취소',
            4: '매도취소'
        }
        self.HOGA = {
            '00': '지정가',
            '03': '시장가'
        }

        self.q = k_queue
        self.qs = {
            'OnReceiveTrData': queue.Queue(),
            'OnReceiveRealData': queue.Queue(),
            'OnReceiveMsg': queue.Queue(),
            'OnReceiveChejanData': queue.Queue(),
            'OnEventConnect': queue.Queue(),
            'OnReceiveRealCondition': queue.Queue(),
            'OnReceiveTrCondition': queue.Queue(),
            'OnReceiveConditionVer': queue.Queue()
        }
        self.ocx = QAxWidget("KHOPENAPI.KHOpenAPICtrl.1")
        self.ocx.OnReceiveTrData[str, str, str, str, str, int, str, str, str].connect(self.OnReceiveTrData)
        self.ocx.OnReceiveRealData[str, str, str].connect(self.OnReceiveRealData)
        self.ocx.OnReceiveMsg[str, str, str, str].connect(self.OnReceiveMsg)
        self.ocx.OnReceiveChejanData[str, int, str].connect(self.OnReceiveChejanData)
        self.ocx.OnEventConnect[int].connect(self.OnEventConnect)
        self.ocx.OnReceiveRealCondition[str, str, str, str].connect(self.OnReceiveRealCondition)
        self.ocx.OnReceiveTrCondition[str, str, str, int, int].connect(self.OnReceiveTrCondition)
        self.ocx.OnReceiveConditionVer[int, str].connect(self.OnReceiveConditionVer)
        atexit.register(self.quit)

    ####################################################
    # Interface Methods
    ####################################################
    def comm_connect(self):
        """
        로그인 윈도우를 실행한다.
        로그인이 성공하거나 실패하는 경우 OnEventConnect 이벤트가 발생하고 이벤트의 인자 값으로 로그인 성공 여부를 알 수 있다.

        :return: 0 - 성공, 음수값은 실패
        """
        return self.ocx.dynamicCall("CommConnect()")

    def comm_rq_data(self, sRQName, sTrCode, nPrevNext, sScreenNo):
        """
        Tran을 서버로 송신한다.

        :param sRQName: 사용자구분 명
        :param sTrCode: Tran명 입력
        :param nPrevNext: 0:조회, 2:연속
        :param sScreenNo: 4자리의 화면번호
        Ex) openApi.CommRqData( “RQ_1”, “OPT00001”, 0, “0101”);
        :return:
        OP_ERR_SISE_OVERFLOW – 과도한 시세조회로 인한 통신불가
        OP_ERR_RQ_STRUCT_FAIL – 입력 구조체 생성 실패
        OP_ERR_RQ_STRING_FAIL – 요청전문 작성 실패
        OP_ERR_NONE(0) – 정상처리
        """
        return self.ocx.dynamicCall("CommRqData(QString, QString, int, QString)", sRQName, sTrCode, nPrevNext, sScreenNo)

    def get_login_info(self, sTag):
        """
        로그인한 사용자 정보를 반환한다.

        :param sTag: 사용자 정보 구분 TAG값
            “ACCOUNT_CNT” – 전체 계좌 개수를 반환한다.
            "ACCNO" – 전체 계좌를 반환한다. 계좌별 구분은 ‘;’이다.
            “USER_ID” - 사용자 ID를 반환한다.
            “USER_NAME” – 사용자명을 반환한다.
            “KEY_BSECGB” – 키보드보안 해지여부. 0:정상, 1:해지
            “FIREW_SECGB” – 방화벽 설정 여부. 0:미설정, 1:설정, 2:해지
            Ex) openApi.GetLoginInfo(“ACCOUNT_CNT”);
        :return: TAG값에 따른 데이터 반환
        """
        return self.ocx.dynamicCall("GetLoginInfo(QString)", [sTag])

    def send_order(self, sRQName, sScreenNo, sAccNo, nOrderType, sCode, nQty, nPrice, sHogaGb, sOrgOrderNo):
        """
        주식 주문을 서버로 전송한다.

        :param sRQName: 사용자 구분 요청 명
        :param sScreenNo: 화면번호[4]
        :param sAccNo: 계좌번호[10]
        :param nOrderType: 주문유형 (1:신규매수, 2:신규매도, 3:매수취소, 4:매도취소, 5:매수정정, 6:매 도정정)
        :param sCode: 주식종목코드
        :param nQty: 주문수량
        :param nPrice: 주문단가
        :param sHogaGb: 거래구분
            00:지정가, 03:시장가, 05:조건부지정가, 06:최유리지정가, 07:최우선지정가, 10: 지정가IOC, 13:시장가IOC,
            16:최유리IOC, 20:지정가FOK, 23:시장가FOK, 26:최유리FOK, 61: 장전시간외종가, 62:시간외단일가, 81:장후시간외종가
            ※ 시장가, 최유리지정가, 최우선지정가, 시장가IOC, 최유리IOC, 시장가FOK, 최유리FOK, 장전시간외, 장후시간외 주문시 주문가격을 입력하지 않습니다.
            ex)
            지정가 매수 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 1, “000660”, 10, 48500, “00”, “”);
            시장가 매수 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 1, “000660”, 10, 0, “03”, “”);
            매수 정정 - openApi.SendOrder(“RQ_1”,“0101”, “5015123410”, 5, “000660”, 10, 49500, “00”, “1”);
            매수 취소 - openApi.SendOrder(“RQ_1”, “0101”, “5015123410”, 3, “000660”, 10, 0, “00”, “2”);
        :param sOrgOrderNo: 원주문번호
        :return: 에러코드 - parse_error_code
        """
        return self.ocx.dynamicCall("SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)",
                                    [sRQName, sScreenNo, sAccNo, nOrderType, sCode, nQty, nPrice, sHogaGb, sOrgOrderNo])

    def send_order_credit(self):
        pass

    def set_input_value(self, sID, sValue):
        """
        Tran 입력 값을 서버통신 전에 입력한다.

        :param sID: 아이템명
        :param sValue: 입력 값
        Ex) openApi.SetInputValue(“종목코드”, “000660”);
            openApi.SetInputValue(“계좌번호”, “5015123401”);
        """
        self.ocx.dynamicCall("SetInputValue(QString, QString)", sID, sValue)

    def set_output_fid(self):
        pass

    def comm_get_data(self, sJongmokCode, sRealType, sFieldName, nIndex, sInnerFieldName):
        """
        Tran 데이터, 실시간 데이터, 체결잔고 데이터를 반환한다.

        1. Tran 데이터
        :param sJongmokCode: Tran명
        :param sRealType: 사용안함
        :param sFieldName: 레코드명
        :param nIndex: 반복인덱스
        :param sInnerFieldName: 아이템명

        2. 실시간 데이터
        :param sJongmokCode: Key Code
        :param sRealType: Real Type
        :param sFieldName: Item Index (FID)
        :param nIndex: 사용안함
        :param sInnerFieldName: 사용안함

        3. 체결 데이터
        :param sJongmokCode: 체결구분
        :param sRealType: “-1”
        :param sFieldName: 사용안함
        :param nIndex: ItemIndex
        :param sInnerFieldName: 사용안함

        :return: 요청 데이터
        """
        return self.ocx.dynamicCall("CommGetData(QString, QString, QString, int, QString)", sJongmokCode, sRealType,
                                    sFieldName, nIndex, sInnerFieldName)

    def disconnect_real_data(self, sScnNo):
        """
        화면 내 모든 리얼데이터 요청을 제거한다.
        화면을 종료할 때 반드시 위 함수를 호출해야 한다.

        :param sScnNo: 화면번호[4]
        Ex) openApi.DisconnectRealData(“0101”);
        """
        self.ocx.dynamicCall("DisconnectRealData(QString)", sScnNo)

    def get_repeat_cnt(self, sTrCode, sRecordName):
        """
        수신 받은 데이터의 반복 개수를 반환한다.
        레코드 반복횟수를 반환한다.

        :param sTrCode: Tran 명
        :param sRecordName: 레코드 명
        Ex) openApi.GetRepeatCnt(“OPT00001”, “주식기본정보”);
        :return: 레코드의 반복횟수
        """
        return self.ocx.dynamicCall("GetRepeatCnt(QString, QString)", sTrCode, sRecordName)

    def comm_kw_rq_data(self, sArrCode, bNext, nCodeCount, nTypeFlag, sRQName, sScreenNo):
        """
        복수종목조회 Tran을 서버로 송신한다.

        :param sArrCode: 종목리스트 - 종목간 구분은 ‘;’이다.
        :param bNext: 연속조회요청
        :param nCodeCount: 종목개수
        :param nTypeFlag: 조회구분 - 0:주식관심종목정보, 3:선물옵션관심종목정보
        :param sRQName: 사용자구분 명
        :param sScreenNo: 화면번호[4]
        ex) openApi.CommKwRqData(“000660;005930”, 0, 2, 0, “RQ_1”, “0101”);
        :return: OP_ERR_RQ_STRING – 요청 전문 작성 실패
            OP_ERR_NONE - 정상처리
        """
        return self.ocx.dynamicCall("CommKwRqData(QString, QBoolean, int, int, QString, QString)",
                                    sArrCode, bNext, nCodeCount, nTypeFlag, sRQName, sScreenNo)

    def get_api_module_path(self):
        pass

    def get_code_list_by_market(self, sMarket):
        """
        시장구분에 따른 종목코드를 반환한다.

        :param sMarket: 시장구분
            0:장내, 3:ELW, 4:뮤추얼펀드, 5:신주인수권, 6:리츠, 8:ETF, 9:하이일드펀드, 10:코스닥, 30:제3시장
        :return: 종목코드 리스트, 종목간 구분은 ’;’이다.
        """
        return self.ocx.dynamicCall("GetCodeListByMarket(QString)", [sMarket])

    def get_connect_state(self):
        """
        현재접속상태를 반환한다.

        :return: 접속상태 - 0:미연결, 1:연결완료
        """
        return self.ocx.dynamicCall("GetConnectState()")

    def get_master_code_name(self, strCode):
        """
        종목코드의 한글명을 반환한다.
        장내외, 지수선옵, 주식선옵 검색 가능.

        :param strCode: 종목코드
        :return: 종목한글명
        """
        return self.ocx.dynamicCall("GetMasterCodeName(QString)", strCode)

    def get_master_listed_stock_cnt(self):
        pass

    def get_master_construction(self):
        pass

    def get_master_listed_stock_date(self):
        pass

    def get_master_last_price(self):
        pass

    def get_master_stock_state(self):
        pass

    def get_data_count(self):
        pass

    def get_output_value(self):
        pass

    def get_comm_data(self, strTrCode, strRecordName, nIndex, strItemName):
        """
        수신 데이터를 반환한다.

        :param strTrCode: Tran 코드
        :param strRecordName: 레코드명
        :param nIndex: 복수데이터 인덱스
        :param strItemName: 아이템명
        Ex)현재가출력 - openApi.GetCommData(“OPT00001”, “주식기본정보”, 0, “현재가”);

        :return: 수신 데이터
        """
        return self.ocx.dynamicCall("GetCommData(QString, QString, int, QString)",
                                    strTrCode, strRecordName, nIndex, strItemName)

    def get_comm_real_data(self, strRealType, nFid):
        """
        실시간데이터를 반환한다.
        참고)실시간 현재가는 주식시세, 주식체결 등 다른 실시간타입(RealType)으로도 수신가능

        :param strRealType: 실시간 구분
        :param nFid: 실시간 아이템
        Ex) 현재가출력 - openApi.GetCommRealData(“주식시세”, 10);

        :return: 수신 데이터
        """
        return self.ocx.dynamicCall("GetCommRealData(QString, int)", strRealType, nFid)

    def get_chejan_data(self, nFid):
        """
        체결잔고 데이터를 반환한다.

        :param nFid: 체결잔고 아이템
        Ex) 현재가출력 – openApi.GetChejanData(10);
        :return: 수신 데이터
        """
        return self.ocx.dynamicCall("GetChejanData(int)", nFid)

    def set_real_reg(self, strScreenNo, strCodeList, strFidList, strRealType):
        """
        실시간 등록을 한다.
        ※ 종목, FID는 각각 한번에 실시간 등록 할 수 있는 개수는 100개 입니다.

        :param strScreenNo: 실시간 등록할 화면 번호
        :param strCodeList: 실시간 등록할 종목코드(복수종목가능 – “종목1;종목2;종목3;....”)
        :param strFidList: 실시간 등록할 FID(“FID1;FID2;FID3;.....”)
            ex)9001;10;13;…
            9001 – 종목코드
            10 - 현재가
            13 - 누적거래량
        :param strRealType: "0", "1" 타입
            strRealType이 “0” 으로 하면 같은화면에서 다른종목 코드로 실시간 등록을 하게 되면
            마지막에 사용한 종목코드만 실시간 등록이 되고 기존에 있던 종목은 실시간이 자동 해지됨.
            “1”로 하면 같은화면에서 다른 종목들을 추가하게 되면 기존에 등록한 종목도 함께 실 시간 시세를 받을 수 있음.
            꼭 같은 화면이여야 하고 최초 실시간 등록은 “0”으로 하고 이후부터 “1”로 등록해야 함.
        :return: 통신결과
        """
        return self.ocx.dynamicCall("SetRealReg(QString, QString, QString, QString)", strScreenNo, strCodeList, strFidList,
                                    strRealType)

    def set_real_remove(self, strScrNo, strDelCode):
        """
        종목별 실시간 해제.
        SetRealReg() 함수로 실시간 등록한 종목만 실시간 해제 할 수 있다.

        -화면별 실시간해제
            여러 화면번호로 걸린 실시간을 해제하려면 파라메터의 화면번호와 종목코드에 “ALL”로 입력하여 호출하시면 됩니다.
            SetRealRemove(“ALL”, “ALL”);
            개별화면별로 실시간 해제 하시려면 파라메터에서 화면번호는 실시간해제할
            화면번호와 종목코드에는 “ALL”로 해주시면 됩니다.
            SetRealRemove(“0001”, “ALL”);
            -화면의 종목별 실시간해제
            화면의 종목별로 실시간 해제하려면 파라메터에 해당화면번호와 해제할
            종목코드를 입력하시면 됩니다.
            SetRealRemove(“0001”, “039490”);

        :param strScrNo: 실시간 해제할 화면 번호
        :param strDelCode: 실시간 해제할 종목.
        :return: 통신결과
        """
        return self.ocx.dynamicCall("SetRealRemove(QString, QString)", strScrNo, strDelCode)

    def get_condition_load(self):
        """
        서버에 저장된 사용자 조건식을 조회해서 임시로 파일에 저장.

        System 폴더에 아이디_NewSaveIndex.dat파일로 저장된다. Ocx가 종료되면 삭제시킨다.
        조건검색 사용시 이 함수를 최소 한번은 호출해야 조건검색을 할 수 있다.
        영웅문에서 사용자 조건을 수정 및 추가하였을 경우에도 최신의 사용자 조건을 받고 싶으면 다시 조회해야한다.

        :return: 사용자 조건식을 파일로 임시 저장.
        """
        return self.ocx.dynamicCall("GetConditionLoad()")

    def get_condition_name_list(self):
        """
        조건검색 조건명 리스트를 받아온다.
        조건명 리스트를 구분(“;”)하여 받아온다. Ex) 인덱스1^조건명1;인덱스2^조건명2;인덱스3^조건명3;...

        :return: 조건명 리스트(인덱스^조건명)
        """
        return self.ocx.dynamicCall("GetConditionNameList()")

    def send_condition(self, strScrNo, strConditionName, nIndex, nSearch):
        """
        조건검색 종목조회 TR송신한다.

        :param strScrNo: 화면번호
        :param strConditionName: 조건명
        :param nIndex: 조건명인덱스
        :param nSearch: 조회구분(0:일반조회, 1:실시간조회, 2:연속조회) - 1:실시간조회의 화면 개수의 최대는 10개
            단순 조건식에 맞는 종목을 조회하기 위해서는 조회구분을 0으로 하고,
            실시간 조건검색을 하기 위해서는 조회구분을 1로 한다.
            OnReceiveTrCondition으로 결과값이 온다.
            연속조회가 필요한 경우에는 응답받는 곳에서 연속조회 여부에 따라 연속조회를 송신하면 된다.
        """
        self.ocx.dynamicCall("SendCondition(QString,QString, int, int)", strScrNo, strConditionName, nIndex, nSearch)

    def send_condition_stop(self, strScrNo, strConditionName, nIndex):
        """
        조건검색 실시간 중지TR을 송신한다.
        해당 조건명의 실시간 조건검색을 중지하거나, 다른 조건명으로 바꿀 때 이전 조건명으로 실시간 조건검색을 반드시 중지해야한다.
        화면 종료시에도 실시간 조건검색을 한 조건명으로 전부 중지해줘야 한다.
        ※ 화면당 실시간 조건검색은 최대 10개로 제한되어 있어서 더 이상 실시간 조건검색을 원하지 않는 조건은 중지해야만 카운트 되지 않습니다.

        :param strScrNo: 화면번호
        :param strConditionName: 조건명
        :param nIndex: 조건명인덱스
        """
        self.ocx.dynamicCall("SendConditionStop(QString, QString, int)", strScrNo, strConditionName, nIndex)

    def get_comm_data_ex(self, strTrCode, strRecordName):
        """
        차트 조회 데이터를 배열로 받아온다.

        ※ 항목의 위치는 KOA Studio의 TR목록 순서로 데이터를 가져옵니다.
        예로 OPT10080을 살펴보면 OUTPUT의 멀티데이터의 항목처럼 현재가, 거래량, 체결시간등 순으로 항목의 위치가 0부터 1씩 증가합니다.

        :param strTrCode: 조회한 TR코드
        :param strRecordName: 조회한 TR명
        :return:
            조회 데이터가 많은 차트 경우 GetCommData()로 항목당 하나씩 받아오는 것 보다
            한번에 데이터 전부를 받아서 사용자가 처리할 수 있도록 배열로 받는다.
        """
        return json.dumps(self.ocx.dynamicCall("GetCommDataEx(QString, QString)", strTrCode, strRecordName))

    ####################################################
    # Control Event Handlers
    ####################################################
    def OnReceiveTrData(self, sScrNo, sRQName, sTrCode, sRecordName, sPreNext, nDataLength, sErrorCode, sMessage, sSplmMsg):
        """
        Tran 수신시 이벤트
        서버통신 후 데이터를 받은 시점을 알려준다.

        :param sScrNo: 화면번호
        :param sRQName: 사용자구분 명
        :param sTrCode: Tran 명
        :param sRecordName: Record 명
        :param sPreNext: 연속조회 유무
        :param nDataLength: 1.0.0.1 버전 이후 사용하지 않음.
        :param sErrorCode: 1.0.0.1 버전 이후 사용하지 않음.
        :param sMessage: 1.0.0.1 버전 이후 사용하지 않음.
        :param sSplmMsg: 1.0.0.1 버전 이후 사용하지 않음.
        """
        self.qs['OnReceiveTrData'].put({
            "sScrNo": sScrNo,
            "sRQName": sRQName,
            "sTrCode": sTrCode,
            "sRecordName": sRecordName,
            "sPreNext": sPreNext
        })
        print("OnReceiveTrData received")

    def OnReceiveRealData(self, sJongmokCode, sRealType, sRealData):
        """
        실시간 시세 이벤트
        실시간데이터를 받은 시점을 알려준다.

        :param sJongmokCode: 종목코드
        :param sRealType: 리얼타입
        :param sRealData: 실시간 데이터전문
        """
        # self.qs['OnReceiveRealData'].put({
        #     "sJongmokCode": sJongmokCode,
        #     "sRealType": sRealType,
        #     "sRealData": sRealData
        # })
        print("OnReceiveRealData received: ")
        print({
            "sJongmokCode": sJongmokCode,
            "sRealType": sRealType,
            "sRealData": sRealData
        })

    def OnReceiveMsg(self, sScrNo, sRQName, sTrCode, sMsg):
        """
        수신 메시지 이벤트
        서버통신 후 메시지를 받은 시점을 알려준다.

        :param sScrNo: 화면번호
        :param sRQName: 사용자구분 명
        :param sTrCode: Tran 명
        :param sMsg: 서버메시지
        """
        self.qs['OnReceiveMsg'].put("receiveMsg.kiwoom", {
            "sScrNo": sScrNo,
            "sRQName": sRQName,
            "sTrCode": sTrCode,
            "sMsg": sMsg
        })
        print("OnReceiveMsg received")

    def OnReceiveChejanData(self, sGubun, nItemCnt, sFidList):
        """
        체결데이터를 받은 시점을 알려준다.

        :param sGubun: 체결구분 - 0:주문체결통보, 1:잔고통보, 3:특이신호
        :param nItemCnt: 아이템갯수
        :param sFidList: 데이터리스트 - 데이터 구분은 ‘;’ 이다.
        """
        self.qs['OnReceiveChejanData'].put({
            "sGubun": sGubun,
            "nItemCnt": nItemCnt,
            "sFidList": sFidList
        })
        print("OnReceiveChejanData received")

        # Todo: API request implementation
        print("sGubun: ", sGubun)
        print(self.get_chejan_data(9203))   # 주문번호
        print(self.get_chejan_data(302))    # 종목명
        print(self.get_chejan_data(900))    # 주문수량
        print(self.get_chejan_data(901))    # 주문가격

    def OnEventConnect(self, nErrCode):
        """
        통신 연결 상태 변경시 이벤트

        :param nErrCode: 에러 코드 - 0이면 로그인 성공, 음수면 실패, 에러코드 참조
        """
        self.qs['OnEventConnect'].put(nErrCode)
        print("OnEventConnect received")

    def OnReceiveRealCondition(self, strCode, strType, strConditionName, strConditionIndex):
        """
        조건검색 실시간 편입,이탈 종목을 받을 시점을 알려준다.
        편입, 이탈 종목이 실시간으로 들어옵니다.
        strConditionName에 해당하는 종목이 실시간으로 들어옴. strType으로 편입된 종목인지 이탈된 종목인지 구분한다.

        :param strCode: 종목코드
        :param strType: 편입(“I”), 이탈(“D”)
        :param strConditionName: 조건명
        :param strConditionIndex: 조건명 인덱스
        """
        self.qs['OnReceiveRealCondition'].put({
            "strCode": strCode,
            "strType": strType,
            "strConditionName": strConditionName,
            "strConditionIndex": strConditionIndex
        })
        print("OnReceiveRealCondition received")

    def OnReceiveTrCondition(self, sScrNo, strCodeList, strConditionName, nIndex, nNext):
        """
        조건검색 조회응답 이벤트
        조건검색 조회응답으로 종목리스트를 구분자(“;”)로 붙어서 받는 시점.

        :param sScrNo: 종목코드
        :param strCodeList: 종목리스트(“;”로 구분)
        :param strConditionName: 조건명
        :param nIndex: 조건명 인덱스
        :param nNext: 연속조회(2:연속조회, 0:연속조회없음)
        :return:
        """
        self.qs['OnReceiveTrCondition'].put({
            "sScrNo": sScrNo,
            "strCodeList": strCodeList,
            "strConditionName": strConditionName,
            "nIndex": nIndex,
            "nNext": nNext,
        })
        print("OnReceiveTrCondition received")

    def OnReceiveConditionVer(self, lRet, sMsg):
        """
        로컬에 사용자조건식 저장 성공여부 응답 이벤트
        로컬에 사용자 조건식 저장 성공 여부를 확인하는 시점

        :param lRet: 사용자 조건식 저장 성공여부 (1: 성공, 나머지 실패)
        :param sMsg:
        """
        self.qs['OnReceiveConditionVer'].put({
            "lRet": lRet,
            "sMsg": sMsg
        })
        print("OnReceiveConditionVer received")

    ####################################################
    # Custom Methods
    ####################################################
    def quit(self):
        """ Quit the server """

        self.disconnect_real_data(self.S_SCREEN_NO)
        QApplication.quit()

    @staticmethod
    def parse_error_code(err_code):
        """
        Return the message of error codes

        :param err_code: Error Code
        :type err_code: str
        :return: Error Message
        """
        err_code = str(err_code)
        ht = {
            "0": "정상처리",
            "-100": "사용자정보교환에 실패하였습니다. 잠시후 다시 시작하여 주십시오.",
            "-101": "서버 접속 실패",
            "-102": "버전처리가 실패하였습니다.",
            "-200": "시세조회 과부하",
            "-201": "REQUEST_INPUT_st Failed",
            "-202": "요청 전문 작성 실패",
            "-300": "주문 입력값 오류",
            "-301": "계좌비밀번호를 입력하십시오.",
            "-302": "타인계좌는 사용할 수 없습니다.",
            "-303": "주문가격이 20억원을 초과합니다.",
            "-304": "주문가격은 50억원을 초과할 수 없습니다.",
            "-305": "주문수량이 총발행주수의 1%를 초과합니다.",
            "-306": "주문수량은 총발행주수의 3%를 초과할 수 없습니다."
        }
        return ht[err_code] + " (%s)" % err_code if err_code in ht else err_code