Example #1
0
def open_login_window(exit_on_login=True):
    app = QApplication(sys.argv)
    control = KiwoomOpenApiQAxWidget()
    if control.GetConnectState() == 0:
        def OnEventConnect(errcode):
            control.OnEventConnect.disconnect(OnEventConnect)
            if exit_on_login:
                app.exit(errcode)
        control.OnEventConnect.connect(OnEventConnect)
        KiwoomOpenApiError.try_or_raise(control.CommConnect())
    return app.exec_()
    def _EnsureConnectedUsingSignalConnector(self):
        errcode = 0
        if self.GetConnectState() == 0:
            q = queue.Queue()

            def OnEventConnect(errcode):
                q.put(errcode)
                self.OnEventConnect.disconnect(OnEventConnect)

            self.OnEventConnect.connect(OnEventConnect)
            errcode = KiwoomOpenApiError.try_or_raise(self.CommConnect())
            errcode = KiwoomOpenApiError.try_or_raise(q.get())
        return errcode
    def Connect(self):
        q = queue.Queue()

        def OnEventConnect(errcode):
            q.put(errcode)

        self.OnEventConnect.connect(OnEventConnect)
        try:
            errcode = KiwoomOpenApiError.try_or_raise(self.CommConnect())
            errcode = KiwoomOpenApiError.try_or_raise(q.get())
        finally:
            self.OnEventConnect.disconnect(OnEventConnect)
        return errcode
def enable_autologin_after_version_update():
    logging.info('trying to enable autologin after version update')
    app = QApplication(sys.argv)
    control = KiwoomOpenApiQAxWidget()
    if control.GetConnectState() == 0:
        def OnEventConnect(errcode):
            logging.info('logged in')
            KiwoomOpenApiError.try_or_raise(errcode)
            enable_autologin_with_control(control)
            control.OnEventConnect.disconnect(OnEventConnect)
            app.exit(errcode)
        control.OnEventConnect.connect(OnEventConnect)
        KiwoomOpenApiError.try_or_raise(control.CommConnect())
        login_semiauto(wait_closed=False)
    return app.exec_()
    def RateLimitedCommRqData(self,
                              rqname,
                              trcode,
                              prevnext,
                              scrnno,
                              inputs=None):
        """
        [OpenAPI 게시판]
          https://bbn.kiwoom.com/bbn.openAPIQnaBbsList.do

        [조회횟수 제한 관련 가이드]
          - 1초당 5회 조회를 1번 발생시킨 경우 : 17초대기
          - 1초당 5회 조회를 5연속 발생시킨 경우 : 90초대기
          - 1초당 5회 조회를 10연속 발생시킨 경우 : 3분(180초)대기
        """
        prevnext = int(prevnext)  # ensure prevnext is int
        code = self.CommRqData(rqname, trcode, prevnext, scrnno)
        spec = 'CommRqData(%r, %r, %r, %r)' % (rqname, trcode, prevnext,
                                               scrnno)

        if inputs is not None:
            spec += ' with inputs %r' % inputs

        if code == KiwoomOpenApiError.OP_ERR_NONE:
            message = 'CommRqData() was successful; ' + spec
            logging.debug(message)
        elif code == KiwoomOpenApiError.OP_ERR_SISE_OVERFLOW:
            message = 'CommRqData() was rejected due to massive request; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        elif code == KiwoomOpenApiError.OP_ERR_ORD_WRONG_INPUT:
            message = 'CommRqData() failed due to wrong input, check if input was correctly set; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        elif code in (KiwoomOpenApiError.OP_ERR_RQ_STRUCT_FAIL,
                      KiwoomOpenApiError.OP_ERR_RQ_STRING_FAIL):
            message = 'CommRqData() request was invalid; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        else:
            message = 'Unknown error occured during CommRqData() request; ' + spec
            korean_message = KiwoomOpenApiError.get_error_message_by_code(code)
            if korean_message is not None:
                message += '; Korean error message: ' + korean_message
            logging.error(message)
            raise KiwoomOpenApiError(code)

        return code
Example #6
0
    def RateLimitedCommRqDataAndCheck(self,
                                      rqname,
                                      trcode,
                                      prevnext,
                                      scrnno,
                                      inputs=None):
        code = self.RateLimitedCommRqData(rqname, trcode, prevnext, scrnno)

        spec = 'CommRqData(%r, %r, %r, %r)' % (rqname, trcode, prevnext,
                                               scrnno)

        if inputs is not None:
            spec += ' with inputs %r' % inputs

        if code == KiwoomOpenApiError.OP_ERR_NONE:
            message = 'CommRqData() was successful; ' + spec
            logging.debug(message)
        elif code == KiwoomOpenApiError.OP_ERR_SISE_OVERFLOW:
            message = 'CommRqData() was rejected due to massive request; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        elif code == KiwoomOpenApiError.OP_ERR_ORD_WRONG_INPUT:
            message = 'CommRqData() failed due to wrong input, check if input was correctly set; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        elif code in (KiwoomOpenApiError.OP_ERR_RQ_STRUCT_FAIL,
                      KiwoomOpenApiError.OP_ERR_RQ_STRING_FAIL):
            message = 'CommRqData() request was invalid; ' + spec
            logging.error(message)
            raise KiwoomOpenApiError(code)
        else:
            message = 'Unknown error occured during CommRqData() request; ' + spec
            korean_message = KiwoomOpenApiError.get_error_message_by_code(code)
            if korean_message is not None:
                message += '; Korean error message: ' + korean_message
            logging.error(message)
            raise KiwoomOpenApiError(code)

        return code
Example #7
0
 def borrow_screen(self, screen_no=None, reuse=True, pop=True):
     with self._lock:
         if screen_no is None or screen_no == '':
             screen_no = self.get_single_free_screen()
         if not reuse:
             if self.is_inuse(screen_no):
                 raise KiwoomOpenApiError("Borrowing screen %s, but it's already is use." % screen_no)
             if len(self._occupied_screen_nos) == self._maximum_num:
                 logging.warning('Borrowing a screen, but already using maximum number of screens.')
                 if pop:
                     oldest = self._occupied_screen_nos.popleft()
                     del self._borrow_count_by_screen_no[oldest]
                     logging.warning('Oldest screen %s popped.', self._number_to_screen_no(oldest))
                 else:
                     raise KiwoomOpenApiError('Cannot allocate more screen')
         screen_no_int = self._screen_no_to_number(screen_no)
         if not self.is_inuse(screen_no):
             self._occupied_screen_nos.append(screen_no_int)
         self._borrow_count_by_screen_no[screen_no_int] = self._borrow_count_by_screen_no.get(screen_no_int, 0) + 1
         if len(self._occupied_screen_nos) == self._maximum_num:
             logging.warning('Maximum number of screens reached.')
         return screen_no
Example #8
0
 def from_tuple(cls, tup):
     if '일자' in tup._fields:
         dt = datetime.datetime.strptime(tup.일자, '%Y%m%d')
         dt = cls.kst.localize(dt)
         time = dt.timestamp() * (10**6)  # pylint: disable=redefined-outer-name
     elif '체결시간' in tup._fields:
         dt = datetime.datetime.strptime(tup.체결시간, '%Y%m%d%H%M%S')
         dt = cls.kst.localize(dt)
         time = dt.timestamp() * (10**6)
     else:
         raise KiwoomOpenApiError('Cannot specify time')
     open = abs(float(tup.시가))  # pylint: disable=redefined-builtin
     high = abs(float(tup.고가))
     low = abs(float(tup.저가))
     close = abs(float(tup.현재가))
     volume = abs(float(tup.거래량))
     return cls(time, open, high, low, close, volume)
    def LoadCondition(self):
        q = queue.Queue()

        def OnReceiveConditionVer(ret, msg):
            if not ret:
                q.put(KiwoomOpenApiError(msg))
            else:
                q.put((ret, msg))

        self.OnReceiveConditionVer.connect(OnReceiveConditionVer)
        try:
            return_code = KiwoomOpenApiError.try_or_raise_boolean(
                self.GetConditionLoad(), 'Failed to load condition')
            res = q.get()
            if isinstance(res, KiwoomOpenApiError):
                raise res
        finally:
            self.OnReceiveConditionVer.disconnect(OnReceiveConditionVer)
        return return_code
Example #10
0
 def borrow_screen(self, screen_no=None, pop=False):
     with self._lock:
         if len(self._occupied_screen_nos) == self._maximum_num:
             logging.warning(
                 'Borrowing a screen, but already using maximum number of screens.'
             )
             if pop:
                 oldest = self._occupied_screen_nos.popleft()
                 logging.warning('Oldest screen %s popped.',
                                 self._number_to_screen_no(oldest))
             else:
                 raise KiwoomOpenApiError('Cannot allocate more screen')
         if screen_no is None or screen_no == '':
             screen_no = self.get_single_free_screen()
         elif self.is_inuse(screen_no):
             logging.warning(
                 "Borrowing screen %s, but it's already is use.", screen_no)
         self._occupied_screen_nos.append(
             self._screen_no_to_number(screen_no))
         if len(self._occupied_screen_nos) == self._maximum_num:
             logging.warning('Maximum number of screens reached.')
         return screen_no
Example #11
0
    def get_history(self, trcode, inputs, dtbegin=None, dtend=None):
        if trcode == 'opt10079':
            code = inputs['종목코드']
            interval = inputs['틱범위']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetTickStockDataAsDataFrame(
                code, interval, dtend, dtbegin, adjusted_price=adjusted_price)
        elif trcode == 'opt10080':
            code = inputs['종목코드']
            interval = inputs['틱범위']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetMinuteStockDataAsDataFrame(
                code, interval, dtend, dtbegin, adjusted_price=adjusted_price)
        elif trcode == 'opt10081':
            code = inputs['종목코드']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetDailyStockDataAsDataFrame(
                code, dtend, dtbegin, adjusted_price=adjusted_price)
        elif trcode == 'opt10082':
            code = inputs['종목코드']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetWeeklyStockDataAsDataFrame(
                code, dtend, dtbegin, adjusted_price=adjusted_price)
        elif trcode == 'opt10083':
            code = inputs['종목코드']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetMonthlyStockDataAsDataFrame(
                code, dtend, dtbegin, adjusted_price=adjusted_price)
        elif trcode == 'opt10094':
            code = inputs['종목코드']
            adjusted_price = inputs.get('수정주가구분') == '1'
            df = self.GetYearlyStockDataAsDataFrame(
                code, dtend, dtbegin, adjusted_price=adjusted_price)
        else:
            raise KiwoomOpenApiError('Unexpected trcode %s' % trcode)

        candles = HistoricalPriceRecord.dict_records_from_dataframe(df)
        response = {'candles': candles}
        return response
Example #12
0
File: cli.py Project: tpag20/koapy
def errmsg(err_code, verbose):
    set_verbosity(verbose)
    from koapy.openapi.KiwoomOpenApiError import KiwoomOpenApiError
    err_msg = KiwoomOpenApiError.get_error_message_by_code(err_code)
    click.echo('[%d] %s' % (err_code, err_msg))
 def OnEventConnect(errcode):
     logging.info('logged in')
     KiwoomOpenApiError.try_or_raise(errcode)
     enable_autologin_with_control(control)
     control.OnEventConnect.disconnect(OnEventConnect)
     app.exit(errcode)
 def OnReceiveConditionVer(ret, msg):
     if not ret:
         q.put(KiwoomOpenApiError(msg))
     else:
         q.put((ret, msg))