Example #1
0
class KospiTracker(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        # self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        # self.timer = QTimer(self)
        # self.timer.start(1000)
        # self.timer.timeout.connect(self.timeout)

        # accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        # accounts = self.kiwoom.get_login_info("ACCNO")
        #
        # accounts_list = accounts.split(';')[0:accouns_num]
        # self.comboBox.addItems(accounts_list)
        #
        # self.lineEdit.textChanged.connect(self.code_changed)
        # self.pushButton.clicked.connect(self.send_order)

    def load_index(self, market, date):
        self.kiwoom.ohlcv = {'date': [], 'cur_price': [], 'volume': []}
        self.kiwoom.set_input_value("업종코드", market)
        self.kiwoom.set_input_value("기준일자", date)
        self.kiwoom.comm_rq_data("opt20006_req", "opt20006", 0, "0215")

        df = pd.DataFrame(self.kiwoom.ohlcv, columns=['date', 'cur_price', 'volume'])

        print(df)

        return df

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account, order_type_lookup[order_type], code, num, price, hoga_lookup[hoga], "")
Example #2
0
class PyMon:
    def __init__(self):
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

    def run(self):
        # self.run_pbr_per_screener()
        # self.run_condition_data()
        self.get_codition_stock_list()

    def get_codition_stock_list(self):
        self.kiwoom.get_condition_load()
        conditionName = self.kiwoom.get_condition_name_list()
        self.kiwoom.send_condition("0150", SEL_CONDITION_NAME, CONDITION_INDEX,
                                   1)
        # print(self.kiwoom.condition_code_list[:-1])
        code_list = self.kiwoom.condition_code_list[:-1]
        print("조건검색결과 주식 : ", code_list, len(code_list))
        f = open(self.kiwoom.buy_loc, 'wt', encoding='UTF-8')
        dm = ';'
        b_gubun = "매수"
        b_status = "매수전"
        b_price = 0
        b_method = "지정가"
        b_qty = 0
        for code in code_list:
            code_info = self.kiwoom.get_master_code_name(code)
            mste_info = self.kiwoom.get_master_construction(code)
            stock_state = self.kiwoom.get_master_stock_state(code)
            print(code_info, mste_info, stock_state)
            if mste_info == '정상':
                stock_info = b_gubun + dm + code + dm + b_method + dm + str(
                    b_qty) + dm + str(b_price) + dm + b_status
                f.write(stock_info + '\n')
        f.close()
        if len(code_list) == 0:
            print("해당하는 조건검색의 결과 주식이 없습니다.")
            pass
        # 로직구현 필요함.
        # result = []
        # for i, code in enumerate(code_list):
        #     print("%d : %d" % (i, len(code_list)))
        #     if i > 100:
        #         break
        #
        #     (per, pbr) = self.get_per_pbr(code)
        #     if 2.5 <= per <= 10:
        #         result.append((code, per, pbr))
        #
        # data = sorted(result, key=lambda x:x[2])
        # self.dump_data(code_list)
        # TEST
        # code_list = ['066590','006920','005690']
        # self.dump_data_json(code_list)

    def run_condition_data(self):
        self.kiwoom.get_condition_load()
        #self.kiwoom.get_condition_name_list()
        self.kiwoom.send_condition("0150", SEL_CONDITION_NAME, CONDITION_INDEX,
                                   1)
        #print(self.kiwoom.condition_code_list[:-1])
        code_list = self.kiwoom.condition_code_list[:-1]
        # 금일날짜
        today = datetime.today().strftime("%Y%m%d")
        r_price = self.get_condition_param(code_list[1], today)
        print(r_price)
        # 영업일 하루전날짜
        df_hdays = pd.read_excel("stor/data.xls")
        hdays = df_hdays['일자 및 요일'].str.extract('(\d{4}-\d{2}-\d{2})',
                                                expand=False)
        hdays = pd.to_datetime(hdays)
        hdays.name = '날짜'
        mdays = pd.date_range('2019-01-01', '2019-12-31', freq='B')
        #print(mdays)
        mdays = mdays.drop(hdays)
        #f_mdays = mdays.to_frame(index=True)
        #print(f_mdays)
        # 개장일을 index로 갖는 DataFrame
        #data = {'values': range(1, 31)}
        #df_sample = pd.DataFrame(data, index=pd.date_range('2019-01-01', '2019-01-31'))
        df_mdays = pd.DataFrame({'date': mdays})
        df_mdays_list = df_mdays['date'].tolist()
        for i, df_day in enumerate(df_mdays_list):
            if (df_day.__format__('%Y%m%d') == today):
                self.prev_bus_day_1 = df_mdays_list[i -
                                                    1].__format__('%Y-%m-%d')
                self.prev_bus_day_2 = df_mdays_list[i -
                                                    2].__format__('%Y-%m-%d')

        print(self.prev_bus_day_1, self.prev_bus_day_2)
        # 두 DataFrame (df_sample, df_mdays)의 인덱스를 기준으로 합친다(merge)
        #df = pd.merge(df_sample, df_mdays, right_index=True, left_index=True)
        #df.head(10)

    def run_pbr_per_screener(self):
        code_list = self.kiwoom.get_code_list_by_market(
            0) + self.kiwoom.get_code_list_by_market(10)

        # result = []
        # for i, code in enumerate(code_list):
        #     print("%d : %d" % (i, len(code_list)))
        #     if i > 100:
        #         break
        #
        #     (per, pbr) = self.get_per_pbr(code)
        #     if 2.5 <= per <= 10:
        #         result.append((code, per, pbr))
        #
        # data = sorted(result, key=lambda x:x[2])
        # self.dump_data(data[:30])
    def get_condition_param(self, code, s_date):
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.set_input_value("시작일자", s_date)
        self.kiwoom.comm_rq_data("opt10086_req", "opt10086", 0, "0101")
        return (self.kiwoom.s_price, self.kiwoom.e_price)

    def get_per_pbr(self, code):
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "0101")
        time.sleep(0.2)
        if (self.kiwoom.per == ''):
            self.kiwoom.per = 0
        if (self.kiwoom.pbr == ''):
            self.kiwoom.pbr = 0
        print(self.kiwoom.per, self.kiwoom.pbr)
        return (float(self.kiwoom.per), float(self.kiwoom.pbr))

    def dump_data(self, data):
        f = open("./database.db", "wb")
        pickle.dump(data, f)
        f.close()

    def dump_data_json(self, data):
        with open('buy_stock.json', 'w', encoding='utf-8') as stock_file:
            json.dump(data, stock_file, ensure_ascii=False, indent="\t")
Example #3
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
Example #4
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.tr = 0  #총TR요청횟수

        #텔레그램봇
        my_token = '692301814:AAEfmddhyZPcO0Uzh8r5ZehfooTPOvKOOqc'
        self.mybot = telegram.Bot(token=my_token)
        self.chat_id = 544924927

        self.kiwoom = Kiwoom()  #키움인스턴스 생성
        self.kiwoom.comm_connect()  #API로그인

        self.ts_1_p = 'False'  #거래전략1 초기값
        self.market_start = 'false'  #마켓 초기값
        self.market_close = 'false'
        self.shutdown_0900 = 'false'
        self.shutdown_1530 = 'false'

        # Timer1
        self.timer = QTimer(self)
        self.timer.start(1000)  #1초 상태바
        self.timer.timeout.connect(self.timeout)

        # Timer2
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 25)  #25초 잔고조회
        self.timer2.timeout.connect(self.timeout2)

        # Timer3
        self.timer3 = QTimer(self)
        self.timer3.start(1000 * 30)  #30초 매수전략1
        self.timer3.timeout.connect(self.timeout3)

        # Timer4
        self.timer4 = QTimer(self)
        self.timer4.start(1000 * 33)  # 33초 매도전략
        self.timer4.timeout.connect(self.timeout4)

        # Timer5
        self.timer5 = QTimer(self)
        self.timer5.start(1000 * 15)  # 60초 09:00~15:30 장중모드
        self.timer5.timeout.connect(self.timeout5)

        # Timer7
        self.timer7 = QTimer(self)
        self.timer7.start(1000 * 1800)  # 30분 중간보고, 장마감후 어플 및 컴퓨터 종료
        self.timer7.timeout.connect(self.timeout7)

        self.list700 = []
        self.list600 = []
        self.buy_list = []

        #버튼, 이벤트발생
        self.lineEdit.textChanged.connect(self.code_changed)  #종목코드 입력시
        self.pushButton.clicked.connect(self.send_order)  #현금주문 버튼 클릭시
        self.pushButton_2.clicked.connect(self.check_balance)  #계좌정보 조회
        self.pushButton_3.clicked.connect(self.trading_strategy_1)  #거래전략1호
        self.pushButton_4.clicked.connect(self.quit_app)  #앱종료
        self.pushButton_4.clicked.connect(
            QCoreApplication.instance().quit)  # 앱종료
        self.pushButton_5.clicked.connect(self.timeout7)  # 테스트버튼

        #계좌정보
        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        #프로그램시작알림
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 시작되었습니다.")
        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               "\n프로그램이 시작되었습니다.")
        self.get_etf_etn_list()  # ETN, ETF 종목 리스트 저장

    #종료
    def quit_app(self):
        if self.ts_1_p == 'True':
            self.trading_strategy_1()
        self.timer.stop()
        self.timer2.stop()
        self.timer3.stop()
        self.timer4.stop()
        self.timer5.stop()
        self.timer7.stop()
        time.sleep(1)

        #계좌정보요청
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        mystocks = ''

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1
        bb = self.kiwoom.opw00018_output['single']
        myaccount = '총매입금액: %s원\n총평가금액: %s원\n총평가손익금액: %s원\n총수익률(%%): %s\n추정예탁자산: %s원' % (
            bb[0], bb[1], bb[2], bb[3], bb[4])

        a = len(self.kiwoom.opw00018_output['multi'])
        if a != 0:
            name = []
            num = []
            buy = []
            price = []
            earn = []
            ret = []
            for i in range(a):
                name.append(self.kiwoom.opw00018_output['multi'][i][0])
                num.append(self.kiwoom.opw00018_output['multi'][i][1])
                buy.append(self.kiwoom.opw00018_output['multi'][i][2])
                price.append(self.kiwoom.opw00018_output['multi'][i][3])
                earn.append(self.kiwoom.opw00018_output['multi'][i][4])
                ret.append(self.kiwoom.opw00018_output['multi'][i][5])
            mystocks = {
                '종목': name,
                '수량': num,
                '매입가': buy,
                '현재가': price,
                '평가손익': earn,
                '수익률(%)': ret
            }
            mystocks = DataFrame(mystocks)
            mystocks = mystocks.set_index(['종목'])

        #last 보고
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 종료되었습니다.")
        self.mybot.sendMessage(
            self.chat_id,
            text=QTime.currentTime().toString("hh:mm:ss") +
            "\n프로그램이 종료되었습니다.\n총 TR 요청 횟수 : %d회\n -----계좌현황-----\n계좌번호: %s\n%s\n -----보유종목-----\n%s"
            % (self.tr, account_number, myaccount, mystocks))
        with open('log.txt', 'a') as f:
            f.writelines(self.textEdit.toPlainText())
        time.sleep(3)

    #상태표시줄(현재시간, 서버연결상태)
    def timeout(self):
        market_start_time = QTime(9, 00, 00)
        market_close_time = QTime(15, 30, 00)
        market_start_time2 = QTime(9, 00, 2)
        market_close_time2 = QTime(15, 30, 2)
        current_time = QTime.currentTime()

        # 9시 이후에 급등주알고리즘 시작
        if current_time > market_start_time and current_time < market_start_time2 and self.market_start == 'false':
            self.market_start = 'true'
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 장이 시장되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 장이 시작되었습니다.")
        elif current_time > market_close_time and current_time < market_close_time2 and self.market_close == 'false':
            self.market_close = 'true'
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 장이 종료되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 장이 종료되었습니다.")

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()
        if state == 1:
            state_msg = "서버가 연결되었습니다."
        else:
            state_msg = "서버가 연결되지 않았습니다."
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ서버가 연결되지 않았습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 서버가 연결되지 않았습니다.")

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()  #계좌정보 실시간 조회

    def timeout3(self):
        if self.ts_1_p == 'True':  #매수전략1 진행시 30초마다 조회
            self.volume_check()

    def timeout4(self):
        self.sell_stocks()  #매도전략

    def timeout5(self):

        if self.checkBox_2.isChecked():

            market_start_time = QTime(9, 3, 00)
            market_close_time = QTime(15, 40, 00)
            current_time = QTime.currentTime()

            # 9시 이후에 급등주알고리즘 시작
            if current_time > market_start_time and self.shutdown_0900 == 'false' and self.ts_1_p == 'False':
                self.shutdown_0900 = 'true'
                self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                     "ㅣ 장 시작, 매수전략1 시작하겠습니다.")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") +
                    "ㅣ 장 시작, 매수전략1 시작하겠습니다.")
                self.trading_strategy_1()

            #15시 40 분 이후 알고리즘 중지 및 10분 뒤 컴퓨터 종료
            elif current_time > market_close_time and self.shutdown_1530 == 'false':
                self.shutdown_1530 = 'true'
                self.trading_strategy_1()
                time.sleep(1)
                self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                     "ㅣ 10분 후 컴퓨터를 종료합니다.")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") +
                    "ㅣ 10분 후 컴퓨터를 종료합니다.")

                self.quit_app()
                time.sleep(10)
                os.system("shutdown -s -t 600")
                print('10분 후 컴퓨터를 종료합니다...')

    def timeout7(self):  #중간보고
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1
        mystocks = ''
        bb = self.kiwoom.opw00018_output['single']
        myaccount = '총매입금액: %s원\n총평가금액: %s원\n총평가손익금액: %s원\n총수익률(%%): %s\n추정예탁자산: %s원' % (
            bb[0], bb[1], bb[2], bb[3], bb[4])
        print(myaccount)
        a = len(self.kiwoom.opw00018_output['multi'])
        if a != 0:
            name = []
            num = []
            buy = []
            price = []
            earn = []
            ret = []
            for i in range(a):
                name.append(self.kiwoom.opw00018_output['multi'][i][0])
                num.append(self.kiwoom.opw00018_output['multi'][i][1])
                buy.append(self.kiwoom.opw00018_output['multi'][i][2])
                price.append(self.kiwoom.opw00018_output['multi'][i][3])
                earn.append(self.kiwoom.opw00018_output['multi'][i][4])
                ret.append(self.kiwoom.opw00018_output['multi'][i][5])
            mystocks = {
                '종목': name,
                '수량': num,
                '매입가': buy,
                '현재가': price,
                '평가손익': earn,
                '수익률(%)': ret
            }
            mystocks = DataFrame(mystocks)
            mystocks = mystocks.set_index(['종목'])
        print(mystocks)
        time.sleep(1)
        # 중간보고
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 중간보고 완료.")
        self.mybot.sendMessage(
            self.chat_id,
            text=QTime.currentTime().toString("hh:mm:ss") +
            "\n--------중간보고--------\n총 TR 요청 횟수 : %d회\n --------계좌현황--------\n계좌번호: %s\n%s\n --------보유종목--------\n%s"
            % (self.tr, account_number, myaccount, mystocks))

    #종목명 나타내기
    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    #현금주문(수동주문)
    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")
        self.tr += 1

    #계좌정보
    def check_balance(self):

        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        self.tr += 1
        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
        self.tr += 1

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
        print('잔고조회완료')

    #거래량급증 거래전략1
    def trading_strategy_1(self):

        if self.ts_1_p == 'False':
            print('ts_1_p = true, 매수전략1 실행중입니다.')
            self.ts_1_p = 'True'
            self.label_7.setText("진행중...")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 매수전략1 시작되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 매수전략1 시작되었습니다.")
            self.volume_check()

        elif self.ts_1_p == 'True':
            print('ts_1_p = False, 매수전략1 중지되었습니다.')
            self.label_7.setText("")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 매수전략1 중지되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 매수전략1 중지되었습니다.")
            self.ts_1_p = 'False'

    #매수,매도주문
    def order_stocks(self, bs, code, num, price, set_price):
        '''
        :param bs: 매수=1 매도=2
        :param code: 종목코드
        :param num: 수량
        :param price: 가격 (시장가이면 0)
        :param set_price: 지정가=00 시장가=03
        :return:
        '''
        account = self.comboBox.currentText()

        # order
        self.kiwoom.send_order("send_order_req", "0101", account, bs, code,
                               num, price, set_price, "")
        self.tr += 1

    #거래량급증 조회
    def volume_check(self):

        print('조회수급등조회시작')
        kospi_url = 'https://finance.naver.com/sise/sise_quant_high.nhn'
        kosdaq_url = 'https://finance.naver.com/sise/sise_quant_high.nhn?sosok=1'

        df = pd.DataFrame()

        html_1 = requests.get(kospi_url).text
        df = df.append(pd.read_html(html_1, header=0)[1])
        html_2 = requests.get(kosdaq_url).text
        df = df.append(pd.read_html(html_2, header=0)[1])
        df = df.dropna()
        df = df.rename(
            columns={
                'N': 'num',
                '증가율': 'rate',
                '종목명': 'name',
                '현재가': 'price',
                '전일비': 'diff',
                '등락률': 'updown',
                '매수호가': 'buy_hoga',
                '매도호가': 'sell_hoga',
                '거래량': 'volume',
                '전일거래량': 'yes_volume',
                'PER': 'PER'
            })
        df = df.set_index(['num'])  #크롤링완료
        html = html_1 + html_2
        if df.empty is True:
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 'ㅣ 네이버금융 데이터가 없습니다.')
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString('hh:mm:ss') +
                'ㅣ 네이버금융 데이터가 없습니다.')
            print('네이버금융 데이터가 없습니다.')
        else:

            # 0.4.1 수정
            #700이상
            df700 = df[[a > 700 for a in df.rate]]
            a700 = list(df700['name'])
            if len(df700) != 0:
                for i in range(len(df700)):
                    a = html.find(a700[i])
                    code = html[a - 22:a - 16]
                    self.list700.append(code)
            print(self.list700)
            print(self.list600)

            #교집합 구하기
            aa = set(self.list700)
            bb = set(self.list600)
            buy_set = aa & bb
            buy_set = list(buy_set)
            if len(buy_set) != 0:
                for code in buy_set:
                    if code in self.etn_etf_list:
                        pass
                    else:
                        for i in range(len(buy_set)):
                            self.buy_list.append(buy_set[i])

            #600~700
            self.list600 = []
            df600 = df[[a > 400 and a < 700 for a in df.rate]]
            a600 = list(df600['name'])
            if len(df600) != 0:
                for i in range(len(df600)):
                    a = html.find(a600[i])
                    code = html[a - 22:a - 16]
                    self.list600.append(code)

            print('매수리스트: %s' % self.buy_list)

        #order
        if len(self.buy_list) == 0:
            pass
        else:
            account_number = self.comboBox.currentText()
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
            buy_q = int(self.kiwoom.d2_deposit.replace(',', ''))
            buy_q = (buy_q //
                     len(self.buy_list)) // 5  #예수금/선정종목갯수/5 : 종목당 매수금액
            self.tr += 1

            for code in self.buy_list:
                time.sleep(0.5)
                self.kiwoom.set_input_value("종목코드", code)
                self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "0101")
                buy_q = buy_q // self.kiwoom.stock_pv  #매수금액/현재가 : 수량
                self.tr += 1
                time.sleep(1)
                if buy_q < 1:
                    self.textEdit.append(
                        QTime.currentTime().toString("hh:mm:ss") +
                        "ㅣ 예수금이 부족합니다.")
                    self.mybot.sendMessage(
                        self.chat_id,
                        text=QTime.currentTime().toString("hh:mm:ss") +
                        "ㅣ 예수금이 부족합니다.")
                    print('예수금이 부족합니다.')
                else:
                    self.order_stocks(1, code, buy_q, 0, '03')
                    self.textEdit.append(
                        QTime.currentTime().toString("hh:mm:ss") +
                        'ㅣ 매수주문\n종목: %s\n수량: %d\n가격: 시장가\n현재가:%s' %
                        (self.kiwoom.stock_name, buy_q, self.kiwoom.stock_pv))
                    self.mybot.sendMessage(
                        self.chat_id,
                        text=QTime.currentTime().toString('hh:mm:ss') +
                        'ㅣ매수주문\n 종목: %s\n수량: %d\n가격: 시장가\n현재가:%s' %
                        (self.kiwoom.stock_name, buy_q, self.kiwoom.stock_pv))
        self.buy_list = []
        self.list700 = []
        print("거래량급증조회완료")

    #목표수익률 도달시 팔기
    def sell_stocks(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1

        list_1 = list(self.kiwoom.opw00018_output['multi'])
        a = len(list_1)
        if a != 0:
            print('보유종목현황: %s' % list_1)
            for i in range(a):
                if float(list_1[i][5]) > 5:
                    code = list_1[i][6]
                    num = int(list_1[i][1].replace('.00', '').replace(',', ''))
                    self.kiwoom.set_input_value("종목코드", code)
                    self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0,
                                             "0101")
                    self.tr += 1
                    time.sleep(1)
                    self.order_stocks(2, code, num, 0, '03')
                    print('매도종목: %s' % code)
                    self.mybot.sendMessage(
                        self.chat_id,
                        text=QTime.currentTime().toString("hh:mm:ss") +
                        'ㅣ 이익실현\n매도주문\n 종목: %s\n수량: %d\n가격: 시장가' %
                        (self.kiwoom.stock_name, num))
                    self.textEdit.append(
                        QTime.currentTime().toString("hh:mm:ss") +
                        'ㅣ 매도주문\n 종목: %s\n수량: %d\n가격: 시장가' %
                        (self.kiwoom.stock_name, num))
                elif float(list_1[i][5]) < -3:
                    code = list_1[i][6]
                    num = int(list_1[i][1].replace('.00', '').replace(',', ''))
                    self.kiwoom.set_input_value("종목코드", code)
                    self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0,
                                             "0101")
                    self.tr += 1
                    time.sleep(1)
                    self.order_stocks(2, code, num, 0, '03')
                    print('매도종목: %s' % code)
                    self.mybot.sendMessage(
                        self.chat_id,
                        text=QTime.currentTime().toString("hh:mm:ss") +
                        'ㅣ 손절\n매도주문\n 종목: %s\n수량: %d\n가격: 시장가' %
                        (self.kiwoom.stock_name, num))
                    self.textEdit.append(
                        QTime.currentTime().toString("hh:mm:ss") +
                        'ㅣ 매도주문\n 종목: %s\n수량: %d\n가격: 시장가' %
                        (self.kiwoom.stock_name, num))

    #ETF, ETN 종목 리스트 저장
    def get_etf_etn_list(self):
        time.sleep(2)
        market_list = ['etn', 'etf']
        self.etn_etf_list = []

        for market in market_list:

            if market == 'etn':
                url = 'https://finance.naver.com/api/sise/etnItemList.nhn?'
            elif market == 'etf':
                url = 'https://finance.naver.com/api/sise/etfItemList.nhn?'
            html = requests.get(url).text
            aa = html.split('},')
            for stock in aa:
                code_start = stock.find('itemcode')
                code = stock[code_start + 11:code_start + 17]
                self.etn_etf_list.append(code)
        print('ETN, ETF 종모리스트 저장 완료')
        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               'ㅣ ETF, ETN 종목리스트 저장 완료')
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             'ㅣ ETF, ETN 종목리스트 저장 완료')
Example #5
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.run()
        self.currentTime = datetime.datetime.now()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        # Timer2 실시간 조회 체크박스 체크하면 10초에 한 번씩 데이터 자동 갱신
        self.timer2 = QTimer(self)
        self.timer2.start(1000*10)
        self.timer2.timeout.connect(self.timeout2)

        # 선정 종목 리스트
        self.load_buy_sell_list()

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")


        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        #self.pushButton_2.clicked.connect(self.check_balance)
        self.check_balance()
        self.kiwoom.OnReceiveRealData.connect(self.kiwoom._receive_real_data)
        self.check_chejan_balance()
        self.save_final_stock()


    def is_trading_time(self):
        vals = []
        current_time = self.currentTime.time()
        for start, end in TRADING_TIME:
            start_time = datetime.time(hour=start[0], minute=start[1])
            end_time = datetime.time(hour=end[0], minute=end[1])
            if(current_time >= start_time and current_time <= end_time):
                vals.append(True)
            else:
                vals.append(False)
                pass
        if vals.count(True):
            return True
        else:
            return False

    """def stock_name(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()
        account = self.comboBox.currentText()

        for row_data in buy_list:
            split_row_data = row_data.split(';')
            code = split_row_data[1]
"""



#주문을 들어가기 전에 파일에서 불러와서 종목을 확인, 종목의 전일 종가 확인 - 첫 번째 주문 시
#두 번째 주문부터는 이미 주문 들어간 파일에서 확인
    # 자동 주문
    def trade_stocks(self):
        #self.check_balance()
        auto_buy = []
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        auto_buy += buy_list
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        account = self.comboBox.currentText()
        close_rate, current_rate = self.run()
        #print("rate: ", rate[2][0])
        print(current_rate)
        # buy list
        for i in range(len(auto_buy)):
            split_row_data = auto_buy[i].split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]
            bdr = split_row_data[5]
            pr = split_row_data[6]
            lr = split_row_data[7]


            #temp = self.kiwoom.opw00018_output['multi'][0][3]
            """for i in range(len(new)):
                price = bdr * new[i]
                price = int(price)
                temp = price % 10
                new_price = price - temp"""
            #print(self.final_stock[0])
            #price = bdr * self.final_stock[cnt]
            """price = int(price)
            temp = price % 10
            new_price = price - """
            print("bdr:", float(bdr))
            # 전날 종가
            new_price = close_rate[i][0] * float(bdr)
            print("cnt:", i)
            print("rate[cnt]", close_rate[i][0])
            print("new_price:", new_price)
            #temp = new_price % 10
            #new_price = new_price - temp
            hoga = "지정가"

            if split_row_data[-1].rstrip() == '매수전' and new_price <= current_rate[i][0]:
                self.kiwoom.send_order("send_order_req", "0101", account, 1, code, num, int(new_price), hoga_lookup[hoga], "")
                if self.kiwoom.orderNum:
                    for i, row_data in enumerate(buy_list):
                        buy_list[i] = buy_list[i].replace("매수전", "주문완료")
            elif split_row_data[-1].rstrip() == '매수전' and self.is_trading_time() == False:
                self.kiwoom.send_order("send_order_req", "0101", account, 1, code, num, price, hoga_lookup[hoga], "")
                if self.kiwoom.orderNum:
                    for i, row_data in enumerate(buy_list):
                        buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2, code, num, price, hoga_lookup[hoga], "")
                if self.kiwoom.orderNum:
                    for i, row_data in enumerate(buy_list):
                        sell_list[i] = sell_list[i].replace("매도전", "주문완료")
        #파일 정보 변경
        # buy list
        """for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")"""

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        """for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")"""

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        # buy list
        # j:행, i:열
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    def save_final_stock(self):
        item_count = len(self.kiwoom.opw00018_output['multi'])
        if(self.is_trading_time() == False):
            self.final_stock = []
            for i in range(item_count):
                row = self.kiwoom.opw00018_output['multi'][i][3]
                self.final_stock.append(row)
            print(self.final_stock)
        #if(self.is_trading_time() == True):
            #종가 파일로 저장.



    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True


        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    # 체크 박스 체크?
    def timeout2(self):
        #if self.checkBox.isChecked():
        self.check_balance()
        self.check_chejan_balance()

    def check_chejan_balance(self):

        self.kiwoom.reset_opt10075_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opt10075_req", "opt10075", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opt10075_req", "opt10075", 0, "2000")

        item_count = len(self.kiwoom.opt10075_output['no_che'])
        self.tableWidget_4.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opt10075_output['no_che'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_4.setItem(j, i, item)

        self.tableWidget_4.resizeRowsToContents()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw0001TR (예수금 데이터)
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        #balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        # 나머지 칼럼 (table1)
        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i-1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        # 행 높이 조절
        self.tableWidget.resizeRowsToContents()

        # Item list (보유 종목별 평가 잔고)
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)
        self.tableWidget_2.resizeRowsToContents()

    def get_ohlcv(self, code, start):
        #self.get_ohlcv("035720", "20190604")
        self.kiwoom.ohlcv = {'date': [], 'close': []}
        self.kiwoom.final = {'close': []}
        self.kiwoom.current = {'current': []}

        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.set_input_value("기준일자", start)
        self.kiwoom.set_input_value("수정주가구분", 1)
        self.kiwoom.comm_rq_data("opt10081_req", "opt10081", 0, "0101")

        #time.sleep(0.2)
        #df = DataFrame(self.kiwoom.ohlcv, columns=['close'],
        #              index=self.kiwoom.ohlcv['date'])
        #return self.kiwoom.ohlcv

    def run(self):
        true_close = []
        true_current = []
        code = []
        today = datetime.datetime.today().strftime("%Y%m%d")
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()

        for row_data in buy_list:
            split_row_data = row_data.split(';')
            code.append(split_row_data[1])
        for i in range(len(code)):
            print("code: ", code[i])
            self.get_ohlcv(code[i], today)
            true_close.append(self.kiwoom.final['close'])
            true_current.append(self.kiwoom.current['current'])
        print(true_close)

        f.close()
        return (true_close, true_current)
Example #6
0
class STA_download():
    def __init__(self):
        # self.info_download()
        # self.bi_download()
        # self.dc_download()
        self.ss_download()
        pass
    
    # ss: short sales // download to db required
    def ss_download(self): 
        app = QApplication([''])
        self.k = Kiwoom()
        ss = self.shortsales_record('005930')
        print(ss)

    # dc: daecha // download to db required
    def dc_download(self):
        app = QApplication([''])
        self.k = Kiwoom()
        # should iterate over dates and code
        # may require to use multiprocessing
        dt1 = self.daecha_trading_record_mkt('20200901', '20200908')
        dt2 = self.daecha_trading_record_code('20200901', '20200908', '005930')
        print(dt1)
        print(dt2)

    ##################
    # program: arbitrage vs non-arbitrage
    # use opt90013: need to be implemented in Kiwoom
    ##################
    
    ##################
    # figure fgn money distribution out and relative performance
    ##################

    ##################
    # validate Morgan Stanley assumption / analysis
    ##################

    # bi: by investors
    def bi_download(self):
        if not os.path.exists(BYINVESTOR_DB): 
            print("byinvestor.db file exis")
            sys.exit()
        topsize = 200
        stepsize = 2
        toptotal = self.get_top_n_code(topsize)
        for i in range(0, topsize, stepsize):
            codelist = toptotal[i:i+stepsize]
            print(codelist, i)
            bi_singlerun_proc = multiprocessing.Process(target=self.bi_download_singlerun, args=(codelist,), daemon=True) 
            bi_singlerun_proc.start()
            bi_singlerun_proc.join()
            bi_singlerun_proc.terminate()
            time.sleep(WAIT_INTERVAL)

    def bi_download_singlerun(self, codelist):
        app = QApplication([''])
        self.k = Kiwoom()
        for code in codelist:
            print(code)
            bi_buy = self.investor_history_singlecase(code, netbuysell='1')
            bi_sell = self.investor_history_singlecase(code, netbuysell='2')
            con = sqlite3.connect(BYINVESTOR_DB)
            bi_buy.to_sql(f'buy{code}', con, if_exists='replace', index = False)
            bi_sell.to_sql(f'sell{code}', con, if_exists='replace', index = False)
            con.close()
        
        # bi_net could be easily constructed through the following: 
        # bi_net = bi_buy.copy()
        # bi_net.loc[:, 'ppl':] = bi_buy.loc[:, 'ppl':] + bi_sell.loc[:, 'ppl':]

    def get_top_n_code(self, n):
        if not os.path.exists(INFO_DB): 
            print("infodb.db file does not exist")
            sys.exit()
        con = sqlite3.connect(INFO_DB)
        idb = pd.read_sql_query(f'select * from {INFO_DB_TABLE}', con)
        con.close()
        return list(idb.nlargest(n, 'mktcap')['code'])

    # info: general info per each code
    def info_download(self):
        app = QApplication([''])
        self.k = Kiwoom()
        if os.path.exists(INFO_DB): 
            print("infodb.db file exists")
            sys.exit()
        self.codelist = self.k.get_codelist_by_market(0).split(';')[:-1]
        self.codelist += self.k.get_codelist_by_market(10).split(';')[:-1]
        self.infodb = pd.DataFrame(columns = ['code', 'cprice', 'total_shares', 'trade_shares', 'fgn_weight', 'PER', 'EPS', 'ROE', 'PBR', 'EV', 'BPS', 'mktcap', 
                                              'sales', 'EBIT', 'netprofit', 'date', 'status', 'name', 'note']).astype({
                                            'code': 'object', 'cprice': 'int64', 'total_shares': 'int64', 'trade_shares': 'int64', 'fgn_weight': 'int64', 
                                            'PER': 'float64', 'EPS': 'int64', 'ROE': 'float64', 'PBR': 'float64', 'EV': 'float64', 'BPS': 'int64', 'mktcap': 'int64', 
                                            'sales': 'int64', 'EBIT': 'int64', 'netprofit': 'int64', 'date': 'object', 'status': 'object', 'name': 'object', 'note': 'object'})
        con = sqlite3.connect(INFO_DB)
        resume_location = 0 # that is the last number printed or INFO_DOWNLOAD_CHUNK * num saved 
        self.infodb.to_sql(INFO_DB_TABLE, con, if_exists = 'append', index = False) # adjust 'replace' as needed
        con.close()

        i = 0
        for code in self.codelist[resume_location:]:
            print('.', end="")
            i += 1
            info_code = self.k.get_basic_info(code)
            info_code['date'] = pd.Timestamp.now().strftime("%Y%m%d")
            self.infodb.loc[len(self.infodb)] = info_code
            if i % INFO_DOWNLOAD_CHUNK == 0:
                print(f' {i}')
                con = sqlite3.connect(INFO_DB)
                self.infodb.to_sql(INFO_DB_TABLE, con, if_exists = 'append', index = False)
                con.close()
                self.infodb.drop(self.infodb.index, inplace = True)
                time.sleep(WAIT_INTERVAL)

        con = sqlite3.connect(INFO_DB)
        self.infodb.to_sql(INFO_DB_TABLE, con, if_exists = 'append', index = False)
        con.close()
        self.infodb.drop(self.infodb.index, inplace = True)

        # cur = con.cursor()
        # cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
        # cur.execute("drop table 'table_name';")
        # res = cur.fetchall()
        # print(res)

    #OPT10068 - no next page available. should adjust start_date and end_date
    def daecha_trading_record_mkt(self, start_date, end_date):
        self.k.set_input_value('시작일자', start_date)
        self.k.set_input_value('종료일자', end_date)
        self.k.set_input_value('전체구분', '1')
        self.k.set_input_value('종목코드', '')
        self.k.comm_rq_data('OPT10068_req', 'OPT10068', 0, '1000')
        dt = pd.DataFrame(self.k.opt10068_multi_data_set)

        if len(dt) == 0:
            print('Kiwoom data download error')
            sys.exit()
            
        dt = dt.astype({0: 'object', 1: 'int64', 2: 'int64', 3: 'int64', 4: 'int64', 5: 'int64'})
        dt.rename(columns = {0: 'date', 1: 'dc_new', 2: 'dc_ret', 3: 'dc_inc', 4: 'dc_remained', 5: 'dc_amount'}, inplace = True)
        return dt

    #opt20068 - no next page available. should adjust start_date and end_date
    def daecha_trading_record_code(self, start_date, end_date, code):
        self.k.set_input_value('시작일자', start_date)
        self.k.set_input_value('종료일자', end_date)
        self.k.set_input_value('전체구분', '0')
        self.k.set_input_value('종목코드', code)
        self.k.comm_rq_data('opt20068_req', 'opt20068', 0, '1000')
        dt = pd.DataFrame(self.k.opt20068_multi_data_set)

        if len(dt) == 0:
            print('Kiwoom data download error')
            sys.exit()

        dt = dt.astype({0: 'object', 1: 'int64', 2: 'int64', 3: 'int64', 4: 'int64', 5: 'int64'})
        dt.rename(columns = {0: 'date', 1: 'dc_new', 2: 'dc_ret', 3: 'dc_inc', 4: 'dc_remained', 5: 'dc_amount'}, inplace = True)
        return dt


    def shortsales_record(self, code): 
        # opt10014 Short Selling  ---------------------------------
        self.k.set_input_value('종목코드', code)
        self.k.set_input_value('시간구분', STA_DATE_PERIOD) # 0: by date, 1: by period
        self.k.set_input_value('시작일자', STA_START_DATE) # if by date, this input ignored
        self.k.set_input_value('종료일자', STA_END_DATE) # should be later than start date
        self.k.comm_rq_data('opt10014_req', 'opt10014', 0, '2000')
        ss = pd.DataFrame(self.k.opt10014_multi_data_set)

        for i in range(STA_NUMBER_TO_RECEIVE_NEXTPAGE):
            print('.', end='')
            if self.k.remained_data:
                self.k.set_input_value('종목코드', code)
                self.k.set_input_value('시간구분', STA_DATE_PERIOD)
                self.k.set_input_value('시작일자', STA_START_DATE)
                self.k.set_input_value('종료일자', STA_END_DATE)
                self.k.comm_rq_data('opt10014_req', 'opt10014', 2, '2000')
                ss =ss.append(pd.DataFrame(self.k.opt10014_multi_data_set)) 
            else: 
                break
        print()
        if len(ss) == 0:
            print('Kiwoom data download error')
            sys.exit()

        # incrate in %
        # volume in a single share
        # shortwgt in %
        # shortamt in 1000
        # clprice = closing price
        ss.reset_index(drop=True, inplace=True)
        ss = ss.astype({0: 'object', 1: 'int64', 2: 'int64', 3: 'int64', 4: 'float64', 5: 'int64', 6: 'int64', 7: 'float64', 8: 'int64', 9: 'int64'})
        ss.rename(columns = {0: 'date', 1: 'clprice', 2: 'deltakey', 3: 'delta', 4: 'incrate', 5: 'volume', 6: 'shortvol', 7: 'shortwgt', 8: 'shortamt', 9: 'shortprice'}, inplace = True)
        ss.clprice = ss.clprice.abs()
        return ss

    def investor_history_singlecase(self, code, moneyquantity='2', netbuysell='0'):
        # opt10059 By Investor  ---------------------------------
        self.k.set_input_value('일자', STA_END_DATE)
        self.k.set_input_value('종목코드', code)
        self.k.set_input_value('금액수량구분', moneyquantity)  # 1: money amount, 2: quantity of units
        self.k.set_input_value('매매구분', netbuysell)  # 0: net, 1: buy, 2: sell
        self.k.set_input_value('단위구분', STA_UNIT) # 1000: a thousand unit, 1: a unit
        self.k.comm_rq_data('opt10059_req', 'opt10059', 0, '3000')
        bi = pd.DataFrame(self.k.opt10059_multi_data_set)

        for i in range(STA_NUMBER_TO_RECEIVE_NEXTPAGE):
            print('.', end='')
            if self.k.remained_data:
                self.k.set_input_value('일자', STA_END_DATE)
                self.k.set_input_value('종목코드', code)
                self.k.set_input_value('금액수량구분', moneyquantity)  # 1: money amount in 1M KRW, 2: quantity of units
                self.k.set_input_value('매매구분', netbuysell)  # 0: net, 1: buy, 2: sell
                self.k.set_input_value('단위구분', STA_UNIT) # 1000: a thousand unit, 1: a unit
                self.k.comm_rq_data('opt10059_req', 'opt10059', 2, '3000')
                bi = bi.append(pd.DataFrame(self.k.opt10059_multi_data_set))
            else: 
                break
        print()
        if len(bi) == 0:
            print('Kiwoom data download error')
            sys.exit()
        
        # incrate in basis point
        # amount in million KRW
        # t_inst = fininv + insu + trust + finetc + bank + pensvg + prieqt + nation
        # volume or amount = ppl + fgn + t_inst +  corpetc + fgnetc when buy/sell(negative)
        # 0  = ppl + fgn + t_inst + nation + corpetc + fgnetc when buy when net
        bi.reset_index(drop=True, inplace=True)
        bi = bi.astype({0: 'object', 1: 'int64', 2: 'int64', 3: 'int64', 4: 'int64', 5: 'int64', 6: 'int64', 7: 'int64', 8: 'int64', 9: 'int64', 
                        10: 'int64', 11: 'int64', 12: 'int64', 13: 'int64', 14: 'int64', 15: 'int64', 16: 'int64', 17: 'int64', 18: 'int64', 19: 'int64'})
        bi.rename(columns = {0: 'date', 1: 'price', 2: 'deltakey', 3: 'delta', 4: 'incrate', 5: 'volume', 6: 'amount', 7: 'ppl', 8: 'fgn', 9: 't_inst', 10: 'fininv', 
                            11: 'insu', 12: 'trust', 13: 'finetc', 14: 'bank', 15: 'pensvg', 16: 'prieqt', 17: 'nation', 18: 'corpetc', 19: 'fgnetc'}, inplace = True)
        bi.price = bi.price.abs()
        return bi
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.token = ""

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.code = '093320'
        self.name = self.kiwoom.get_master_code_name(self.code)
        self.kiwoom.current = {}

        self.past_price = 0
        self.past_ratio = 0
        self.past_amount = 0

        # Timer1 - 1초에 한 번씩 이벤트가 발생한다.
        self.timer = QTimer(self)
        self.timer.start(1000 * 15)
        self.timer.timeout.connect(self.timeout_visualize)

        self.timer = QTimer(self)
        self.timer.start(1000 * 30)
        self.timer.timeout.connect(self.timeout_message)

    def request_data(self, code):
        """
        데이터 요청

        :param code:
        :return:
        """
        self.kiwoom.current = {}
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.comm_rq_data("opt10001_req", 'opt10001', 0, '2000')

    def timeout_visualize(self):
        """
        30초마다 서버로부터 가격, 상승률, 양을 가져온다.

        :return:
        """
        current_time = QTime.currentTime()

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

        self.request_data(self.code)
        self.lineEdit.setText(self.kiwoom.get_master_code_name(self.code))
        self.lineEdit_2.setText(self.kiwoom.current['price'])
        self.lineEdit_3.setText(self.kiwoom.current['ratio'])
        self.lineEdit_4.setText(self.kiwoom.current['amount'])

    def timeout_message(self):
        """
        60초마다 변경 사항이 있을 시 텔레그램 메세지를 보낸다.

        :return:
        """
        bot = telegram.Bot(token=self.token)
        chat_id = bot.getUpdates()[-1].message.chat.id

        price = self.kiwoom.current['price']
        ratio = self.kiwoom.current['ratio']
        amount = self.kiwoom.current['amount']

        if self.past_price != price:
            message = self.name + "\n" + \
                  "현재 가격: " + price + "\n" + \
                  "등락율: " + ratio + "%\n" + \
                  "거래량: " + amount + "\n"
            bot.sendMessage(chat_id=chat_id, text=message)

            self.past_price = price
            self.past_ratio = ratio
            self.past_amount = amount
Example #8
0
class Bring_stock_data():
    def __init__(self):
        super().__init__()

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.kiwoom.ohlcv = {
            'date': [],
            'open': [],
            'high': [],
            'low': [],
            'close': [],
            'volume': []
        }
        self.kiwoom.df_10001 = {
            'code': [],
            'name': [],
            'month': [],
            'face_value': [],
            'capital': []
        }
        self.kiwoom.df_10002 = {
            'code': [],
            'name': [],
            '매도거래원명1': [],
            '매도거래원1': [],
            '매도거래량1': [],
            '매수거래원명1': [],
            '매수거래원1': [],
            '매수거래량1': []
        }
        self.kiwoom.df_10003 = {'시간': [], '현재가': [], '누적거래량': []}
        self.kiwoom.df_10004 = {
            '총매도잔량': [],
            '총매수잔량': [],
            '시간외매도잔량': [],
            '시간외매수잔량': []
        }
        self.kiwoom.df_10005 = {
            '날짜': [],
            '시가': [],
            '고가': [],
            '저가': [],
            '종가': []
        }
        self.kiwoom.df_10006 = {
            '날짜': [],
            '시가': [],
            '고가': [],
            '저가': [],
            '종가': []
        }
        self.kiwoom.df_20006 = {'일자': [], '시가': [], '고가': [], '저가': []}

    # 주식 기본정보를 df로 받는다.
    def load_item_basic_info(self):
        stock_code = input("stock_code: ")
        start_date = input("start_date: ")
        stock_code = str(stock_code)
        start_date = str(start_date)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.set_input_value("조회일자", start_date)
        self.kiwoom.comm_rq_data("opt10086_req", "opt10086", 0, "0124")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", stock_code)
            self.kiwoom.set_input_value("조회일자", start_date)
            self.kiwoom.comm_rq_data("opt10086_req", "opt10086", 2, "0124")

        df = pd.DataFrame(self.kiwoom.ohlcv,
                          columns=['open', 'high', 'low', 'close', 'volume'],
                          index=self.kiwoom.ohlcv['date'])
        print(df)
        print("save_to_csv")
        df.to_csv(
            "C:\\workplace\\atm_project\\atm_ver_0.1_jh\\item_basic_info.csv",
            mode='w')

        return df

    def get_tr10001_data(self):
        stock_code = input("stock_code: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "0286")

        print(self.kiwoom.df_10001)

        df = pd.DataFrame(self.kiwoom.df_10001,
                          columns=['name', 'month', 'face_value', 'capital'],
                          index=self.kiwoom.df_10001['code'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10001.csv",
                  mode='w')

    def get_tr10002_data(self):
        stock_code = input("stock_code: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10002_req", "opt10002", 0, "0129")

        print(self.kiwoom.df_10002)
        df = pd.DataFrame(self.kiwoom.df_10002,
                          columns=[
                              'name', '매도거래원명1', '매도거래원1', '매도거래량1', '매수거래원명1',
                              '매수거래원1', '매수거래량1'
                          ],
                          index=self.kiwoom.df_10002['code'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10002.csv",
                  mode='w')

    def get_tr10003_data(self):
        stock_code = input("stock_code: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10003_req", "opt10003", 0, "0120")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", stock_code)
            self.kiwoom.comm_rq_data("opt10003_req", "opt10003", 2, "0120")

        print(self.kiwoom.df_10003)
        df = pd.DataFrame(self.kiwoom.df_10003,
                          columns=['현재가', '누적거래량'],
                          index=self.kiwoom.df_10003['시간'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10003.csv",
                  mode='w')

    def get_tr10004_data(self):
        stock_code = input("종목코드: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10004_req", "opt10004", 0, "0119")

        df = pd.DataFrame(self.kiwoom.df_10004,
                          columns=['총매도잔량', '총매수잔량', '시간외매도잔량', '시간외매수잔량'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10004.csv",
                  mode='w')

    def get_tr10005_data(self):
        stock_code = input("종목코드: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10005_req", "opt10005", 0, "0124")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", stock_code)
            self.kiwoom.comm_rq_data("opt10005_req", "opt10005", 2, "0124")

        df = pd.DataFrame(self.kiwoom.df_10005,
                          columns=['시가', '고가', '저가', '종가'],
                          index=self.kiwoom.df_10005['날짜'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10005.csv",
                  mode='w')

    def get_tr10006_data(self):
        stock_code = input("종목코드: ")
        stock_code = str(stock_code)

        self.kiwoom.set_input_value("종목코드", stock_code)
        self.kiwoom.comm_rq_data("opt10006_req", "opt10006", 0, "0124")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", stock_code)
            self.kiwoom.comm_rq_data("opt10006_req", "opt10006", 2, "0124")

        df = pd.DataFrame(self.kiwoom.df_10006,
                          columns=['시가', '고가', '저가', '종가'],
                          index=self.kiwoom.df_10006['날짜'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr10006.csv",
                  mode='w')

    def get_tr20006_data(self):
        market_code = input("업종코드: ")
        start_date = input("기준일자: ")
        market_code = str(market_code)
        start_date = str(start_date)

        self.kiwoom.set_input_value("업종코드", market_code)
        self.kiwoom.set_input_value("기준일자", start_date)
        self.kiwoom.comm_rq_data("opt20006_req", "opt20006", 0, "0602")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("업종코드", market_code)
            self.kiwoom.set_input_value("기준일자", start_date)
            self.kiwoom.comm_rq_data("opt20006_req", "opt20006", 2, "0602")

        df = pd.DataFrame(self.kiwoom.df_20006,
                          columns=['시가', '고가', '저가'],
                          index=self.kiwoom.df_20006['일자'])
        print(df)
        print("save_to_csv")
        df.to_csv("C:\\workplace\\atm_project\\atm_ver_0.1_jh\\tr20006.csv",
                  mode='w')

    # df를 csv파일로 저장
    def save_df_to_csv(self, df):
        print("stock_save_to_csv")
        df.to_csv(
            "C:\\workplace\\atm_project\\atm_ver_0.1_jh\\item_basic_info.csv",
            mode='w')
Example #9
0
class PyMon:
    def __init__(self):
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()
        self.stratagy = SysStratagy()

    def run(self):
        # self.run_pbr_per_screener()
        # self.run_condition_data()
        # self.get_codition_stock_list()
        self.init_maedo_proc()

    def init_maedo_proc(self):
        self.check_balance()
        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        if item_count == 0:
            print("보유종목이 없습니다. [", item_count, "]")
            pass
        # 한 종목에 대한 종목명, 보유량, 매입가, 현재가, 평가손익, 수익률(%)은 출력
        stratagy = SysStratagy()
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            boyou_cnt = int(row[1].replace(',', ''))
            maeip_price = int(row[2].replace(',', ''))
            stock_code = row[6]
            mado_price = stratagy.get_maedo_price(maeip_price, 1.02)
            self.add_stock_sell_info(stock_code, mado_price, boyou_cnt)

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]  # 첫번째 계좌번호 호출

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

    def add_stock_sell_info(self, code, sell_price, sell_qty):
        dm = ';'
        b_gubun = "매도"
        b_status = "매도전"
        b_price = sell_price
        b_method = "지정가"
        b_qty = sell_qty
        included = False
        code_info = self.kiwoom.get_master_code_name(code)
        mste_info = self.kiwoom.get_master_construction(code)
        stock_state = self.kiwoom.get_master_stock_state(code)
        print(code_info, mste_info, stock_state)

        f = open(self.kiwoom.sell_loc, 'rt', encoding='UTF-8')
        sell_list = f.readlines()
        f.close()

        if self.stratagy.isTimeAvalable(self.kiwoom.maesu_start_time,
                                        self.kiwoom.maesu_end_time):
            if len(sell_list) > 0:
                write_mode = 'a'  # 추가
            else:
                write_mode = 'wt'

            for stock in sell_list:
                if code in stock:
                    included = True
                else:
                    included = False

            if included == False:
                f = open(self.kiwoom.sell_loc, write_mode, encoding='UTF-8')
                stock_info = b_gubun + dm + code + dm + b_method + dm + str(
                    b_qty) + dm + str(b_price) + dm + b_status
                f.write(stock_info + '\n')
                f.close()
        else:
            f = open(self.kiwoom.sell_loc, 'wt', encoding='UTF-8')
            stock_info = b_gubun + dm + code + dm + b_method + dm + str(
                b_qty) + dm + str(b_price) + dm + b_status
            f.write(stock_info + '\n')
            f.close()
Example #10
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        # 한번에 한 종목에 들어갈 돈 세팅
        self.one_buy_money = 10000000

        self.setupUi(self)
        self.load_data_lock = False
        self.trade_stocks_done = False
        self.choose_buy_done = False
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton_2.clicked.connect(self.check_balance)

        self.load_buy_sell_list()

        # Timer2
        self.timer2 = QTimer(self)
        #3 sec로 세팅 ms단위
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.pushButton.clicked.connect(self.send_order)
        # 처음에 조회
        self.check_balance()
        self.kiwoom.dynamicCall("GetConditionLoad()")
        self.kiwoom.tr_event_loop = QEventLoop()
        self.kiwoom.tr_event_loop.exec_()

    # 0529 - YW : 자동으로 검색식에 있는 종목을 매수 설정한다.
    # sell은 잔고자동편입을 이용한다.
    # algorithm 조건 식 종류 선택
    def choose_buy(self, algorithm):
        # 화면번호, 조건식명, 조건식 index, 0: 정적조회, 1: 실시간 조회
        print("choose buy")
        self.kiwoom.reset_condition_output()

        # 처음은 종가과매수만 진행할 예정
        if algorithm == 0:
            self.kiwoom.get_condition("0156", "S_종가과매수", 0, 0)
        # 05 29 add for test
        elif algorithm == 1:
            self.kiwoom.get_condition("0156", "무패신호", 7, 0)

        # self.kiwoom.condition_output에 종목코드가 list로 들어가 있음

        # make buy_list file
        f = codecs.open("data/buy_list.txt", 'w', 'utf-8')
        log = codecs.open("data/log_file.txt", 'a', 'utf-8')
        now = datetime.now()
        log.write('\n%s-%s-%s %s:%s\n' %
                  (now.year, now.month, now.day, now.hour, now.minute))
        self.load_data_lock = True
        for i in self.kiwoom.condition_output:
            #일단은 시장가매수

            name = self.kiwoom.get_master_code_name(i)
            last_price = int(self.fetch_chart_data(i))
            order_number = int(self.one_buy_money / last_price)
            order_price = last_price
            log.write("%s, %s, %s원, %s주, %d만원 \n" %
                      (i, name, last_price, order_number,
                       last_price * order_number / 10000))
            f.write("매수,%s,시장가,%d,%d,매수전\n" % (i, order_number, order_price))
        f.close()
        log.close()
        self.load_data_lock = False

    #종목 코드 기준 날짜
    #기준 날짜부터 과거까지 순서로 조회한다. but 지금은 당일 data만 필요
    def fetch_chart_data(self, code_num):
        self.kiwoom.reset_ohlcv()
        base_date = datetime.today().strftime('%Y%m%d')
        self.kiwoom.call_day_chart(code_num, base_date, 1)
        # 판다스를 이용하여 저장
        df = pd.DataFrame(self.kiwoom.ohlcv,
                          columns=['open', 'high', 'low', 'close', 'volume'],
                          index=self.kiwoom.ohlcv['date'])
        return df.ix[base_date]["close"]

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = codecs.open("data/buy_list.txt", 'r', 'utf-8')
        buy_list = f.readlines()
        f.close()

        f = codecs.open("data/sell_list.txt", 'r', 'utf-8')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(',')
            try:
                hoga = split_row_data[2]
            except:
                break
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(',')
            try:
                hoga = split_row_data[2]
            except:
                break
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

        # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # file update
        f = codecs.open("data/buy_list.txt", 'w', 'utf-8')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = codecs.open("data/sell_list.txt", 'w', 'utf-8')
        for row_data in sell_list:
            f.write(row_data)
        f.close()

    def load_buy_sell_list(self):
        f = codecs.open("data/buy_list.txt", "r", "utf-8")
        buy_list = f.readlines()
        f.close()

        f = codecs.open("data/sell_list.txt", "r", "utf-8")
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(',')
            try:
                split_row_data[1] = self.kiwoom.get_master_code_name(
                    split_row_data[1].rstrip())
            except:
                break

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                if i == 0:
                    item.setForeground(Qt.red)
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(',')
            try:
                split_row_data[1] = self.kiwoom.get_master_code_name(
                    split_row_data[1].rstrip())
            except:
                break

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                if i == 0:
                    item.setForeground(Qt.blue)
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    def timeout(self):
        # 9시 1분에 주문넣기
        market_start_time = QTime(9, 1, 0)
        market_end_time = QTime(15, 30, 0)
        current_time = QTime.currentTime()

        if market_start_time < current_time < market_end_time and self.trade_stocks_done is False:
            self.trade_stocks_done = True
            self.trade_stocks()
            self.trade_stocks_done = False
        #3시 10분 종목선정~

        if QTime(15, 10, 0) < current_time and self.choose_buy_done is False:
            self.choose_buy(0)
            self.choose_buy_done = True

        # 오후 6시 프로그램 자동 종료
        if current_time > QTime(18, 00, 0):
            print("End program")
            self.quit()

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()
        #print(account, order_type,code,hoga,num,price)
        #print(order_type_lookup[order_type],hoga_lookup[hoga] )
        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def timeout2(self):
        #연속조회시 transaction 충돌로 starvation이 걸림
        if self.load_data_lock is False:
            #체크 하지 않아도 system trading 업데이트
            self.load_buy_sell_list()
            #check 했을 때 만 자동 조회
            if self.checkBox.isChecked():
                self.check_balance()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]
        account_number = self.comboBox.currentText()

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)
        #single
        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])

            if i == 3 or i == 4:
                if item.text().startswith('-'):
                    item.setForeground(Qt.blue)
                else:
                    item.setForeground(Qt.red)

            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # multi Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                if i == len(row) - 1 or i == len(row) - 2:
                    if item.text().startswith('-'):
                        item.setForeground(Qt.blue)
                    else:
                        item.setForeground(Qt.red)

                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
Example #11
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.timer2 = QTimer(self)
        self.timer2.start(1000 *10)
        self.timer2.timeout.connect(self.timeout2)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account, order_type_lookup[order_type], code, num, price, hoga_lookup[hoga], "")

    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i - 1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
Example #12
0
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        #QtGui.QMainWindow.__init__(self,parent)
        #self.setupUi(self)

        # 키움 API 접속
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        #키움 API 신호
        #self.kiwoom.OnEventConnect.connect(self._event_connect)
        #self.kiwoom.OnReceiveTrData.connect(self._receive_tr_data)

        # 타이틀 설정
        self.setWindowTitle("종목 코드")
        self.setGeometry(300, 300, 300, 180)

        #1초 타이머 설정
        self.timer1s = QTimer(self)
        self.timer1s.start(1000)
        self.timer1s.timeout.connect(self.timer1sec)

        # 400ms 타이머 설정
        self.timer10ms = QTimer(self)
        self.timer10ms.start(400)
        self.timer10ms.timeout.connect(self.getdatatimer)
        self.getdataflag = 0
        self.getdatacount = -1

        self.prvFilename = ""

        self.temp = 0

        self.setupUI()

    def setupUI(self):

        # StatusBar
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)

        # button 1
        self.btn1 = QPushButton("연결", self)
        self.btn1.move(190, 10)
        self.btn1.clicked.connect(self.btn1_clicked)

        # button 2
        self.btn2 = QPushButton("데이터 산출", self)
        self.btn2.move(190, 45)
        self.btn2.clicked.connect(self.btn2_clicked)

        # button 3
        self.btn3 = QPushButton("데이터 분절", self)
        self.btn3.move(190, 80)
        self.btn3.clicked.connect(self.btn3_clicked)

        self.btn1.setDisabled(1)
        self.btn2.setDisabled(1)
        self.btn3.setDisabled(1)

        self.listWidget = QListWidget(self)
        self.listWidget.setGeometry(10, 10, 170, 130)

    def timer1sec(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 성공"
            self.btn1.setDisabled(1)
            self.btn2.setDisabled(0)
            self.btn3.setDisabled(0)
        else:
            state_msg = "서버 미접속"
            self.btn1.setDisabled(0)
            self.btn2.setDisabled(1)
            self.btn3.setDisabled(1)
        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def getdatatimer(self):
        if self.kiwoom.dataReceived == 1:
            current_date = QDate.currentDate()
            filename = '..\\data\\' + current_date.toString(
                "yyyyMMdd") + '_' + self.codelist[self.getdatacount] + '.csv'

            if filename == self.prvFilename:
                with open(filename, 'a') as sfile:
                    i = 0
                    if self.kiwoom.dataunit != None:
                        while i < len(self.kiwoom.dataunit):
                            for j in range(0, 6):
                                if j == 2:  # 날짜인 경우
                                    sfile.write("'" +
                                                self.kiwoom.dataunit[i][j] +
                                                "'")
                                else:
                                    sfile.write(self.kiwoom.dataunit[i][j])
                                if j != 5:
                                    sfile.write(",")
                                else:
                                    sfile.write('\n')
                            i = i + 1
                        self.kiwoom.dataReceived = 0
            else:
                if self.prvFilename != "":
                    time.sleep(12)
                logfilename = 'lastest.txt'
                with open(logfilename, 'w') as logfile:
                    logfile.write(self.prvFilename)
                current_time = QTime.currentTime()
                self.listWidget.insertItem(
                    0,
                    current_time.toString("hh:mm:ss") + " - " +
                    self.codelist[self.getdatacount] + " 조회 시작")
                self.prvFilename = filename
                with open(filename, 'w') as sfile:
                    i = 0
                    if self.kiwoom.dataunit != None:
                        while i < len(self.kiwoom.dataunit):
                            for j in range(0, 6):
                                if j == 2:  # 날짜인 경우
                                    sfile.write("'" +
                                                self.kiwoom.dataunit[i][j] +
                                                "'")
                                else:
                                    sfile.write(self.kiwoom.dataunit[i][j])

                                if j != 5:
                                    sfile.write(',')
                                else:
                                    sfile.write('\n')
                            i = i + 1
                        self.kiwoom.dataReceived = 0

        else:
            if self.getdataflag == 1:
                if self.kiwoom.remained_data == False:
                    self.getdatacount = self.getdatacount + 1

                if self.getdatacount < len(self.codelist):
                    self.kiwoom.set_input_value(
                        "종목코드", self.codelist[self.getdatacount])
                    self.kiwoom.set_input_value("시작일자", "20170805")
                    self.kiwoom.set_input_value("종료일자", "20170805")
                    self.kiwoom.set_input_value("수정주가구분", 0)
                    if self.kiwoom.remained_data == True:
                        self.kiwoom.comm_rq_data("주식분봉차트조회", "opt10080", 2,
                                                 "1001")
                    else:
                        self.kiwoom.comm_rq_data("주식분봉차트조회", "opt10080", 0,
                                                 "1001")
                else:
                    self.getdataflag = 0
                    self.getdatacount = 0

    def btn1_clicked(self):
        self.kiwoom.comm_connect()
        print(ret)
        if ret == 0:
            self.listWidget.insertItem(1, "로그인 성공")
        else:
            self.listWidget.insertItem(1, "로그오프")

    def btn2_clicked(self):
        codestring = self.kiwoom.get_kospi_code_list()
        self.codelist = codestring.split(";")
        self.getdataflag = 1

    def btn3_clicked(self):
        files = glob.glob('..\\data\\*.csv')
        while len(files) > i:
            with open(files[i], 'r') as sfile:  #파일 순차적으로 열기
                fileline = sfile.readlines()
                linecount = 0
                filecount = 0
                oclock = 0
                while len(fileline) > linecount:
                    featuredata = fileline[linecount].split(",")
                    if oclock != int(featuredata[2][9:10]):  #시간이 변경되면 파일 변경
                        oclock = int(featuredata[2][9:10])

                    with open(files[i], 'w') as sfile:
                        i = i + 1
Example #13
0
class TR_Practice(QMainWindow):
    def __init__(self):
        super().__init__()

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.kiwoom.ohlcv = {
            'date': [],
            'open': [],
            'high': [],
            'low': [],
            'close': [],
            'volume': []
        }
        self.kiwoom.trp20002 = {
            'code': [],
            'name': [],
            'cur_price': [],
            'volume': [],
            'high_price': [],
            'low_price': []
        }
        self.kiwoom.trp20006 = {'date': [], 'cur_price': [], 'volume': []}
        self.kiwoom.trp20007 = {
            'date': [],
            'cur_price': [],
            'high_price': [],
            'low_price': [],
            'volume': []
        }
        self.kiwoom.trp50036 = {
            'date': [],
            'yesterday_end_price': [],
            'gift_historic_variability': []
        }
        self.kiwoom.trp50037 = {'date': [], 'kospi_200_index': []}

    def business_type_juga(self):
        # market_gubun = input("market_gubun : ")
        # business_code = input("business_code : ")

        # self.kiwoom.set_input_value("시장구분", market_gubun)
        # self.kiwoom.set_input_value("업종코드", business_code)

        self.kiwoom.set_input_value("시장구분", "0")
        self.kiwoom.set_input_value("업종코드", "001")
        self.kiwoom.comm_rq_data("OPT20002_req", "OPT20002", 0, "0213")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("시장구분", "0")
            self.kiwoom.set_input_value("업종코드", "001")
            self.kiwoom.comm_rq_data("OPT20002_req", "OPT20002", 2, "0213")

        trp20002_df = pd.DataFrame(self.kiwoom.trp20002,
                                   columns=[
                                       "code", "name", "cur_price", "volume",
                                       "high_price", "low_price"
                                   ],
                                   index=self.kiwoom.trp20002["code"])
        trp20002_df.to_csv('C:\\workplace\\atm_project\\tr20002.csv',
                           encoding='ms949')
        #print(trp20002_df)
        return trp20002_df

    def business_ilbong_load(self):
        # market_gubun = input("market_gubun : ")
        # business_code = input("business_code : ")

        # self.kiwoom.set_input_value("시장구분", market_gubun)
        # self.kiwoom.set_input_value("업종코드", business_code)

        self.kiwoom.set_input_value("업종코드", "001")
        self.kiwoom.set_input_value("기준일자", "20190218")
        self.kiwoom.comm_rq_data("opt20006_req", "opt20006", 0, "0202")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("업종코드", "001")
            self.kiwoom.set_input_value("기준일자", "20190218")
            self.kiwoom.comm_rq_data("opt20006_req", "opt20006", 2, "0202")

        trp20006_df = pd.DataFrame(self.kiwoom.trp20006,
                                   columns=["cur_price", "volume"],
                                   index=self.kiwoom.trp20006["date"])
        trp20006_df.to_csv('C:\\workplace\\atm_project\\tr20006.csv',
                           encoding='ms949')
        #print(trp20006_df)
        return trp20006_df

    def business_jubong_load(self):
        business_code = input("business_code : ")
        standard_date = input("standard_date : ")
        #스트링 변환 넣어주기
        #상동 *2

        self.kiwoom.set_input_value("업종코드", business_code)
        self.kiwoom.set_input_value("기준일자", standard_date)
        self.kiwoom.comm_rq_data("opt20007_req", "opt20007", 0, "0202")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("업종코드", business_code)
            self.kiwoom.set_input_value("기준일자", standard_date)
            self.kiwoom.comm_rq_data("opt20007_req", "opt20007", 2, "0202")

        trp20007_df = pd.DataFrame(
            self.kiwoom.trp20007,
            columns=["cur_price", "high_price", "low_price", "volume"],
            index=self.kiwoom.trp20007["date"])
        trp20007_df.to_csv('C:\\workplace\\atm_project\\tr20007.csv',
                           encoding='ms949')
        print(trp20007_df)
        return trp20007_df

    def major_index_variability_chart(self):
        # event_code = input("event_code : ")
        # standard_date = input("standard_date : ")
        # period = input("period : ")
        # chart_gubun = input("chart_gubun : ")
        event_code = '_JP#NI225'
        standard_date = '20190220'
        period = 2
        chart_gubun = 0

        self.kiwoom.set_input_value("종목코드", str(event_code))
        self.kiwoom.set_input_value("기준일자", str(standard_date))
        self.kiwoom.set_input_value("기간", period)
        self.kiwoom.set_input_value("차트구분", chart_gubun)
        self.kiwoom.comm_rq_data("opt_50036_req", "OPT50036", 0, "0733")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", str(event_code))
            self.kiwoom.set_input_value("기준일자", str(standard_date))
            self.kiwoom.set_input_value("기간", period)
            self.kiwoom.set_input_value("차트구분", chart_gubun)
            self.kiwoom.comm_rq_data("OPT50036_req", "OPT50036", 2, "0733")

        trp50036_df = pd.DataFrame(self.kiwoom.trp50036,
                                   columns=[
                                       "date", "yesterday_end_price",
                                       "gift_historic_variability"
                                   ],
                                   index=self.kiwoom.trp50036["date"])
        trp50036_df.to_csv('C:\\workplace\\atm_project\\tr50036.csv',
                           encoding='ms949')
        print(trp50036_df)
        return trp50036_df

    def kospi200_index_load(self):
        event_code = input("event_code : ")
        standard_date = input("standard_date : ")
        event_code = str(event_code)
        standard_date = str(standard_date)

        self.kiwoom.set_input_value("종목코드", event_code)
        self.kiwoom.set_input_value("기준일자", standard_date)
        self.kiwoom.comm_rq_data("opt50037_req", "opt50037", 0, "0221")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("종목코드", event_code)
            self.kiwoom.set_input_value("기준일자", standard_date)
            self.kiwoom.comm_rq_data("opt50037_req", "opt50037", 2, "0221")

        trp50037_df = pd.DataFrame(self.kiwoom.trp50037,
                                   columns=["kospi_200_index"],
                                   index=self.kiwoom.trp50037["date"])
        trp50037_df.to_csv('C:\\workplace\\atm_project\\tr50037.csv',
                           encoding='ms949')
        print(trp50037_df)
        return trp50037_df
Example #14
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        # Database 연결
        self.con = sqlite3.connect("HBase.db")
        self.cursor = self.con.cursor()

        #보유종목현황 / 선정 종목 버튼 리스트
        self.btn_list1 = []
        self.btn1_num = 0
        self.btn_list2 = []
        self.btn2_num = 0

        #현재 시간을 알려주기 위한 Timer
        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        #실시간 잔고 및 보유종목 현황을 보여주기 위한 Timer
        self.timer2 = QTimer(self)
        self.timer.start(5000)
        self.timer.timeout.connect(self.timeout2)

        #종목코드 입력
        self.lineEdit.textChanged.connect(self.code_change)
        #계좌번호 출력
        accounts_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accounts_num]
        self.comboBox.addItems(accounts_list)
        #주문버튼 / 잔고 조회 버튼
        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)
        #선정 종목 정보 출력
        self.load_buy_sell_list()

        #self.kiwoom._set_real_reg("6000", "8121773611", "8019", "0") //실시간 정보 확인

    #프로그램 상에서 수동 주문하는 함수 -> 주문 정보를 DB에 저장
    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        #프로그램 상에서 텍스트 박스 상의 정보를 이용하여 주문
        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        current_time = QTime.currentTime().toString()
        now = datetime.now()
        current_date = str(now.year) + '-' + str(now.month) + '-' + str(
            now.day)

        #구매 정보 DB에 저장
        if order_type == '신규매수':
            sql = "INSERT INTO buy_inform VALUES("
            sql = sql + "'" + current_date + "'" + "," + "'" + current_time + "'" + "," + "'" + name + "'" + "," + "'" + code + "'" + "," + "'수동주문'" + ")"
            self.cursor.execute(sql)
            self.con.commit()
        elif order_type == '신규매도':
            sql = "INSERT INTO sell_inform VALUES("
            #buy_inform 에서 데이터가져오기  // 매수 정보에서 불러온 정보와 더불어 매도 정보에 저장
            df = pd.read_sql("SELECT * FROM buy_inform",
                             self.con,
                             index_col=None)
            df_num = len(df)

            for i in range(df_num - 1, -1, -1):
                if df.loc[i, "종목명"] == name:
                    buy_date = df.loc[i, "매수날짜"]
                    buy_time = df.loc[i, "매수시각"]
                    buy_reason = df.loc[i, "매수근거"]
                    break

            #보유종목현황에서 데이터가져오기
            item_count = len(self.kiwoom.opw00018_output['multi'])
            for j in range(item_count):
                row = self.kiwoom.opw00018_output['multi'][j]
                if row[0] == name:
                    sql = sql + "'" + buy_date + "','" + buy_time + "','" + current_date + "','" + current_time + "','" + row[
                        0] + "','" + row[1] + "','" + row[2] + "','" + row[
                            3] + "','" + row[4] + "','" + row[5] + "','" + row[
                                6] + "','" + row[
                                    7] + "','" + buy_reason + "'," + "'수동주문'" + ")"
                    #delete_sql = "DELETE FROM buy_inform WHERE 종목명 = "
                    #delete_sql = delete_sql + "'" + name + "'"
                    self.cursor.execute(sql)
                    #self.cursor.execute(delete_sql)
                    self.con.commit()
                    break
        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def code_change(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    #종목번호를 누르면 네이버,다음 증권 정보를 불러옴
    def link_btn(self):
        naver_url = "https://finance.naver.com/item/fchart.nhn?code="
        daum_url = "https://finance.daum.net/quotes/"
        sender = self.sender()
        code = sender.text()
        daum_url = daum_url + "A" + code + "#chart"
        webbrowser.open_new(daum_url)
        code = re.findall('\d+', code)[0]
        naver_url = naver_url + code
        webbrowser.open_new(naver_url)

    #현재 보유하고 있는 주식과 잔고를 보여주는 함수
    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        #opw00018 - 각 종목에 대한 비중, 매입가, 평가액 등을 요청
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        #opw00001 - 이틀 뒤의 예수금을 보여줌
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        #balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        #Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                if i == 1:
                    self.btn_list1.append(QPushButton(self.tableWidget_2))
                    self.btn_list1[self.btn1_num].setText(row[i])
                    self.btn_list1[self.btn1_num].clicked.connect(
                        self.link_btn)
                    self.tableWidget_2.setCellWidget(
                        j, i, self.btn_list1[self.btn1_num])
                    self.btn1_num += 1
                else:
                    item = QTableWidgetItem(row[i])
                    item.setTextAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
                    self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    #매수해야 하는 목록, 매도해야 하는 목록을 불러와 표로 보여주는 함수
    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt', encoding='UTF8')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt', encoding='UTF8')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        #buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')

            for i in range(len(split_row_data)):
                if i == 1:
                    self.btn_list2.append(QPushButton(self.tableWidget_2))
                    self.btn_list2[self.btn2_num].setText(
                        split_row_data[i].rstrip())
                    self.btn_list2[self.btn2_num].clicked.connect(
                        self.link_btn)
                    self.tableWidget_3.setCellWidget(
                        j, i, self.btn_list2[self.btn2_num])
                    self.btn2_num += 1
                else:
                    item = QTableWidgetItem(split_row_data[i].rstrip())
                    item.setTextAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
                    self.tableWidget_3.setItem(j, i, item)

        #sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')

            for i in range(len(split_row_data)):
                if i == 1:
                    self.btn_list2.append(QPushButton(self.tableWidget_2))
                    self.btn_list2[self.btn2_num].setText(
                        split_row_data[i].rstrip())
                    self.btn_list2[self.btn2_num].clicked.connect(
                        self.link_btn)
                    self.tableWidget_3.setCellWidget(
                        len(buy_list) + j, i, self.btn_list2[self.btn2_num])
                    self.btn2_num += 1
                else:
                    item = QTableWidgetItem(split_row_data[i].rstrip())
                    item.setTextAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
                    self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    #현재 작성되어 있는 매수해야하는 목록과 매도해야 하는 목록을 바탕으로 매수,매도 진행
    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt', encoding='UTF8')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt', encoding='UTF8')
        sell_list = f.readlines()
        f.close()

        #acoount
        account = self.comboBox.currentText()

        #Current Time and Date Check
        current_time = QTime.currentTime().toString()
        now = datetime.now()
        current_date = str(now.year) + '-' + str(now.month) + '-' + str(
            now.day)

        #buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[3]
            code = split_row_data[1]
            name = split_row_data[2]
            num = split_row_data[4]
            price = split_row_data[5]
            buy_reason = split_row_data[7]

            if split_row_data[6].rstrip() == '매수전':
                sql = "INSERT INTO buy_inform VALUES("
                sql = sql + "'" + current_date + "'" + "," + "'" + current_time + "'" + "," + "'" + name + "'" + "," + "'" + code + "','" + buy_reason + "')"
                self.cursor.execute(sql)
                self.con.commit()
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")

        #sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[3]
            code = split_row_data[1]
            name = split_row_data[2]
            num = split_row_data[4]
            price = split_row_data[5]
            sell_reason = split_row_data[7]

            if split_row_data[6].rstrip() == '매도전':
                sql = "INSERT INTO sell_inform VALUES("
                # buy_inform 에서 데이터가져오기
                df = pd.read_sql("SELECT * FROM buy_inform",
                                 self.con,
                                 index_col=None)
                df_num = len(df)
                for i in range(df_num - 1, -1, -1):
                    if df.loc[i, "종목명"] == name:
                        buy_date = df.loc[i, "매수날짜"]
                        buy_time = df.loc[i, "매수시각"]
                        buy_reason = df.loc[i, "매수근거"]
                        break

                # 보유종목현황에서 데이터가져오기
                item_count = len(self.kiwoom.opw00018_output['multi'])
                for j in range(item_count):
                    row = self.kiwoom.opw00018_output['multi'][j]
                    if row[0] == name:
                        sql = sql + "'" + buy_date + "','" + buy_time + "','" + current_date + "','" + current_time + "','" + \
                              row[0] + "','" + row[1] + "','" + row[2] + "','" + row[3] + "','" + row[4] + "','" + row[
                                  5] + "','" + row[6] + "','" + row[7] + "','" + buy_reason + "','" + sell_reason + "')"
                        # delete_sql = "DELETE FROM buy_inform WHERE 종목명 = "
                        # delete_sql = delete_sql + "'" + name + "'"
                        self.cursor.execute(sql)
                        # self.cursor.execute(delete_sql)
                        self.con.commit()
                        break

                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

        #buy / sell list replace
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        #file update
        f = open("buy_list.txt", 'wt', encoding='UTF8')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        f = open("sell_list.txt", 'wt', encoding='UTF8')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.trade_stocks_done = False

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        # Timer1 - 1초에 한 번씩 이벤트가 발생한다.
        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        # Account 정보 가져오기
        accounts_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accounts_num]
        self.lineEdit.textChanged.connect(self.code_changed)
        self.comboBox.addItems(accounts_list)
        self.comboBox_2.addItems(['신규주문', '신규매도', '매수취소', '매도취소'])
        self.comboBox_3.addItems(['지정가', '시장가'])

        # Order
        self.pushButton.clicked.connect(self.send_order)

        # Balance
        self.pushButton_2.clicked.connect(self.check_balance)

        # Timer2 - 10초에 한 번씩 이벤트를 발생한다.
        self.timer2 = QTimer(self)
        self.timer2.start(1000*10)
        self.timer2.timeout.connect(self.timeout2)

        # Load Buy and Sell list
        self.load_buy_sell_list()

    def timeout(self):
        """
        TImer

        :return:
        """
        # 장시작 시 주문
        market_start_time = QTime(9, 0, 0)
        market_end_time = QTime(15, 30, 0)
        current_time = QTime.currentTime()

        if market_start_time < current_time < market_end_time:
            if self.trade_stocks_done is False:
                self.trade_stocks()

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def code_changed(self):
        """
        사용자가 입력한 종목 정보를 얻어온다.

        :return:
        """
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1,
                             '신규매도': 2,
                             '매수취소': 3,
                             '매도취소': 4}
        hoga_lookup = {'지정가': '00', '시장가': '03'}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", '0101', account, order_type_lookup[order_type], code, num, price, hoga_lookup[hoga], "")

    def check_balance(self):
        """
        계좌 전체 잔고 및 종목별 수익 현황을 출력

        :return:
        """
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:

            # opw00018
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i-1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)
        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    def timeout2(self):
        """
        실시간 조회 기능 구현

        :return:
        """
        if self.checkBox.isChecked():
            self.check_balance()

    # load buy list
    def load_buy_sell_list(self):
        """
        buy and sell list를 텍스트 파일로부터 불러온다.

        :return:
        """
        f = open('buy_list.txt', 'rt', encoding='UTF8')
        buy_list = f.readlines()
        f.close()

        f = open('sell_list.txt', 'rt', encoding='UTF8')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        # buy_list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell_list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    # trade stocks
    def trade_stocks(self):
        """
        stock을 거래한다.

        :return:
        """
        hoga_lookup = {'지정가': '00', '시장가': '03'}

        f = open('buy_list.txt', 'rt', encoding='UTF8')
        buy_list = f.readlines()
        f.close()

        f = open('sell_list.txt', 'rt', encoding='UTF8')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy_list
        buy_return_list = [-1] * len(buy_list)
        for i, row_data in enumerate(buy_list):
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == "매수전":
                buy_return = self.kiwoom.send_order("send_order_req", '0101', account, 1, code, num, price, hoga_lookup[hoga], "")

                if buy_return == 0:
                    buy_return_list[i] = 0
            elif split_row_data[-1].rstrip() == "주문완료":
                buy_return_list[i] = 0

        for i, row_data in enumerate(buy_list):
            if buy_return_list[i] == 0:
                buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # sell_list
        sell_return_list = [-1] * len(sell_list)
        for i, row_data in enumerate(sell_list):
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == "매도전":
                sell_return = self.kiwoom.send_order("send_order_req", '0101', account, 2, code, num, price, hoga_lookup[hoga], "")

                if sell_return == 0:
                    sell_return_list[i] = 0
            elif split_row_data[-1].rstrip() == "주문완료":
                sell_return_list[i] = 0

        for i, row_data in enumerate(sell_list):
            if sell_return_list[i] == 0:
               sell_list[i] = sell_list[i].replace('매도전', '주문완료')

        trade_sum = 0
        for i, row_data in enumerate(buy_list):
            split_row_data = row_data.split(';')
            if split_row_data[-1].rstrip() == '주문완료':
                trade_sum += 1

        for i, row_data in enumerate(sell_list):
            split_row_data = row_data.split(';')
            if split_row_data[-1].rstrip() == '주문완료':
                trade_sum += 1

        print(trade_sum)
        if trade_sum == len(buy_list) + len(sell_list):
            self.trade_stocks_done = True

        # file update
        f = open('buy_list.txt', "wt", encoding='UTF8')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # file update
        f = open('sell_list.txt', "wt", encoding='UTF8')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
Example #16
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.saveditem = Saveditem()

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        fname = "ongoing_list.txt"
        if not os.path.isfile(fname):
            f = open(fname, 'wt')
            f.close()

        # 선정 종목 리스트
        self.load_buy_sell_list()
        self.file_upload()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        #실시간 현재가
        self.scrnum = 5000
        self.set_current()
        self.kiwoom.OnReceiveRealData.connect(self.kiwoom._receive_real_data)
        self.kiwoom.sig_cl.sig_.connect(self.stockgridview)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]

        self.comboBox.addItems(accounts_list)
        self.exe_save = 0
        self.pushButton.clicked.connect(self.save_ongoing)
        #self.check_chejan_balance()
        self.check_balance()

        # 주문 들어가는 부분
        self.timer3 = QTimer(self)
        self.timer3.start(1000 * 10)
        self.timer3.timeout.connect(self.timeout3)

    # 화면번호
    def getnum(self):
        if self.scrnum < 9999:
            self.scrnum += 1
        else:
            self.scrnum = 5000
        return int(self.scrnum)

    #실시간 현재가 불러오기 위한 종목코드 수집
    def file_upload(self):
        # 오늘의 추천 파일만 확인
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        self.ncode = []
        #self.check_price = []
        for i in range(len(buy_list)):
            split_row_data = buy_list[i].split(' ')
            self.ncode.append(split_row_data[8])
            #self.check_price.append(split_row_data[14])

    #실시간 설정
    def set_current(self):
        print(self.ncode)
        for i in range(0, len(self.ncode)):
            self.kiwoom._set_real_reg(self.getnum(), self.ncode[i], "9001;10",
                                      "0")

    def stockgridview(self):
        item_cnt = len(self.saveditem.item_view)
        self.scode_list = list(self.saveditem.item_view.keys())
        self.tableWidget_5.setRowCount(item_cnt)
        for i in range(item_cnt):
            for j in range(3):
                #print(self.savedstockitem.item_view[self.scode_list[i]][j])
                item = QTableWidgetItem(
                    self.saveditem.item_view[self.scode_list[i]][j])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_5.setItem(i, j, item)

    # 버튼으로 파일 저장
    def save_ongoing(self):
        self.exe_save = 1
        self.check_chejan_balance()

    # 거래시간 확인
    def is_trading_time(self):
        global special
        vals = []
        current_time = datetime.datetime.now().time()
        #print(current_time)
        for start, end in TRADING_TIME:
            # 수능날
            now = datetime.datetime.now()
            soo_day = datetime.datetime.today().weekday()
            soo = now.isocalendar()
            # 수능날
            if soo_day == 3 and soo[1] == 46:
                start_time = datetime.time(hour=9, minute=start[1])
                end_time = datetime.time(hour=16, minute=end[1])
            # 새해 다음날
            elif now.month == 1 and now.day == 2:
                start_time = datetime.time(hour=9, minute=start[1])
                end_time = datetime.time(hour=end[0], minute=end[1])
            else:
                start_time = datetime.time(hour=start[0], minute=start[1])
                end_time = datetime.time(hour=end[0], minute=end[1])

            if (current_time >= start_time and current_time <= end_time):
                vals.append(True)
            else:
                vals.append(False)
                pass
        if vals.count(True):
            return True
        else:
            return False

    def is_end_time(self):
        vals = []
        current_time = datetime.datetime.now().time()
        for start, end in TRADING_TIME:
            now = datetime.datetime.now()
            soo_day = datetime.datetime.today().weekday()
            soo = now.isocalendar()
            # 수능날
            if now.month == 11 and soo_day == 3:
                if soo[1] == 46:
                    start_time = datetime.time(hour=16, minute=20)
            # 새해 다음날
            elif now.month == 1 and now.day == 2:
                start_time = datetime.time(hour=15, minute=20)
            # 동시 호가 시간 포함한 3시 30분
            else:
                end_che = datetime.time(hour=4, minute=15)
                start_time = datetime.time(hour=end[0], minute=end[1] + 10)
            if (current_time >= start_time):
                vals.append(True)
            elif (current_time >= end_che and current_time <= start_time):
                vals.append(False)
            else:
                vals.append(False)
                pass
        if vals.count(True):
            return True
        else:
            return False

    # 자동 주문
    def trade_stocks(self):
        self.is_order_correct()
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        global lr_list
        global pr_list

        current_time = datetime.datetime.now()

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        account = self.comboBox.currentText()

        now = datetime.datetime.now()
        soo_day = datetime.datetime.today().weekday()
        soo = now.isocalendar()
        today_hd = datetime.datetime.today().strftime("%Y%m%d")

        order_check1 = ["주문완료", "매도완료"]

        # 매수
        for i in range(len(buy_list)):
            split_row_data = buy_list[i].split(' ')
            machine = split_row_data[0]
            code = split_row_data[8]
            num = split_row_data[13]
            price = split_row_data[14]
            hoga = "지정가"

            #print("first_order", self.first_order)
            if self.is_trading_time() == True:
                if code in self.scode_list:
                    if not machine in order_check1:
                        if int(price) <= int(
                                self.saveditem.item_view[code][1]):
                            print("{0}: 코드, {1}: 주문가격 {2}: 현재가".format(
                                code, int(price),
                                int(self.saveditem.item_view[code][1])))
                            self.kiwoom.send_order("send_order_req", "0101",
                                                   account, 1, code, int(num),
                                                   int(price),
                                                   hoga_lookup[hoga], "")
                            buy_list[i] = buy_list[i].replace(
                                machine, order_check1[0])
            f = open("buy_list.txt", 'wt')
            for row_data in buy_list:
                f.write(row_data)
        # 매도
        num_data = len(self.kiwoom.opw00018_output['multi'])

        for i in range(num_data):
            code_name = self.kiwoom.opw00018_output['compare'][i][0]
            quantity = self.kiwoom.opw00018_output['compare'][i][1]
            current_price = self.kiwoom.opw00018_output['compare'][i][2]
            purchase_price = self.kiwoom.opw00018_output['compare'][i][3]
            print("종목이름: %s, 현재가격: %s, 구입가격: %s" %
                  (code_name, current_price, purchase_price))

            location = 0
            while (location < len(current_price)):
                if current_price[location] == ',':
                    current_price = current_price[:location] + current_price[
                        location + 1::]
                location += 1
            current_price = int(current_price)

            location2 = 0
            while (location2 < len(purchase_price)):
                if purchase_price[location2] == ',':
                    purchase_price = purchase_price[:
                                                    location2] + purchase_price[
                                                        location2 + 1::]
                location2 += 1

            for j in range(len(buy_list)):
                split_row_data = buy_list[j].split(' ')
                machine = split_row_data[0]
                hd = split_row_data[7]
                code = split_row_data[8]
                num = split_row_data[13]
                price = split_row_data[14]
                pr = split_row_data[15]
                lr = split_row_data[16].replace("\n", "")
                hoga = "지정가"

                code_new = self.kiwoom.get_master_code_name(code)

                due_time = current_time.replace(hour=15,
                                                minute=15,
                                                second=0,
                                                microsecond=0)
                if soo_day == 3 and soo[1] == 46:
                    due_time = current_time.replace(hour=16,
                                                    minute=15,
                                                    second=0,
                                                    microsecond=0)

                if due_time < current_time and machine == "주문완료":
                    print(hd, today_hd)
                    if hd == today_hd:
                        self.kiwoom.send_order("send_order_req", "0101",
                                               account, 2, code, num,
                                               current_price,
                                               hoga_lookup[hoga], "")
                        print("hd 만료, 시장가 판매")
                        buy_list[j] = buy_list[j].replace(machine, "매도완료")

                #if code_name == code_new and int(quantity) >= int(num): << 에러남 확인 바람
                if code_name == code_new:
                    print("code name: %s, lr: %f, pr: %f" %
                          (code, float(lr), float(pr)))
                    pr_price = float(pr) * int(purchase_price)
                    print("pr_price: %f * %d = %d" %
                          (float(pr), int(purchase_price), int(pr_price)))
                    lr_price = float(lr) * float(purchase_price)
                    pr_price = int(pr_price)
                    lr_price = int(lr_price)
                    lr_list[code_name] = lr_price
                    pr_list[code_name] = pr_price
                    print("profit rate price: ", pr_price)
                    print("loss rate price: ", lr_price)
                    print("current price: ", current_price)

                    if machine == "주문완료" and self.is_trading_time() == True:

                        if (current_price >= pr_price):
                            self.kiwoom.send_order("send_order_req", "0101",
                                                   account, 2, code, num,
                                                   current_price,
                                                   hoga_lookup[hoga], "")
                            print("pr 주문완료")
                            print(account, code, num, current_price,
                                  hoga_lookup[hoga])
                            buy_list[j] = buy_list[j].replace(machine, "매도완료")
                            break

                        elif current_price <= lr_price:
                            self.kiwoom.send_order("send_order_req", "0101",
                                                   account, 2, code, num,
                                                   current_price,
                                                   hoga_lookup[hoga], "")
                            print(account, code, num, current_price,
                                  hoga_lookup[hoga])
                            buy_list[j] = buy_list[j].replace(machine, "매도완료")
        print(lr_list)
        print(pr_list)

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

    def load_buy_sell_list(self):

        global file_changed

        current_time = datetime.datetime.now()
        today_file = datetime.datetime.today().strftime("%Y%m%d")

        file_name = today_file + "추천.txt"
        print(file_name)

        if os.path.isfile(file_name) == False:
            print("오늘의 추천 파일을 찾을 수 없습니다.")

        elif file_changed == False and current_time < current_time.replace(
                hour=15, minute=16):
            print(file_name, " buy_list로 변환")
            f = open(file_name, 'rt')
            temp_list = f.readlines()
            f.close()

            frow_data = []
            for row_data in temp_list:
                frow_data.append(' '.join(row_data.split()))
            frow_data = filter(str.strip, frow_data)
            temp = []
            for x in frow_data:
                temp.append(x)

            bl = []
            for j in range(2, len(temp) - 1):
                x = []
                split_row_data = temp[j].split(' ')
                split_row_data[7] = (
                    split_row_data[7][split_row_data[7].find("(") +
                                      1:split_row_data[7].find(")")])
                split_row_data[8] = re.sub(r'\([^)]*\)', '', split_row_data[8])
                split_row_data[9] = split_row_data[9].replace("원", "")
                split_row_data[9] = split_row_data[9].replace(",", "")
                split_row_data[13] = split_row_data[13].replace("주", "")
                split_row_data[13] = split_row_data[13].replace(",", "")
                split_row_data[14] = split_row_data[14].replace("원", "")
                split_row_data[14] = int(split_row_data[14].replace(",", ""))

                for i in range(len(split_row_data)):
                    x.append(split_row_data[i])
                x = map(str, x)
                y = " ".join(x)
                bl.append(y)

            # 전날 미매도 파일 불러오기
            f = open("ongoing_list.txt", 'rt')
            sell_list = f.readlines()
            sell_list2 = [s.rstrip() for s in sell_list]
            bl += sell_list2
            f.close()

            f = open("buy_list.txt", 'wt')
            for i in range(len(bl)):
                # print(bl[i])
                f.write(bl[i])
                f.write("\n")
            f.close()

            file_changed = True
            print("file_changed?? ", file_changed)

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        row_count = len(buy_list)
        self.tableWidget_3.setRowCount(row_count)

        self.num_name = {}
        # buy list
        # j:행, i:열
        for j in range(len(buy_list)):
            split_row_data = buy_list[j].split(' ')
            temp_name = split_row_data[8]
            # 종목명 구하기
            code_name = self.kiwoom.get_master_code_name(temp_name)
            self.num_name[code_name] = temp_name

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        self.tableWidget_3.resizeRowsToContents()
        print("num_name", self.num_name)

    def timeout(self):
        # market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()
        """if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True"""
        now = QDate.currentDate()
        text_time = now.toString(
            Qt.DefaultLocaleLongDate) + " " + current_time.toString("hh:mm:ss")
        time_msg = text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout3(self):
        print(datetime.datetime.now())
        self.check_balance()
        print("check_balance 완료")
        self.check_chejan_balance()
        print("check_chejan_balance 완료")
        self.trade_stocks()
        print("trade_stocks 완료")
        self.load_buy_sell_list()
        print("load_buy_sell_list 완료")

    def check_chejan_balance(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        name = []
        num_order = []
        file_price = []
        buy_list2 = []
        check_order = []
        self.first_order = {}

        for i in range(len(buy_list)):
            split_row_data = buy_list[i].split(' ')
            machine = split_row_data[0]
            code = split_row_data[8]
            num = split_row_data[13]
            price = int(split_row_data[14])
            name.append(code)
            num_order.append(num)
            file_price.append(price)
            check_order.append(machine)
        # SetInputValue(입력 데이터 설정)과 CommRqData(TR 요청)
        # 최대 20개의 보유 종목 데이터 리턴 반복
        self.kiwoom.reset_opt10075_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opt10075_req", "opt10075", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opt10075_req", "opt10075", 0, "2000")
            # if self.is_trading_time() == False:
            #    break

        item_count = len(self.kiwoom.opt10075_output['no_che'])
        self.tableWidget_4.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opt10075_output['no_che'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_4.setItem(j, i, item)
                # 매수만 된 종목 확인
                if row[0] == '접수':
                    if row[1] == '+매수':
                        self.first_order[int(self.num_name[self.kiwoom.opt10075_output['no_che'][j][3]])] = \
                        int(self.kiwoom.opt10075_output['no_che'][j][7])
                # ongoin_list 저장
                if self.is_end_time() == True or self.exe_save == 1:
                    if row[0] == '체결':
                        # 오늘자 파일의 매수 확인 후 ongoing_list에 저장
                        if row[1] == '+매수':
                            # if row[1] == '-매도':
                            for l in range(0, j + 1):
                                if self.kiwoom.opt10075_output['no_che'][l][3] == \
                                        self.kiwoom.opt10075_output['no_che'][j][3]:
                                    # print("l-{0} {1}".format(l, self.kiwoom.opt10075_output['no_che'][l]))
                                    # print("j-{0} {1}".format(j, self.kiwoom.opt10075_output['no_che'][j]))
                                    # 후에 매도가 됐는지 확인
                                    if not self.kiwoom.opt10075_output[
                                            'no_che'][l][1] == '-매도':
                                        for k in range(len(buy_list)):
                                            if int(self.num_name[self.kiwoom.opt10075_output['no_che'][j][3]]) == int(name[k]) \
                                                    and int(self.kiwoom.opt10075_output['no_che'][j][4]) == int(num_order[k])\
                                                    and int(self.kiwoom.opt10075_output['no_che'][j][7]) == int(file_price[k]):
                                                #print(buy_list[k])
                                                #buy_list[k].replace(self.check_price[k], '-1')
                                                buy_list2.append(buy_list[k])
                        # 계속 감시 중인 종목이 매도되지 않을 시 ongoing_list에 추가
                        elif row[1] == '-매도':
                            for s in range(len(buy_list)):
                                if check_order[s] == "주문완료":
                                    if not int(self.num_name[self.kiwoom.opt10075_output['no_che'][j][3]]) == int(name[s]) \
                                        and int(self.kiwoom.opt10075_output['no_che'][j][4]) == int(num_order[s]):
                                        buy_list2.append(buy_list[s])

                                # print(self.kiwoom.opt10075_output['no_che'][j][3])
                                # print("l - %d, j - %d" %(l, j))
                                # print("확인용", self.kiwoom.opt10075_output['no_che'][l])
                            """for k in range(len(buy_list)):
                                if int(self.num_name[row[3]]) == int(name[k]):
                                    #print(k)
                                    #print(buy_list[k])
                                    buy_list2.append(buy_list[k])"""
        buy_list2 = list(set(buy_list2))
        if self.is_end_time() == True or self.exe_save == 1:
            f = open("ongoing_list.txt", 'wt')
            for row_data in buy_list2:
                row_data = row_data
                f.write(row_data)
            f.close()

        self.exe_save = 0
        self.tableWidget_4.resizeRowsToContents()

    # 잔고 및 보유 계좌 정보 확인
    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        # opw00001
        # 예수금 데이터 얻어오기
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
        #모의투자 시 밑의 세줄 주석 처리
        #self.kiwoom.set_input_value("비밀번호", "0000")
        #self.kiwoom.set_input_value("비밀번호입력매체구분", "00")
        #self.kiwoom.set_input_value("조회구분", 1)
        #self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
        # balance
        # 예수금 데이터 tableWidget에 출력
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        # 해당 칼럼에 값 추가
        for i in range(1, 6):
            print(self.kiwoom.opw00018_output['single'][i - 1])
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)
        # 아이템 크기에 맞춰 행 높이 조절
        self.tableWidget.resizeRowsToContents()
        # Item list 보유종목 출력
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            if row[0] in lr_list and pr_list:
                str_lr = str(lr_list[row[0]])
                row[4] = str_lr
                print(row[4])
                str_pr = str(pr_list[row[0]])
                row[5] = str_pr
                print(row[5])
            print(row)
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)
        self.tableWidget_2.resizeRowsToContents()

    # 매수 조건은 완료하였지만 실제 매수가 안 되는 경우가 있어 확인
    def is_order_correct(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        order_check1 = ["주문완료", "매도완료"]

        # 매수
        for i in range(len(buy_list)):
            split_row_data = buy_list[i].split(' ')
            machine = split_row_data[0]
            code = split_row_data[8]
            num = split_row_data[13]
            price = split_row_data[14]
            hoga = "지정가"

            if machine == order_check1[0]:
                if not int(code) in self.first_order:
                    buy_list[i] = buy_list[i].replace(machine, "미매수")

                f = open("buy_list.txt", 'wt')
                for row_data in buy_list:
                    f.write(row_data)
Example #17
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.trade_stocks_done = False

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)  #10초에 한번임
        self.timer2.timeout.connect(self.timeout2)

        #계좌정보 관련련
        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox_Acc.addItems(accounts_list)

        #종목코드 입력하면 호출되는 슬롯
        self.lineEdit_Stock_Code.textChanged.connect(self.code_changed)
        #주문 버튼
        self.pushButton_order.clicked.connect(self.send_order)
        #조회버튼
        self.pushButton_look.clicked.connect(self.check_balance)

        # 선정 종목 정보 출력 메서드
        self.load_buy_sell_list()

    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def code_changed(self):
        code = self.lineEdit_Stock_Code.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_Stock_Code_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox_Acc.currentText()
        order_type = self.comboBox_order_type.currentText()
        code = self.lineEdit_Stock_Code.text()
        hoga = self.comboBox_hoga.currentText()
        num = self.spinBox_num.value()
        price = self.spinBox_price.value()

        self.kiwoom.send_order("send_order_req", "0101", account, order_type_lookup[order_type], code, num, price,hoga_lookup[hoga], "")

    def check_balance(self):
        # 데이터 초기화 먼저 하고
        self.kiwoom.reset_opw00018_output()
        # 계좌 정보 불러오고
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        # set_input_value
        self.kiwoom.set_input_value("계좌번호", account_number)
        # opw00018 실행
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")
        # 보유종목이 20개이상일 경우 연속적으로 데이터 요청
        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001 d+2추정예수금
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        # 싱글데이터 (총매입, 총평가, 총손익, 총수익률, 추정자산)
        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i - 1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        # 아이템의 크기에 맞춰 행의 높이 조절
        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        # 보유종목 수에 따라서 행의 개수 설정
        self.tableWidget_2.setRowCount(item_count)
        
        # QTableWidget에 아이템 추가
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)
        # 아이템의 크기에 맞춰 행의 높이 조절
        self.tableWidget_2.resizeRowsToContents()


    def load_buy_sell_list(self):
        # 파일 읽어서 데이터 긁어오고 (인코딩에러 조심)
        # f = open("buy_list.txt", 'rt', encoding='UTF8')
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        # f = open("sell_list.txt", 'rt', encoding='UTF8')
        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()
        
        # 데이터의 총 개수 확인
        row_count = len(buy_list) + len(sell_list)
        # 자동 선정 종목 리스트 행 수 적용
        self.tableWidget_3.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            # 종목 코드를 종목 명으로 바꿔줌
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            # 종목 코드를 종목 명으로 바꿔줌
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        # f = open("buy_list.txt", 'rt', encoding='UTF8')
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        # f = open("sell_list.txt", 'rt', encoding='UTF8')
        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox_Acc.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1, code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2, code, num, price, hoga_lookup[hoga], "")

        # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
Example #18
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.timer2 = QTimer(self)
        self.timer2.start(1000 *10)
        self.timer2.timeout.connect(self.timeout2)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)

        self.load_buy_sell_list()

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1, code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2, code, num, price, hoga_lookup[hoga], "")

        # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContents()

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account, order_type_lookup[order_type], code, num, price, hoga_lookup[hoga], "")

    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i - 1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
Example #19
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.kiwoom.excelfile_initiator()
        self.kospi_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSPI)
        self.kosdaq_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSDAQ)
        self.candidate_codes = [
            '005930', '252670', '122630', '000660', '207940', '035420',
            '006400', '035720', '005380', '034730', '036570', '017670',
            '105560', '096770', '090430', '097950', '018260', '003550',
            '006800', '078930'
        ]

        # There can be limits in the number of timers
        self.timer = QTimer(self)
        self.timer.start(
            1000 * 10)  # Timer for time update: refresh at every 10*1000ms
        self.timer.timeout.connect(self.timeout)

        # self.timer_balance_check = QTimer(self)
        # self.timer_balance_check.start(1000*10)
        # self.timer_balance_check.timeout.connect(self.check_balance)

        self.timer_autotrade_run = QTimer(self)
        self.timer_autotrade_run.start(1000 * AUTOTRADE_INTERVAL)
        self.timer_autotrade_run.timeout.connect(self.timeout_autotrade_run)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton.clicked.connect(self.send_order_ui)
        self.pushButton_2.clicked.connect(self.check_balance)
        self.pushButton_3.clicked.connect(self.timeout_autotrade_run)

        self.check_balance()

    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm")
        time_msg = "Time: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "Server Connected"
        else:
            state_msg = "Server Not Connected"
        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout_autotrade_run(self):
        current_time = QTime.currentTime()
        if RUN_AUTOTRADE and not RUN_ANYWAY_OUT_OF_MARKET_OPEN_TIME:
            if datetime.datetime.today().weekday() in range(
                    0, 5
            ) and current_time > MARKET_START_TIME and current_time < MARKET_FINISH_TIME:
                self.autotrade_list_gen()
                self.trade_stocks()
                self.label_8.setText("Autotrade executed")
            else:
                self.label_8.setText("Market not open")
        elif RUN_AUTOTRADE:
            self.label_8.setText("Autotrade / market may not open")
            self.autotrade_list_gen()
            self.trade_stocks()
        else:
            self.label_8.setText("Autotrade disabled")

    def code_changed(self):
        code = self.lineEdit.text()
        if len(code) >= CODE_MIN_LENGTH:
            name = self.kiwoom.get_master_code_name(code)
            if name != "":
                self.kiwoom.set_input_value("종목코드", code)
                self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "1001")
                self.lineEdit_2.setText(name)
                self.spinBox_2.setValue(self.kiwoom.cur_price)
            else:
                self.lineEdit_2.setText("")
                self.spinBox_2.setValue(0)
        else:
            self.lineEdit_2.setText("")
            self.spinBox_2.setValue(0)

    def send_order_ui(self):
        order_type_lookup = {'Buy': 1, 'Sell': 2}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = HOGA_LOOKUP[self.comboBox_3.currentText()]
        num = self.spinBox.value()
        if hoga == "00":
            price = self.spinBox_2.value()
        elif hoga == "03":
            price = 0
        res = self.kiwoom.send_order("send_order_req", "0101", account,
                                     order_type_lookup[order_type], code, num,
                                     price, hoga, "")
        if res[0] == 0 and res[1] != "":
            self.label_8.setText("Order sent")
            ###################################
            if self.kiwoom.order_chejan_finished == True:
                self.label_8.setText("Order completed")
        else:
            self.label_8.setText("Errer in order processing")

    def check_balance(self):
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    def load_buy_sell_list(self):
        try:
            buy_list = pd.read_excel(EXCEL_BUY_LIST,
                                     index_col=None,
                                     converters={'Code': str})
        except Exception as e:
            print(e)
            buy_list = pd.DataFrame()

        try:
            sell_list = pd.read_excel(EXCEL_SELL_LIST,
                                      index_col=None,
                                      converters={'Code': str})
        except Exception as e:
            print(e)
            sell_list = pd.DataFrame()

        return [buy_list, sell_list]

###########################################################################
##### EXECUTION
###########################################################################

    def trade_stocks(self):
        [buy_list, sell_list] = self.load_buy_sell_list()

        # account
        account = self.comboBox.currentText()
        buy_order = 1
        sell_order = 2

        # buy_list
        for i in buy_list.index:
            if buy_list["Tr"][i] == 'yet' or buy_list["Tr"][i] == 'failed':
                hoga = HOGA_LOOKUP[buy_list["Order_type"][i]]
                if hoga == "00":
                    price = buy_list["Price"][i]
                elif hoga == "03":
                    price = 0
                res = self.kiwoom.send_order("send_order_req", "0101", account,
                                             buy_order, buy_list["Code"][i],
                                             int(buy_list["Amount"][i]), price,
                                             hoga, "")

                if res[0] == 0 and res[1] != "":
                    self.label_8.setText("Order sent: " + str(res[1]))
                    buy_list.at[i, "Tr"] = 'ordered'
                    ###################################
                    if self.kiwoom.order_chejan_finished == True:
                        buy_list.at[i, "Tr"] = 'done'
                else:
                    self.label_8.setText("Errer in order processing")
                    buy_list.at[i, "Tr"] = 'failed'

        buy_list.to_excel(EXCEL_BUY_LIST, index=False)

        # sell_list
        for i in sell_list.index:
            if sell_list["Tr"][i] == 'yet' or sell_list["Tr"][i] == 'failed':
                hoga = HOGA_LOOKUP[sell_list["Order_type"][i]]
                if hoga == "00":
                    price = sell_list["Price"][i]
                elif hoga == "03":
                    price = 0
                res = self.kiwoom.send_order("send_order_req", "0101", account,
                                             sell_order, sell_list["Code"][i],
                                             int(sell_list["Amount"][i]),
                                             price, hoga, "")
                if res[0] == 0 and res[1] != "":
                    self.label_8.setText("Order sent: " + str(res[1]))
                    sell_list.at[i, "Tr"] = 'ordered'
                    ###################################
                    if self.kiwoom.order_chejan_finished == True:
                        buy_list.at[i, "Tr"] = 'done'
                else:
                    self.label_8.setText("Errer in order processing")
                    sell_list.at[i, "Tr"] = 'failed'

        sell_list.to_excel(EXCEL_SELL_LIST, index=False)


###########################################################################
##### ALGORITHMS
###########################################################################

    def autotrade_list_gen(self):

        [code, price] = self.algo_random_choose_buy(3)
        # sell_list = self.algo_random_choose_sell(3)
        sell_list = self.algo_sell_by_return_range(10, -1)

        self.kiwoom.update_buy_list(code, price)
        self.kiwoom.update_sell_list(sell_list)

    def check_speedy_rising_volume(self, code):
        today = datetime.datetime.today().strftime("%Y%m%d")
        df = self.kiwoom.get_ohlcv(code, today)
        volumes = df['volume']

        if len(volumes) < 21:
            return False

        sum_vol20 = 0
        today_vol = 0

        for i, vol in enumerate(volumes):
            if i == 0:
                today_vol = vol
            elif 1 <= i <= 20:
                sum_vol20 += vol
            else:
                break
        avg_vol20 = sum_vol20 / 20

        if today_vol > avg_vol20 * 3:
            return True

        return False

    def algo_speedy_rising_volume(self):
        buy_list_code = []
        for i, code in enumerate(self.kosdaq_codes):
            if self.check_speedy_rising_volume(code):
                buy_list_code.append(code)
        return buy_list_code

    def algo_random_choose_buy(self, BUY_SELL_SIZE):
        buy_list_code = []
        buy_list_price = []
        for i in range(BUY_SELL_SIZE):
            code = random.choice(self.candidate_codes)
            self.kiwoom.set_input_value("종목코드", code)
            self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "1001")
            name = self.kiwoom.get_master_code_name(code)
            price = self.kiwoom.cur_price
            if price > MIN_STOCK_PRICE:
                buy_list_code.append(code)
                buy_list_price.append(price)
        return [buy_list_code, buy_list_price]

    def algo_random_choose_sell(self, BUY_SELL_SIZE):
        my_stock_list = self.kiwoom.get_my_stock_list()
        if len(my_stock_list) > BUY_SELL_SIZE:
            n = list(range(len(my_stock_list)))
            set_to_sell = random.sample(n, BUY_SELL_SIZE)
            return my_stock_list.iloc[set_to_sell]
        else:
            return my_stock_list

    def algo_sell_by_return_range(
            self, upperlimit,
            lowerlimit):  # upperlimit, lowerlimit in percentage
        my_stocks = self.kiwoom.get_my_stock_list()
        profit_sell_list = my_stocks[my_stocks['earning_rate'] > upperlimit]
        loss_sell_list = my_stocks[my_stocks['earning_rate'] < lowerlimit]
        print('Profit Sell List (up to 50 items): \n',
              tabulate(profit_sell_list[:50], headers='keys', tablefmt='psql'))
        print('Loss Sell List (up to 50 items): \n',
              tabulate(loss_sell_list[:50], headers='keys', tablefmt='psql'))
        return profit_sell_list.append(loss_sell_list)
Example #20
0
class Pymon:
    def __init__(self):
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()
        self.get_code_list()
        self.excelfile_initiator()

    def get_code_list(self):
        self.kospi_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSPI)
        self.kosdaq_codes = self.kiwoom.get_code_list_by_market(MARKET_KOSDAQ)

    def get_ohlcv(self, code, start):
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.set_input_value("기준일자", start)
        self.kiwoom.set_input_value("수정주가구분", 1)
        self.kiwoom.comm_rq_data("opt10081_req", "opt10081", 0, "0101")

        df = pd.DataFrame(self.kiwoom.ohlcv,
                          columns=['open', 'high', 'low', 'close', 'volume'],
                          index=self.kiwoom.ohlcv['date'])
        return df

    def update_buy_list(self, buy_list_code):
        buy_list = pd.read_excel(EXCEL_BUY_LIST,
                                 index_col=None,
                                 converters={'Code': str})

        for i, code in enumerate(buy_list_code):
            name = self.kiwoom.get_master_code_name(code)
            today = datetime.datetime.today().strftime("%Y%m%d")
            time_ = datetime.datetime.now().strftime("%H:%M:%S")
            self.kiwoom.set_input_value("종목코드", code)
            self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "1001")

            amount = round(ALLOCATION_SIZE / self.kiwoom.cur_price)
            buy_list = buy_list.append(
                {
                    'Date': today,
                    'Time': time_,
                    'Name': name,
                    'Code': code,
                    'Order_type': 'mkt',
                    'Tr': 'yet',
                    'Price': self.kiwoom.cur_price,
                    'Amount': amount
                },
                ignore_index=True)

        print('Buy List: \n',
              tabulate(buy_list, headers='keys', tablefmt='psql'))

        buy_list.to_excel(EXCEL_BUY_LIST, index=False)

    def get_stock_list(self):
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        stock_list = pd.DataFrame(self.kiwoom.opw00018_rawoutput,
                                  columns=[
                                      'name', 'code', 'quantity',
                                      'purchase_price', 'current_price',
                                      'invested_amount', 'current_total',
                                      'eval_profit_loss_price', 'earning_rate'
                                  ])
        for i in stock_list.index:
            stock_list.at[i, 'code'] = stock_list['code'][i][
                1:]  # taking off "A" in front of returned code
        return stock_list.set_index('code')

    def update_sell_list(self, sell_list_code):
        sell_list = pd.read_excel(EXCEL_SELL_LIST,
                                  index_col=None,
                                  converters={'Code': str})
        stock_list = self.get_stock_list()

        for i, code in enumerate(sell_list_code):
            if code in list(stock_list.index):
                name = self.kiwoom.get_master_code_name(code)
                today = datetime.datetime.today().strftime("%Y%m%d")
                time_ = datetime.datetime.now().strftime("%H:%M:%S")
                self.kiwoom.set_input_value("종목코드", code)
                self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0,
                                         "1001")  # getting current price

                amount = stock_list['quantity'][code]
                sell_list = sell_list.append(
                    {
                        'Date': today,
                        'Time': time_,
                        'Name': name,
                        'Code': code,
                        'Order_type': 'mkt',
                        'Tr': 'yet',
                        'Price': self.kiwoom.cur_price,
                        'Amount': amount
                    },
                    ignore_index=True)

        print('Sell List: \n',
              tabulate(sell_list, headers='keys', tablefmt='psql'))
        sell_list.to_excel(EXCEL_SELL_LIST, index=False)

    def excelfile_initiator(self):
        if not os.path.exists(EXCEL_BUY_LIST):
            # create buy list
            bl = xlsxwriter.Workbook(EXCEL_BUY_LIST)
            blws = bl.add_worksheet()

            blws.write('A1', 'Date')  # Date / Time when the item is added
            blws.write('B1', 'Time')
            blws.write('C1', 'Name')
            blws.write('D1', 'Code')
            blws.write('E1', 'Order_type')  # 시장가 ('mkt') vs 지정가 ('fixed')
            blws.write('F1', 'Tr')  # yet: not, done: done
            blws.write('G1',
                       'Price')  # latest price when the list is populated
            blws.write('H1', 'Amount')
            # blws.write('I1', 'Invested_total') # Before any fee and tax
            # blws.write('J1', 'Date_Trans') # Date / Time when the item is purchased
            # blws.write('K1', 'Time_Trans')
            bl.close()

        if not os.path.exists(EXCEL_SELL_LIST):
            # create sell list
            sl = xlsxwriter.Workbook(EXCEL_SELL_LIST)
            slws = sl.add_worksheet()

            slws.write('A1', 'Date')  # Date / Time when the item is added
            slws.write('B1', 'Time')
            slws.write('C1', 'Name')
            slws.write('D1', 'Code')
            slws.write('E1', 'Order_type')  # 시장가 ('mkt') vs 지정가 ('fixed')
            slws.write('F1', 'Tr')  # yet: not, done: done
            slws.write('G1',
                       'Price')  # latest price when the list is populated
            slws.write('H1', 'Amount')  # Amount to sell
            # slws.write('I1', 'Fee_Tax')
            # slws.write('J1', 'Harvested_total') # After fee and tax
            # slws.write('K1', 'Date_Trans') # Date / Time when the item is purchased
            # slws.write('L1', 'Time_Trans')
            sl.close()

###########################################################################
##### ALGORITHMS
###########################################################################

    def check_speedy_rising_volume(self, code):
        today = datetime.datetime.today().strftime("%Y%m%d")
        df = self.get_ohlcv(code, today)
        volumes = df['volume']

        if len(volumes) < 21:
            return False

        sum_vol20 = 0
        today_vol = 0

        for i, vol in enumerate(volumes):
            if i == 0:
                today_vol = vol
            elif 1 <= i <= 20:
                sum_vol20 += vol
            else:
                break
        avg_vol20 = sum_vol20 / 20

        if today_vol > avg_vol20 * 3:
            return True

        return False

    def algo_speedy_rising_volume(self):
        buy_list_code = []
        for i, code in enumerate(self.kosdaq_codes):
            if self.check_speedy_rising_volume(code):
                buy_list_code.append(code)
        return buy_list_code


###########################################################################
##### EXECUTION
###########################################################################

    def run(self):  # has to return True if the list is updated
        current_time = QTime.currentTime()

        # Timer
        while datetime.datetime.today().weekday() in range(
                0, 5
        ) and current_time > MARKET_START_TIME and current_time < MARKET_FINISH_TIME:
            # Algo
            buy_list_code = []
            buy_list_code.append(random.choice(self.kospi_codes))
            buy_list_code.append(random.choice(self.kospi_codes))
            buy_list_code.append(random.choice(self.kospi_codes))
            buy_list_code.append(random.choice(self.kospi_codes))
            buy_list_code.append(random.choice(self.kospi_codes))

            stock_list_codelist = self.get_stock_list().index.tolist()
            sell_list_code = []
            sell_list_code.append(random.choice(stock_list_codelist))
            sell_list_code.append(random.choice(stock_list_codelist))
            sell_list_code.append(random.choice(stock_list_codelist))
            sell_list_code.append(random.choice(stock_list_codelist))
            sell_list_code.append(random.choice(stock_list_codelist))

            pymon.update_buy_list(buy_list_code)
            pymon.update_sell_list(sell_list_code)

            # Checking
            time.sleep(AUTOTRADE_INTERVAL)
            current_time = QTime.currentTime()
            print(current_time.toString("hh:mm:ss"))
Example #21
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.lineEdit.textChanged.connect(self.code_changed)

        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
Example #22
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # PyTrader 최초 실행 시 주문 여부 False
        self.trade_stocks_done = False
        # PyTrader 프로그램이 실행될 때 키움 로그인이 진행되도록 생성자에서 키움 객체를 생성한 후 comm_connect 메서드를 호출
        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        # 매수매도 종목 파일 읽기
        self.load_buy_sell_list()

        self.lineEdit.textChanged.connect(
            self.code_changed)  # lineEdit 객체에 종목코드를 입력

        accounts_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accounts_num]
        self.comboBox.addItems(accounts_list)  # 계좌를 combobox에 출력
        self.pushButton.clicked.connect(
            self.send_order)  # 현금주문 클릭 시 send_order 실행
        self.pushButton_2.clicked.connect(
            self.check_balance)  # 보유종목 현황 클릭 check_balance 실행

        # Timer1
        self.timer = QTimer(self)
        self.timer.start(1000)  # 1초마다 주기적으로 timeout 시그널 발생
        self.timer.timeout.connect(
            self.timeout)  # timeout 시그널 처리할 슬롯으로 self.timeout 설정

        # Timer2
        # [실시간 조회] 체크박스를 체크하면 10초에 한 번씩 데이터가 자동으로 갱신
        # 다른 TR의 요청이 많은 경우에는 주의(TR 요청 초과 될수도 있으므로)
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):
        # 각 값에 해당하는 정수값으로 변환하여 키움증권 APi에 전달
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        # opw00018 TR은 최대 20개의 보유 종목에 대한 데이터를 리턴
        # 보유 종목이 20개 이상인 경우를 고려해서 반복문을 통해 연속적으로 데이터를 요청
        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001: 예수금 데이터
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        # 예수금 데이터를 QTableWidget에 출력하기 위해 먼저 self.kiwoom.d2_deposit에 저장된 예수금 데이터를 QTableWidgetItem 객체로 만듦
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        # 아이템의 크기에 맞춰 행의 높이를 조절
        self.tableWidget.resizeRowsToContents()

        # Item list
        # 보유 종목별 평가 잔고 데이터를 QTableWidget에 추가
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # 매수/매도 종목 각각에 대한 데이터 개수를 확인한 후 이 두 값을 더한 값을 QTableWidet 객체의 setRowCount 메서드로 설정
        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list(매수 종목)
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())  # 종목코드를 종목명으로 변경

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)

        # sell list(매도 종목)
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContents()  # 행 크기 조절

    def trade_stocks(self):
        """
        trade_stocks(): 각 거래일의 장 시작에 맞춰 정해진 주문 방식에 따라 주문을 수행
        """
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        # 미리 생성된 파일로부터 매수/매도 종목을 읽음
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account: 주문할 때 필요한 계좌 정보를 QComboBox 위젯으로부터 얻어옴
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]  # 호가
            code = split_row_data[1]  # 종목코드
            num = split_row_data[3]  # 수량
            price = split_row_data[4]  # 가격

            # 읽어온 데이터의 주문 수행 여부가 ‘매수전’인 경우에만 해당 주문 데이터를 토대로 send_order 메서드를 통해 매수 주문을 수행
            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

        # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
Example #23
0
class MyWindow(QMainWindow, form_class):
    # QMainWindow: QWidget 상속하는 클래스(위젯 사용할 수 있도록), form_class: pytrader.ui
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()  # Kiwoom 인스턴스 생성
        self.kiwoom.comm_connect()  # 로그인

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

        accouns_num = int(
            self.kiwoom.get_login_info("ACCOUNT_CNT"))  # 보유계좌 갯수 (ex. 2)
        accounts = self.kiwoom.get_login_info(
            "ACCNO")  # 구분자 ';'로 연결된 보유계좌 목록을 반환 (ex. 8165088111;8753740831;)

        accounts_list = accounts.split(';')[0:accouns_num]  # 계좌번호를 리스트로 저장
        self.comboBox.addItems(accounts_list)  # 계좌번호를 comboBox에 넣음

        self.lineEdit.textChanged.connect(self.code_changed)  # 종목코드 입력시
        self.pushButton.clicked.connect(self.send_order)  # [현금주문] 버튼 누를시
        self.pushButton_2.clicked.connect(self.check_balance)  # [조회] 버튼 누를시

    def code_changed(self):
        code = self.lineEdit.text()  # 변경된 종목코드 text 받아서
        name = self.kiwoom.get_master_code_name(code)  # 종목코드에 맞는 종목명을 받아옴
        self.lineEdit_2.setText(name)  # 종목명 보여줌

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()  # 계좌번호
        order_type = self.comboBox_2.currentText()  # 신규매수/신규매도/매수취소/매도취소
        code = self.lineEdit.text()  # 종목코드
        hoga = self.comboBox_3.currentText()  # 지정가/시장가
        num = self.spinBox.value()  # 수량
        price = self.spinBox_2.value()  # 가격

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def timeout(self):  # 화면 왼쪽 아래에 서버 연결 여부와 현재시간 출력
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):  # 실시간 계좌정보 조회 여부
        if self.checkBox.isChecked():
            self.check_balance()

    def check_balance(self):  # 계좌정보 조회
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
Example #24
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        #텔레그램봇
        my_token = '692301814:AAEfmddhyZPcO0Uzh8r5ZehfooTPOvKOOqc'
        self.mybot = telegram.Bot(token=my_token)
        self.chat_id = 544924927

        self.kiwoom = Kiwoom()  #키움인스턴스 생성
        self.kiwoom.comm_connect()  #API로그인

        self.ts_1_p = 'False'  #거래전략1 초기값

        # Timer1
        self.timer = QTimer(self)
        self.timer.start(1000)  #1초
        self.timer.timeout.connect(self.timeout)

        # Timer2
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)  #10초
        self.timer2.timeout.connect(self.timeout2)

        # Timer3
        self.timer3 = QTimer(self)
        self.timer3.start(1000 * 30)  #30초
        self.timer3.timeout.connect(self.timeout3)

        # Timer4
        self.timer4 = QTimer(self)
        self.timer4.start(1000 * 33)  # 33초
        self.timer4.timeout.connect(self.timeout4)

        # Timer5
        self.timer5 = QTimer(self)
        self.timer5.start(1000 * 35)  # 35초
        self.timer5.timeout.connect(self.timeout5)

        # Timer6
        self.timer6 = QTimer(self)
        self.timer6.start(1000 * 37)  # 37초
        self.timer6.timeout.connect(self.timeout6)

        # Timer10
        self.timer4 = QTimer(self)
        self.timer4.start(1000 * 3600)  #1시간 후 프로그램종료!
        self.timer4.timeout.connect(self.quit_app)
        self.timer4.timeout.connect(QCoreApplication.instance().quit)

        self.list700 = []
        self.list600700 = []

        self.lineEdit.textChanged.connect(self.code_changed)  #종목코드 입력시
        self.pushButton.clicked.connect(self.send_order)  #현금주문 버튼 클릭시
        self.pushButton_2.clicked.connect(self.check_balance)  #계좌정보 조회
        self.pushButton_3.clicked.connect(self.trading_strategy_1)  #거래전략1호
        self.pushButton_4.clicked.connect(self.quit_app)  #앱종료
        self.pushButton_4.clicked.connect(
            QCoreApplication.instance().quit)  # 앱종료
        #계좌정보
        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.load_buy_sell_list()

        #로그기록
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 시작되었습니다.")
        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               "ㅣ 프로그램이 시작되었습니다.")

    #종료
    def quit_app(self):
        self.timer = ''
        self.timer2 = ''
        self.timer3 = ''
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 종료되었습니다.")
        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               "ㅣ 프로그램이 종료되었습니다.")
        time.sleep(3)

    #상태표시줄(현재시간, 서버연결상태)
    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()
        if state == 1:
            state_msg = "서버 연결되었습니다."
        else:
            state_msg = "서버가 연결되지 않았습니다."

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()  #계좌정보 실시간 조회

    def timeout3(self):
        if self.ts_1_p == 'True':  #거래전략1 진행시 30초마다 조회
            self.volume_check()

    def timeout4(self):
        self.sell_stocks()

    def timeout5(self):
        self.load_buy_sell_list()

    def timeout6(self):
        self.trade_stocks()

    #로그파일 > txt파일로 저장
    def txt_changed(self):
        f = open('log.txt', 'a')
        log_text = self.textEdit.text
        f.write(log_text)
        f.close()

    #종목명 나타내기
    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    #현금주문
    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    #계좌정보
    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        #account_number = self.kiwoom.get_login_info("ACCNO")
        #account_number = account_number.split(';')[0]
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
        print('잔고조회완료')

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        ff = open("sell_list.txt", 'rt')
        sell_list = ff.readlines()
        ff.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)
        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContents()
        print('buy & sell.txt 불러오기')

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") + 'ㅣ ' +
                    code + ' ' + num + '주 ' + price + "원 매수주문")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") + 'ㅣ ' +
                    code + ' ' + num + '주 ' + price + "원 매도주문")

                # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "매수주문완료")

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "매도주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
        print('거래알고리즘실행완료')

    #거래량급증 거래전략1
    def trading_strategy_1(self):

        if self.ts_1_p == 'False':
            print('ts_1_p = true')
            self.ts_1_p = 'True'
            self.label_7.setText("진행중...")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 전략1호 시작되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 전략1호 시작되었습니다.")
            self.volume_check()

        elif self.ts_1_p == 'True':
            print('ts_1_p = False')
            self.label_7.setText("")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 전략1호 중지되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 전략1호 중지되었습니다.")
            self.ts_1_p = 'False'

    #거래량급증 조회
    def volume_check(self):
        print('거래량급등조회시작')
        self.kiwoom.reset_opt10023_output()

        self.kiwoom.set_input_value("시장구분", 000)
        self.kiwoom.set_input_value("시간구분", 2)
        self.kiwoom.set_input_value("정렬구분", 2)
        self.kiwoom.set_input_value("거래량구분", 5)
        self.kiwoom.set_input_value("시간", "")
        self.kiwoom.set_input_value("종목조건", 0)
        self.kiwoom.set_input_value("가격구분", 0)
        self.kiwoom.comm_rq_data("opt10023_req", "opt10023", 0, "0168")

        while self.kiwoom.remained_data == True:
            time.sleep(TR_REQ_TIME_INTERVAL)
            self.kiwoom.set_input_value("시장구분", 000)
            self.kiwoom.set_input_value("시간구분", 2)
            self.kiwoom.set_input_value("정렬구분", 2)
            self.kiwoom.set_input_value("거래량구분", 5)
            self.kiwoom.set_input_value("시간", "")
            self.kiwoom.set_input_value("종목조건", 0)
            self.kiwoom.set_input_value("가격구분", 0)
            self.kiwoom.comm_rq_data("opt10023_req", "opt10023", 2, "0168")

        df = DataFrame(self.kiwoom.opt10023_output)  #거래급증종목 데이터프레임으로 받음
        print(df)
        df700 = df[[a > 700 for a in df.volume]]  #700이상 종목
        self.list700 = list(df700['code'])
        #print('700이상: ' + self.list700)
        aa = set(self.list700)
        bb = set(self.list600700)
        buy_set = aa & bb
        buy_set = list(buy_set)
        df600 = df[[a > 600 for a in df.volume]]
        df600700 = df600[[a < 700 for a in df600.volume]]

        self.list600700 = []
        self.list600700 = list(df600700['code'])
        #print('600이상700미만: ' + self.list600700)

        #buy_list 업데이트
        if len(buy_set) == 0:
            pass
        else:
            #print('buy_list: ' + buy_set)
            account_number = self.comboBox.currentText()
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
            buy_q = int(self.kiwoom.d2_deposit[:-3].replace(',', ''))
            buy_q = (buy_q // len(buy_set)) // 5

            f = open("buy_list.txt", "a")
            for code in buy_set:
                time.sleep(0.2)
                self.kiwoom.set_input_value("종목코드", code)
                self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "0101")
                self.mybot.sendMessage(self.chat_id,
                                       text="매수선정종목: " +
                                       self.kiwoom.stock_name)
                f.write("매수;%s;시장가;%d;0;매수전\n" %
                        (code, buy_q // self.kiwoom.stock_pv))
                print('buy_list.txt updated')
            f.close()

        self.list700 = []
        print("거래량급증조회완료")

    #목표수익률 도달시 팔기
    def sell_stocks(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        print('보유종목현황: ' + self.kiwoom.opw00018_output['multi'])
        list_1 = list(self.kiwoom.opw00018_output['multi'])
        a = len(list_1)
        f = open('sell_list.txt', 'a')
        for i in range(a):
            if float(list_1[i][5]) > 5:
                f.write("매도;%s;시장가;%s;0;매도전\n" % (list_1[i][6], list_1[i][1]))
            elif float(list_1[i][5]) < -2:
                f.write("매도;%s;시장가;%s;0;매도전\n" % (list_1[i][6], list_1[i][1]))
        f.close()
Example #25
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False
        self.bucket = list()
        self.item_list = list()
        self.code_list = list()

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

        accounts_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")

        accounts_list = accounts.split(';')[0:accounts_num]
        self.comboBox.addItems(accounts_list)
        self.comboBox_2.addItems(accounts_list)

        self.codeLineEdit.textChanged.connect(self.code_changed)
        self.codeLineEdit_2.textChanged.connect(self.code_changed_2)
        self.viewButton.clicked.connect(self.check_balance)
        self.resetButton.clicked.connect(self.reset_bucket)
        self.addButton.clicked.connect(self.add_to_bucket)
        self.showButton.clicked.connect(self.show_bucket)
        self.downButton.clicked.connect(self.download_data)
        self.optButton.clicked.connect(self.optimize_weights)
        self.sendButton.clicked.connect(self.send_initial_order)
        self.spinBox.valueChanged.connect(self.asset_num)

        self.LogDisplay = LogDisplay(self)

    def send_order(self):
        order_type_lookup = {
            'Buying': 1,
            'Selling': 2,
            'Cancel Buying': 3,
            'Cancel Selling': 4
        }
        hoga_lookup = {'Limit': "00", 'Market': "03"}

        account = self.comboBox_2.currentText()
        order_type = self.comboBox_3.currentText()
        code2 = self.codeLineEdit_2.text()
        hoga = self.comboBox_4.currentText()
        num = self.spinBox_2.value()
        price = self.spinBox_3.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code2, num,
                               price, hoga_lookup[hoga], "")

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)
        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    # my portfolio
    def code_changed(self):
        code = self.codeLineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.nameLineEdit.setText(name)

    # manual order
    def code_changed_2(self):
        code2 = self.codeLineEdit_2.text()
        name = self.kiwoom.get_master_code_name(code2)
        self.nameLineEdit_2.setText(name)

    def asset_num(self):
        self.num = self.spinBox.value()

    def reset_bucket(self):
        self.bucket = list()
        self.item_list = list()
        self.code_list = list()

    def add_to_bucket(self):
        code = self.codeLineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.nameLineEdit.setText(name)
        self.bucket.append([code, name])

    def show_bucket(self):
        item_count = len(self.bucket)
        print(self.num)
        if self.num != item_count:
            QMessageBox.about(
                self, "Warning!",
                "Item # is different from the number of assets added to your bucket!"
            )
            return

        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]
        self.kiwoom.set_input_value("계좌번호", account_number)

        # Item list
        self.bucketTable.setRowCount(item_count)

        for j in range(item_count):
            row = self.bucket[j]
            self.code_list.append(row[0])
            self.item_list.append(row[1])
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                self.bucketTable.setItem(j, i, item)
        self.bucketTable.resizeRowsToContents()

    def download_data(self):
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]
        self.kiwoom.set_input_value("계좌번호", account_number)
        for code in self.code_list:
            self.kiwoom.get_ohlcv(code)
        QMessageBox.about(self, "Notification", "Download Completed")

    def optimize_weights(self):
        self.po = PortfolioOptimizer(self.code_list)
        QMessageBox.about(self, "Notification", "Calculation Completed")

    def send_initial_order(self):
        df = self.po.init_buy_list.reset_index()
        print("****** Proceeding my initial order ******")
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]
        self.kiwoom.set_input_value("계좌번호", account_number)
        for i in range(len(df)):
            print(
                "{name}({code}) buy {quantity}".format(name=df.iloc[i][1],
                                                       code=df.iloc[i][0],
                                                       quantity=df.iloc[i][5]))
            self.kiwoom.send_order('order_req', '0101', account_number, 1,
                                   df.iloc[i][0], df.iloc[i][5], 0, '03', '')
        print("succeeded")
        QMessageBox.about(self, "Notification", "Order Completed")

    def display_log(self):
        self.LogDisplay()
Example #26
0
class StockT(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()  #키움 로그인

        self.trade_stocks_done = False  #자동 주문

        self.timer = QTimer(self)
        self.timer.start(1000)  #1초에 한 번씩 주기적으로 timeout 시그널이 발생
        self.timer.timeout.connect(
            self.timeout)  #timeout 시그널이 발생할 때 이를 처리할 슬롯으로 self.timeout을 설정
        #StatusBar 위젯에 서버 연결 상태 및 현재 시간을 출력

        self.lineEdit.textChanged.connect(
            self.code_changed)  #lineEdit 객체가 변경될 때 호출되는 슬롯을 지정
        self.pushButton.clicked.connect(self.send_order)  #현금주문

        accouns_num = int(self.kiwoom.get_login_info(
            "ACCOUNT_CNT"))  #계좌 정보를 QComboBox 위젯에 출력하는 코드
        accounts = self.kiwoom.get_login_info("ACCNO")  #로그인 정보 가져오기
        accounts_list = accounts.split(';')[
            0:accouns_num]  #계좌가 여러 개인 경우 각 계좌는';'를 통해 구분

        self.comboBox.addItems(accounts_list)

        self.pushButton_2.clicked.connect(
            self.check_balance)  #시그널과 슬롯을 연결하는 코드

        self.load_buy_sell_list()  #선정 종목 리스트 출력

    def timeout(self):
        # 현재 시간이 09시 00분 00초를 지났고 매수/매도 주문을 수행하지 않았을 때 trade_stocks 메서드 호출
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        # 장이 시작할 때 매수/매도 주문을 넣으려면 timeout 메서드에서 시간 체크
        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")  #시간:분:초
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()  #서버 연결 상태 확인
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def code_changed(
            self):  #사용자가 ineEdit에 종목코드를 입력하면 종목코드를 읽은 후 API를 사용해 종목명 알아내기
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def send_order(self):  #pushButton 객체가 클릭될 때 호출되는 send_order 메서드
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def check_balance(self):  #'조회' 버튼이 클릭됐을 때 '잔고 및 보유종목현황' 데이터 호출하도록
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)  #입력 데이터 설정
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")  #TR 요청

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        # 예수금 데이터를 얻기 위해 opw00001 TR을 요청
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)  #칼럼의 위치로 (0, 0)

        for i in range(1, 6):  #리스트로 저장되어 있기에 반복문으로 가져오기
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()  #아이템의 크기에 맞춰 행의 높이를 조절

        # Item list
        # 보유 종목별 평가 잔고 데이터를 QTableWidget에 추가
        # 행의 개수를 따로 설정하지 않았기에, 먼저 보유종목의 개수를 확인한 후 행의 개수를 설정해야 함
        # (열의 개수는 Qt Designer가 자동으로 설정)
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):  #아이템 추가
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()  #행의 크기를 조절

        # Timer2
        # [실시간 조회] 체크박스를 체크하면 데이터가 자동으로 갱신
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)  #10초에 한 번
        self.timer2.timeout.connect(self.timeout2)

    def timeout2(self):  # QCheckBox가 체크됐는지 확인한 후 체크돼 있을 때 데이터를 갱신
        if self.checkBox.isChecked():
            self.check_balance()

    # buy_list.txt와 sell_list.txt 파일을 열고 파일로부터 데이터를 읽는 코드
    # 아직 알고리즘을 안만들었기에
    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        #데이터의 총 개수 확인
        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        # buy list 매수 종목
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell list 매도 종목
        for j in range(len(sell_list)):  #j : 행(row)에 대한 인덱스 값
            row_data = sell_list[j]
            split_row_data = row_data.split(';')  #문자열을 ;로 분리
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())  #종목코드로부터 종목명 구하기

            for i in range(len(split_row_data)):  #i : 열(column)에 대한 인덱스 값
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()  #행의 크기 조절

    # 장이 시작하면 미리 선정된 종목에 대해 자동으로 주문하는 기능 구현
    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()  #미리 생성된 파일로부터 매수/매도 종목을 읽는 코드

        # account
        # 주문할 때 필요한 계좌 정보
        account = self.comboBox.currentText()

        # buy list 매수 주문
        # 데이터를 하나씩 얻어온 후 문자열을 분리해서 주문에 필요한 정보 준비
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            # 읽어온 데이터의 주문 수행 여부가 ‘매수전’인 경우에만 해당 주문 데이터를 토대로 send_order 메서드를 통해 매수 주문 수행
            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")

        # sell list 매도 주문
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

        # buy list
        # 저장된 주문 여부를 업데이트
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "주문완료")  #바꾸기

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
Example #27
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False  # 자동 trading False이면 작동

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()
        # 전략
        self.stratagy = SysStratagy()

        # Timer1
        self.timer = QTimer(self)
        self.timer.start(1000 * 5)

        # Timer2
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)

        # Timer3
        self.timer3 = QTimer(self)
        self.timer3.start(1000 * 10)

        # Timer4 손절처리를 위한 Timer 설정
        self.timer4 = QTimer(self)
        self.timer4.start(1000 * 60)

        # Naver에서 현재가 가져오기
        self.timer_naver = QTimer(self)
        self.timer_naver.start(1000 * 4)

        # Naver에서 현재가 가져오기
        self.timer_rate = QTimer(self)
        self.timer_rate.start(1000 * 3)

        # 계좌정보 넣어줌
        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        # 보유 종목정보
        self.boyou_stock_list = []
        self.check_balance()
        self.init_boyou_stock_list = self.kiwoom.opw00018_output['multi']
        self.boyou_stock_list = self.init_boyou_stock_list
        # self.boyou_stock_list.append(['삼성전자', '100', '40000', '42000', '200000', '5', '005930'])
        # 아침에 보유주식 매도기능 주석처리함.. 보유주식 정보에서 처리하면 되므로 2019.05.19
        # 보유 주식 매도 주문 아침9시전에 구동시에 보유주식에 대한 매도주문처리
        # self.init_boyou_mado()

        # 매도/매수 리스트 조회
        self.load_buy_sell_list()

        # 보유주식정보 json으로 저장
        self.boyoustock = BoyouStock()
        self.boyou_stock_save_json()

        # 이벤트 정보 연결
        self.timer.timeout.connect(self.timeout)
        self.timer2.timeout.connect(self.timeout2)
        self.timer3.timeout.connect(self.timeout3)
        self.timer4.timeout.connect(
            self.timeout4)  # stop loss 처리 # 보유주식정보 가져오는 것으로 수정함.2019.05.19
        self.timer_naver.timeout.connect(self.timeout_naver)
        self.timer_rate.timeout.connect(self.timeout_rate)
        self.lineEdit.textChanged.connect(self.code_changed)
        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(
            self.check_balance_Widget
        )  # pushButton_2 라는 객체가 클릭될 때 check_balance라는 메서드가 호출

        # 손절,익절률 설정 값 읽어오기
        config = self.boyoustock.readConfig()
        if len(config) > 0:
            self.stop_profit_rate = (config["stop_profit_rate"] / 100) + 1
            self.stop_loss_rate = 1 - (config["stop_loss_rate"] / 100)
            self.spinBox_6.setValue(config["stop_profit_rate"])
            self.spinBox_7.setValue(config["stop_loss_rate"])
        else:
            self.stop_profit_rate = (self.spinBox_6.value() / 100) + 1
            self.stop_loss_rate = 1 - (self.spinBox_7.value() / 100)
        print("초기 설정 익절률: " + str(self.stop_profit_rate))
        print("초기 설정 손절률: " + str(self.stop_loss_rate))

    def init_boyou_mado(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        # self.init_maedo_proc()

        if current_time < market_start_time:
            # 보유종목 매도 처리..
            self.init_maedo_proc()
        else:
            print("보유주식에 대한 매도주문은 9시전에만 가능함.")

    def timeout(self):
        # market_start_time = QTime(8, 0, 0)
        # market_end_time = QTime(19, 0, 0)
        current_time = QTime.currentTime()

        if self.stratagy.isTimeAvalable(self.kiwoom.maesu_start_time,
                                        self.kiwoom.maesu_end_time
                                        ) and self.trade_stocks_done is False:
            self.trade_stocks()
            # self.trade_stocks_done = True
        else:
            print("지금은 거래 가능한 시간이 아닙니다.")
            self.kiwoom.comm_terminate()
            sys.exit(1)

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance_Widget()

    def timeout3(self):
        if self.checkBox_2.isChecked():
            self.load_buy_sell_list()

    def timeout4(self):
        self.boyoustock.readBoyouStockInfo()
        # if self.checkBox_3.isChecked():  # 일단주석처리.
        #     self.stock_stop_loss()

    def timeout_naver(self):
        self.cur_stock_price_naver()

    def timeout_rate(self):
        config = {}
        profit = (self.spinBox_6.value() / 100) + 1
        loss = 1 - (self.spinBox_7.value() / 100)
        if self.stop_profit_rate != profit:
            self.stop_profit_rate = profit
            self.spinBox_6.setValue(self.spinBox_6.value())
            config["stop_profit_rate"] = self.spinBox_6.value()
            config["stop_loss_rate"] = self.spinBox_7.value()
            self.boyoustock.updateConfig(config)
            print("익절률이 변경되었습니다. TO " + str(profit))
        if self.stop_loss_rate != loss:
            self.stop_loss_rate = loss
            self.spinBox_7.setValue(self.spinBox_7.value())
            config["stop_profit_rate"] = self.spinBox_6.value()
            config["stop_loss_rate"] = self.spinBox_7.value()
            self.boyoustock.updateConfig(config)
            print("손절률이 변경되었습니다. TO " + str(loss))

    def boyou_stock_save_json(self):
        if len(self.init_boyou_stock_list) > 0:
            init_stock_list = []
            self.boyoustock.updateBoyouStockInfo(init_stock_list)
            for key in range(len(self.init_boyou_stock_list)):
                row = self.boyou_stock_list[key]
                boyou_cnt = int(row[1].replace(',', ''))
                maeip_price = int(row[2].replace(',', ''))
                # cur_price = int(row[3].replace(',', ''))
                stock_code = row[6]
                stock_name = row[0]
                mado_price = self.stratagy.get_maedo_price(
                    maeip_price, self.stop_loss_rate)  # 5% 손절가처리
                sell_price = self.stratagy.get_maedo_price(
                    maeip_price, self.stop_profit_rate)  # 목표가 처리
                self.boyoustock.stock_buy([
                    stock_code, stock_name, maeip_price, boyou_cnt, sell_price,
                    mado_price
                ])
        else:
            init_stock_list = []
            self.boyoustock.updateBoyouStockInfo(init_stock_list)

    def cur_stock_price_naver(self):
        # self.chg_boyou_stock_list = self.kiwoom.opw00018_output['multi']
        # # 초기에 보유주식과 매수/매도가 발생시 보유 주식이 다를 수 있으므로
        # # 이렇게 처리함..
        # logger.debug("== cur_stock_price_naver ==")
        # logger.debug((self.init_boyou_stock_list, self.chg_boyou_stock_list))
        # if util.list_diff(self.init_boyou_stock_list, self.chg_boyou_stock_list):
        #     self.boyou_stock_list = self.chg_boyou_stock_list
        self.boyou_stock_list = self.boyoustock.readBoyouStockInfo()
        for key in range(len(self.boyou_stock_list)):
            bstock = self.boyou_stock_list[key]
            stock_cd = bstock[0]  # 주식코드
            stock_nm = bstock[1]  # 주식명
            maeip_price = bstock[2]  # 매입단가
            maeip_qtr = bstock[3]  # 매입수
            stop_price = self.stratagy.get_maedo_price(
                maeip_price, self.stop_loss_rate)  # -5% 손절가
            dest_price = self.stratagy.get_maedo_price(
                maeip_price, self.stop_profit_rate)  # 목표가 도달시
            cur_price = util.get_naver_cur_stock_price(
                stock_cd)  # 네이버에서 가져온 현재가
            logger.debug(util.cur_date_time() + '보유주식명:' + stock_nm +
                         ',주식코드:' + stock_cd + ',현재가:' + str(cur_price) +
                         ',예상 손절가:' + str(stop_price))
            if cur_price <= stop_price:
                logger.debug(util.cur_date_time() + '손절 프로세스 진행 ===> 보유주식명:' +
                             stock_nm + ',주식코드:' + stock_cd + ',현재가:' +
                             str(cur_price) + ',예상 손절가:' + str(stop_price))
                # self.stock_stop_loss(stock_cd, maeip_qtr, stop_price)
                self.add_init_stock_sell_info(stock_cd, dest_price, maeip_qtr,
                                              'S')
            elif cur_price >= dest_price:
                logger.debug(util.cur_date_time() +
                             '이익 매도 프로세스 진행 ===> 보유주식명:' + stock_nm +
                             ',주식코드:' + stock_cd + ',현재가:' + str(cur_price) +
                             ',예상 손절가:' + str(stop_price))
                self.add_init_stock_sell_info(stock_cd, dest_price, maeip_qtr,
                                              'I')

    # 이익을 위한 매도주문(즉시 매도처리 이므로)을 취소하고 손실을 중지하기 위한 주문처리를 함.
    def stock_stop_loss(self, t_stock_code, num, price):
        is_existed_stock = False
        self.check_balance()
        item_count = len(self.kiwoom.opw00018_output['multi'])
        logger.debug("itemCount ==> " + str(item_count))
        if item_count == 0:
            logger.debug("보유종목이 없습니다.")

        # 한 종목에 대한 종목명, 보유량, 매입가, 현재가, 평가손익, 수익률(%)은 출력
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            stock_code = row[6]
            if t_stock_code == stock_code:
                is_existed_stock = True

        if is_existed_stock:
            order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
            hoga_lookup = {'지정가': "00", '시장가': "03"}

            account = self.comboBox.currentText()

            self.kiwoom.send_order("send_order_req", "0101", account,
                                   order_type_lookup['신규매도'], t_stock_code,
                                   num, price, hoga_lookup['시장가'], "")
        else:
            print("이미 매도 되었거나 매수되지 않은 주식입니다.")

        # logger.debug("=== stock_stop_loss ===")
        # logger.debug("손실에 대한 loss 처리 설정했습니다.")
        # self.check_balance()
        # # Item list
        # item_count = len(self.kiwoom.opw00018_output['multi'])
        # logger.debug("itemCount ==> " + str(item_count))
        # if item_count == 0:
        #     logger.debug("보유종목이 없습니다.")
        #
        # # 한 종목에 대한 종목명, 보유량, 매입가, 현재가, 평가손익, 수익률(%)은 출력
        # for j in range(item_count):
        #     row = self.kiwoom.opw00018_output['multi'][j]
        #     boyou_cnt = int(row[1].replace(',', ''))
        #     maeip_price = int(row[2].replace(',', ''))
        #     cur_price = int(row[3].replace(',', ''))
        #     stock_code = row[6]
        #     logger.debug(util.cur_date_time() + "현재보유주식코드=>" + stock_code + ",손절주식코드=>" + t_stock_code)
        #     if stock_code == t_stock_code:
        #         # 보유종목의 이익매도 주문이 있는 경우 이익매도주문 취소후 익절처리
        #         self.check_michegyoel_joomoon(stock_code)
        #         row2 = self.kiwoom.opw00007_output[j]
        #         if len(row2) > 0:
        #             if row2[5] != '':
        #                 orgJoomoonNo = int(row2[5])  # 원주문번호 정보를 가져온다.
        #                 self._file_line_delete(self.kiwoom.sell_loc, stock_code)  # stor파일에 해당 종목을 삭제한다.
        #             else:
        #                 orgJoomoonNo = ''
        #         else:
        #             orgJoomoonNo = ""
        # logger.debug(util.cur_date_time() + ":보유주식수/ 매입가/주식코드/원주문번호: %s %s %s %s" % (boyou_cnt, maeip_price, stock_code, orgJoomoonNo))

        # if orgJoomoonNo != "":
        #     self.kiwoom.add_stock_sell_info_loss(stock_code, 0, boyou_cnt, orgJoomoonNo)
        # else:
        #     self.add_init_stock_sell_info(stock_code, 0, boyou_cnt, 'S')

        # print("종목코드 :", stock_code, " 원주문번호 : ", orgJoomoonNo)
        # logger.debug(util.cur_date_time() + ":보유주식수/ 매입가/주식코드/원주문번호: %s %s %s %s" % (
        # boyou_cnt, maeip_price, stock_code, orgJoomoonNo))
        # mado_price = self.stratagy.get_maedo_price(maeip_price, 0.95)  # 4% 익절가처리
        # 해당주식의 (이익을 얻기 위한)매도 주문 취소 처리
        # 아침에 자동 매도주문 처리가 됐을것이고 그것에 대해 취소처리를 하는 것..
        # if not self._item_stock_exist(stock_code):
        # logger.debug(util.cur_date_time() + " : 현재가 / 손절가: %s %s " % (cur_price, mado_price))
        # 일단 주석처리 2019.05.02
        # if cur_price < mado_price: # 익절가보다 작으면 매도처리
        #     if orgJoomoonNo != "":
        #         self.kiwoom.add_stock_sell_info_loss(stock_code, mado_price, boyou_cnt, orgJoomoonNo)
        #     else:
        #         self.add_init_stock_sell_info(stock_code, mado_price, boyou_cnt, 'S')

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    def get_boyou_cnt(self):
        self.check_balance()
        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        if item_count == 0:
            print("보유종목이 없습니다.")
        return item_count

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]  # 첫번째 계좌번호 호출

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

    def check_michegyoel_joomoon(self, code):
        self.kiwoom.reset_opw00007_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]  # 첫번째 계좌번호 호출
        joomoondate = util.cur_date('%y%m%d')
        self.kiwoom.set_input_value("주문일자", joomoondate)
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.set_input_value("비밀번호", "3051")
        self.kiwoom.set_input_value("비밀번호매체구분", "00")
        self.kiwoom.set_input_value("조회구분", "3")
        self.kiwoom.set_input_value("주식채권구분", "1")
        self.kiwoom.set_input_value("매도매수구분", "1")
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.set_input_value("시작주문번호", "")
        self.kiwoom.comm_rq_data("opw00007_req", "opw00007", 0, "2000")

    def check_balance_Widget(self):
        self.check_balance()
        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        # 총매입, 총평가, 총손익, 총수익률(%), 추정자산을 QTableWidget의 칼럼에 추가하는 코드.
        # 데이터는 self.kiwoom.opw00018_output['single']을 통해 얻어올 수 있음.
        for i in range(1, 6):
            print('Debug', self.kiwoom.opw00018_output['single'][i - 1])
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        # resizeRowsToContents 메서드를 호출해서 아이템의 크기에 맞춰 행의 높이를 조절
        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        # 한 종목에 대한 종목명, 보유량, 매입가, 현재가, 평가손익, 수익률(%)은 출력
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        # resizeRowsToContents 메서드를 호출해서 아이템의 크기에 맞춰 행의 높이를 조절
        self.tableWidget.resizeRowsToContents()

    def load_buy_sell_list(self):
        f = open(self.kiwoom.buy_loc, 'rt', encoding='UTF-8')
        buy_list = f.readlines()
        f.close()

        f = open(self.kiwoom.sell_loc, 'rt', encoding='UTF-8')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_3.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_3.setItem(len(buy_list) + j, i, item)

        self.tableWidget_3.resizeRowsToContents()

    # 프로그램 시작시, 보유종목에 대한 매도처리
    def init_maedo_proc(self):
        self.check_balance()
        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        if item_count == 0:
            print("보유종목이 없습니다. [", item_count, "]")
            pass
        # 한 종목에 대한 종목명, 보유량, 매입가, 현재가, 평가손익, 수익률(%)은 출력
        stratagy = SysStratagy()
        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            boyou_cnt = int(row[1].replace(',', ''))
            maeip_price = int(row[2].replace(',', ''))
            stock_code = row[6]
            mado_price = stratagy.get_maedo_price(maeip_price,
                                                  self.stop_profit_rate)
            self.add_init_stock_sell_info(stock_code, mado_price, boyou_cnt,
                                          'I')

    # 매도 Stor에 매도 종목 추가
    def add_init_stock_sell_info(self, code, sell_price, sell_qty, status):
        dm = ';'
        b_gubun = "매도"
        b_status = "매도전"
        b_price = sell_price
        if status == 'I':
            b_method = "지정가"
        else:
            b_method = "시장가"
        b_qty = sell_qty
        included = False
        code_info = self.kiwoom.get_master_code_name(code)
        mste_info = self.kiwoom.get_master_construction(code)
        stock_state = self.kiwoom.get_master_stock_state(code)
        print(code_info, mste_info, stock_state)

        f = open(self.kiwoom.sell_loc, 'rt', encoding='UTF-8')
        sell_list = f.readlines()
        f.close()

        if self.stratagy.isTimeAvalable(self.kiwoom.maesu_start_time,
                                        self.kiwoom.maesu_end_time):
            if len(sell_list) > 0:
                write_mode = 'a'  # 추가
            else:
                write_mode = 'wt'
            for stock in sell_list:
                if code in stock:
                    included = True
                else:
                    included = False
            if not included:
                f = open(self.kiwoom.sell_loc, write_mode, encoding='UTF-8')
                stock_info = b_gubun + dm + code + dm + b_method + dm + str(
                    b_qty) + dm + str(b_price) + dm + b_status + dm
                f.write(stock_info + '\n')
                f.close()
        else:
            f = open(self.kiwoom.sell_loc, 'wt', encoding='UTF-8')
            stock_info = b_gubun + dm + code + dm + b_method + dm + str(
                b_qty) + dm + str(b_price) + dm + b_status + dm
            f.write(stock_info + '\n')
            f.close()

    # buy_list는 애초에 모니터링시 기본정보 목록에서 추출
    # 매매전략에 해당하는 종목을 buy_list_txt에 저장
    def trade_buy_stratagic(self, code):
        stockInfo = {}
        stockInfo = self.get_current_info(code)
        if stockInfo is not None and len(stockInfo) > 0:
            print('종목정보 : ', stockInfo)
            name = self.kiwoom.get_master_code_name(code)
            cur_price = stockInfo.get('현재가')
            open_price = stockInfo.get('시가')
            print('현재가 :', cur_price, ' 시가:', open_price)
            if open_price == '' or cur_price == '':
                return False
            else:
                if cur_price[0] == '-' or cur_price[0] == '+':
                    cur_price = cur_price[1:]
                if open_price[0] == '-' or open_price[0] == '+':
                    open_price = open_price[1:]
                result = self.stratagy.isBuyStockAvailable(
                    code, name, cur_price, open_price, s_year_date)
        else:
            self.kiwoom.set_input_value("종목코드", code)
            self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "2000")
            name = self.kiwoom.get_master_code_name(code)
            # cur_price = self.kiwoom.jangoInfo[code]['현재가']
            # if cur_price[0] == '-' or cur_price[0] == '+':
            #     cur_price = cur_price[1:]
            # open_price = self.kiwoom.jangoInfo[code]['시가']
            # if cur_price[0] == '-' or cur_price[0] == '+':
            #     open_price = open_price[1:]
            # print(name, ",현재가 : ", self.kiwoom.cur_price)
            result = self.stratagy.isBuyStockAvailable(code, name,
                                                       self.kiwoom.cur_price,
                                                       self.kiwoom.open_price,
                                                       s_year_date)

        # 주식 정상상태 로직 추가 2019.04.20 start
        mste_info = self.kiwoom.get_master_construction(code)
        if mste_info == '정상' and result is True:
            result = True
        else:
            result = False
        # End

        return result
        # return True

    def _file_update(self, fileName, code, pre_status, chg_status):
        stock_list = []
        f = open(fileName, 'rt', encoding='UTF-8')
        stock_list = f.readlines()
        f.close()

        for i, row_data in enumerate(stock_list):
            if code in stock_list[i]:
                stock_list[i] = stock_list[i].replace(pre_status, chg_status)

        # file update
        f = open(fileName, 'wt', encoding='UTF-8')
        for row_data in stock_list:
            f.write(row_data)
        f.close()

    def _file_line_delete(self, fileName, code):
        stock_list = []
        f = open(fileName, 'rt', encoding='UTF-8')
        stock_list = f.readlines()
        f.close()

        for i, row_data in enumerate(stock_list):
            if code in stock_list[i]:
                stock_list[i + 1].remove()

        # file update
        f = open(fileName, 'wt', encoding='UTF-8')
        for row_data in stock_list:
            f.write(row_data)
        f.close()

    def _item_stock_exist(self, fileName, code):
        stock_list = []
        f = open(fileName, 'rt', encoding='UTF-8')
        stock_list = f.readlines()
        f.close()
        b_exist = False
        for i, row_data in enumerate(stock_list):
            if code in stock_list[i]:
                b_exist = True

        return b_exist

    def get_current_info(self, code):
        return self.kiwoom.jongmokInfo.get(code)

    def get_current_info_tr(self, code):
        self.kiwoom.set_input_value("종목코드", code)
        self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "2000")

    def trade_stocks(self):
        if self.stratagy.isTimeAvalable(self.kiwoom.maesu_start_time,
                                        self.kiwoom.maesu_end_time):
            logger.debug("trade_stocks_1")
            hoga_lookup = {'지정가': "00", '시장가': "03"}
            f = open(self.kiwoom.buy_loc, 'rt', encoding='UTF-8')
            buy_list = f.readlines()
            logger.debug("trade_stocks_2")
            f.close()
            code = ''
            for stock in buy_list:
                code = code + stock.split(";")[1] + ";"

            if code != '':
                fidList = str(jk_util.name_fid["현재가"]) + ";" + str(
                    jk_util.name_fid["종목명"]) + ";" + str(
                        jk_util.name_fid["종목코드"])
                self.kiwoom.setRealReg("0101", code[:-1], fidList, "0")
            logger.debug("trade_stocks_3")
            f = open(self.kiwoom.sell_loc, 'rt', encoding='UTF-8')
            sell_list = f.readlines()
            f.close()

            account = self.comboBox.currentText()
            logger.debug("trade_stocks_4")
            if len(buy_list) == 0:
                print("매수 대상 종목이 존재하지 않습니다.")
            logger.debug("trade_stocks_5")
            # buy list
            for row_data in buy_list:
                split_row_data = row_data.split(';')
                hoga = split_row_data[2]
                code = split_row_data[1]
                num = split_row_data[3]
                price = split_row_data[4]
                if split_row_data[-1].rstrip() == '매수전':
                    logger.debug("trade_stocks_6")
                    if self.trade_buy_stratagic(code):  # * 매수전략 적용 *
                        logger.debug("trade_stocks_7")
                        # 다시 해당 주식의 TR정보를 가져옮.. 상한가 오류로 인하여..
                        self.get_current_info_tr(code)
                        if self.get_boyou_cnt() >= total_boyou_cnt:
                            print("보유 종목이 3개 이상 입니다.")
                        else:
                            buy_num_info = self.stratagy.get_buy_num_price(
                                total_buy_money, self.kiwoom.high_price,
                                self.kiwoom.cur_price)
                            num = buy_num_info[0]
                            price = buy_num_info[1]
                            print("매수수량 : ", num, " 매수상한가 : ", price)
                            logger.debug("trade_stocks_8")
                            self.kiwoom.send_order("send_order_req", "0101",
                                                   account, 1, code, num,
                                                   price, hoga_lookup[hoga],
                                                   "")  # 1: 매수, 2: 매도
                            logger.debug("trade_stocks_9")
                            if self.kiwoom.order_result == 0:
                                self._file_update(self.kiwoom.buy_loc, code,
                                                  '매수전', '주문완료')
                            else:
                                print(self.kiwoom.order_result,
                                      ': 매수 처리 못했습니다.')
                # time.sleep(5)
            logger.debug("trade_stocks_10")
            if len(sell_list) == 0:
                print("매도 대상 종목이 존재하지 않습니다.")
            logger.debug("trade_stocks_11")
            # sell list
            for row_data in sell_list:
                split_row_data = row_data.split(';')
                hoga = split_row_data[2]
                code = split_row_data[1]
                num = split_row_data[3]
                price = split_row_data[4]
                logger.debug("trade_stocks_12")
                if split_row_data[-2].rstrip() == '매도전':
                    logger.debug("trade_stocks_13")
                    self.kiwoom.send_order("send_order_req", "0101", account,
                                           2, code, num, price,
                                           hoga_lookup[hoga],
                                           "")  # 1: 매수, 2: 매도
                    print('결과 : ', self.kiwoom.order_result)
                    if self.kiwoom.order_result == 0:
                        self._file_update(self.kiwoom.sell_loc, code, '매도전',
                                          '주문완료')
                    else:
                        print(self.kiwoom.order_result, ': 매도 처리 못했습니다.')
Example #28
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.trade_stocks_done = False

        self.kiwoom = Kiwoom()
        self.kiwoom.comm_connect()

        self.timer = QTimer(self)
        self.timer.start(1000)
        self.timer.timeout.connect(self.timeout)

        self.lineEdit.textChanged.connect(self.code_changed)

        self.pushButton.clicked.connect(self.send_order)
        self.pushButton_2.clicked.connect(self.check_balance)

        # Timer2
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 10)
        self.timer2.timeout.connect(self.timeout2)

        self.load_buy_sell_list()
        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContens()
        self.load_buy_sell_list()

    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusBar().showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()

    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

        accounts_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accounts_num]
        self.comboBox.addItems(accounts_list)

    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")

    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.kiwoom.get_login_info("ACCNO")
        account_number = account_number.split(';')[0]

        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt")
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt")
        sell_list = f.readlines()
        f.close()

        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)

        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContens()

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, i,
                                       code, num, price, hoga_lookup[hoga], "")

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")

        # buy list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()

    def timeout(self):
        market_start_time = QTime(9, 0, 0)
        current_time = QTime.currentTime()

        if current_time > market_start_time and self.trade_stocks_done is False:
            self.trade_stocks()
            self.trade_stocks_done = True

        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간" + text_time

        state = self.kiwoom.get_connect_state()
        if state == 1:
            state_msg = "서버 연결 중"
        else:
            state_msg = "서버 미 연결 중"

        self.statusbar.showMessage(state_msg + " | " + time_msg)
Example #29
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.tr = 0
        #텔레그램봇
        my_token = '692301814:AAEfmddhyZPcO0Uzh8r5ZehfooTPOvKOOqc'
        self.mybot = telegram.Bot(token=my_token)
        self.chat_id = 544924927

        self.kiwoom = Kiwoom()  #키움인스턴스 생성
        self.kiwoom.comm_connect()  #API로그인

        self.ts_1_p = 'False'  #거래전략1 초기값

        # Timer1
        self.timer = QTimer(self)
        self.timer.start(1000)  #1초 상태바
        self.timer.timeout.connect(self.timeout)

        # Timer2
        self.timer2 = QTimer(self)
        self.timer2.start(1000 * 25)  #25초 잔고조회
        self.timer2.timeout.connect(self.timeout2)

        # Timer3
        self.timer3 = QTimer(self)
        self.timer3.start(1000 * 30)  #30초 거래전략1
        self.timer3.timeout.connect(self.timeout3)

        # Timer4
        self.timer4 = QTimer(self)
        self.timer4.start(1000 * 33)  # 33초 매도전략
        self.timer4.timeout.connect(self.timeout4)

        # Timer5
        self.timer5 = QTimer(self)
        self.timer5.start(1000 * 20)  # 20초 buy&sell.txt 로드
        self.timer5.timeout.connect(self.timeout5)

        # Timer6
        #self.timer6 = QTimer(self)
        #self.timer6.start(1000 * 38)  # 38초 주문 넣기
        #self.timer6.timeout.connect(self.timeout6)

        # Timer7
        self.timer7 = QTimer(self)
        self.timer7.start(1000 * 1800)  # 30분 중간보고
        self.timer7.timeout.connect(self.timeout7)

        # Timer10
        #self.timer4 = QTimer(self)
        #self.timer4.start(1000 * 3600) #1시간 후 프로그램종료!
        #self.timer4.timeout.connect(self.quit_app)
        #self.timer4.timeout.connect(QCoreApplication.instance().quit)

        self.list700 = []
        self.list600 = []
        self.buy_list = []

        self.lineEdit.textChanged.connect(self.code_changed)  #종목코드 입력시
        self.pushButton.clicked.connect(self.send_order)  #현금주문 버튼 클릭시
        self.pushButton_2.clicked.connect(self.check_balance)  #계좌정보 조회
        self.pushButton_3.clicked.connect(self.trading_strategy_1)  #거래전략1호
        self.pushButton_4.clicked.connect(self.quit_app)  #앱종료
        self.pushButton_4.clicked.connect(
            QCoreApplication.instance().quit)  # 앱종료
        #계좌정보
        accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT"))
        accounts = self.kiwoom.get_login_info("ACCNO")
        accounts_list = accounts.split(';')[0:accouns_num]
        self.comboBox.addItems(accounts_list)

        self.load_buy_sell_list()

        #로그기록
        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 시작되었습니다.")
        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               "ㅣ 프로그램이 시작되었습니다.")

    #종료
    def quit_app(self):
        self.timer = ''
        self.timer2 = ''
        self.timer3 = ''
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1
        myaccount = self.kiwoom.opw00018_output['single']
        mystocks = self.kiwoom.opw00018_output['multi']

        self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                             "ㅣ 프로그램이 종료되었습니다.")
        self.mybot.sendMessage(
            self.chat_id,
            text=QTime.currentTime().toString("hh:mm:ss") +
            "ㅣ 프로그램이 종료되었습니다.\n총 TR 요청 횟수 : %d회\n 계좌현황 :%s\n 보유종목 : %s" %
            (self.tr, myaccount, mystocks))
        time.sleep(3)

    #상태표시줄(현재시간, 서버연결상태)
    def timeout(self):
        current_time = QTime.currentTime()
        text_time = current_time.toString("hh:mm:ss")
        time_msg = "현재시간: " + text_time

        state = self.kiwoom.GetConnectState()
        if state == 1:
            state_msg = "서버 연결되었습니다."
        else:
            state_msg = "서버가 연결되지 않았습니다."

        self.statusbar.showMessage(state_msg + " | " + time_msg)

    def timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()  #계좌정보 실시간 조회

    def timeout3(self):
        if self.ts_1_p == 'True':  #거래전략1 진행시 30초마다 조회
            self.volume_check()

    def timeout4(self):
        self.sell_stocks()

    def timeout5(self):
        self.load_buy_sell_list()

    #def timeout6(self):
    #    self.trade_stocks()
    def timeout7(self):  #중간보고
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1
        myaccount = self.kiwoom.opw00018_output['single']
        mystocks = self.kiwoom.opw00018_output['multi']

        self.mybot.sendMessage(self.chat_id,
                               text=QTime.currentTime().toString("hh:mm:ss") +
                               "ㅣ 총 TR 요청 횟수 : %d회\n 계좌현황 :%s\n 보유종목 : %s" %
                               (self.tr, myaccount, mystocks))

    #종목명 나타내기
    def code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)

    #현금주문
    def send_order(self):
        order_type_lookup = {'신규매수': 1, '신규매도': 2, '매수취소': 3, '매도취소': 4}
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        account = self.comboBox.currentText()
        order_type = self.comboBox_2.currentText()
        code = self.lineEdit.text()
        hoga = self.comboBox_3.currentText()
        num = self.spinBox.value()
        price = self.spinBox_2.value()

        self.kiwoom.send_order("send_order_req", "0101", account,
                               order_type_lookup[order_type], code, num, price,
                               hoga_lookup[hoga], "")
        self.tr += 1

    #계좌정보
    def check_balance(self):
        self.kiwoom.reset_opw00018_output()
        #account_number = self.kiwoom.get_login_info("ACCNO")
        #account_number = account_number.split(';')[0]
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(0.2)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")

        self.tr += 1
        # opw00001
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
        self.tr += 1

        # balance
        item = QTableWidgetItem(self.kiwoom.d2_deposit)
        item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.tableWidget.setItem(0, 0, item)

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents()

        # Item list
        item_count = len(self.kiwoom.opw00018_output['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.opw00018_output['multi'][j]
            for i in range(len(row)):
                item = QTableWidgetItem(row[i])
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
                self.tableWidget_2.setItem(j, i, item)

        self.tableWidget_2.resizeRowsToContents()
        print('잔고조회완료')

    def load_buy_sell_list(self):
        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        ff = open("sell_list.txt", 'rt')
        sell_list = ff.readlines()
        ff.close()

        row_count = len(buy_list) + len(sell_list)
        self.tableWidget_4.setRowCount(row_count)

        # buy list
        for j in range(len(buy_list)):
            row_data = buy_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rsplit())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(j, i, item)
        # sell list
        for j in range(len(sell_list)):
            row_data = sell_list[j]
            split_row_data = row_data.split(';')
            split_row_data[1] = self.kiwoom.get_master_code_name(
                split_row_data[1].rstrip())

            for i in range(len(split_row_data)):
                item = QTableWidgetItem(split_row_data[i].rstrip())
                item.setTextAlignment(Qt.AlignVCenter | Qt.AlignCenter)
                self.tableWidget_4.setItem(len(buy_list) + j, i, item)

        self.tableWidget_4.resizeRowsToContents()
        print('buy & sell.txt 불러오기')

    def trade_stocks(self):
        hoga_lookup = {'지정가': "00", '시장가': "03"}

        f = open("buy_list.txt", 'rt')
        buy_list = f.readlines()
        f.close()

        f = open("sell_list.txt", 'rt')
        sell_list = f.readlines()
        f.close()

        # account
        account = self.comboBox.currentText()

        # buy list
        for row_data in buy_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매수전':
                self.kiwoom.send_order("send_order_req", "0101", account, 1,
                                       code, num, price, hoga_lookup[hoga], "")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") + 'ㅣ ' +
                    code + ' ' + num + '주 ' + price + "원 매수주문")
                self.tr += 1

        # sell list
        for row_data in sell_list:
            split_row_data = row_data.split(';')
            hoga = split_row_data[2]
            code = split_row_data[1]
            num = split_row_data[3]
            price = split_row_data[4]

            if split_row_data[-1].rstrip() == '매도전':
                self.kiwoom.send_order("send_order_req", "0101", account, 2,
                                       code, num, price, hoga_lookup[hoga], "")
                self.mybot.sendMessage(
                    self.chat_id,
                    text=QTime.currentTime().toString("hh:mm:ss") + 'ㅣ ' +
                    code + ' ' + num + '주 ' + price + "원 매도주문")
                self.tr += 1

                # buy list
        for i, row_data in enumerate(buy_list):
            buy_list[i] = buy_list[i].replace("매수전", "매수주문완료")

        # file update
        f = open("buy_list.txt", 'wt')
        for row_data in buy_list:
            f.write(row_data)
        f.close()

        # sell list
        for i, row_data in enumerate(sell_list):
            sell_list[i] = sell_list[i].replace("매도전", "매도주문완료")

        # file update
        f = open("sell_list.txt", 'wt')
        for row_data in sell_list:
            f.write(row_data)
        f.close()
        print('거래알고리즘실행완료')

    #거래량급증 거래전략1
    def trading_strategy_1(self):

        if self.ts_1_p == 'False':
            print('ts_1_p = true')
            self.ts_1_p = 'True'
            self.label_7.setText("진행중...")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 전략1호 시작되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 전략1호 시작되었습니다.")

        elif self.ts_1_p == 'True':
            print('ts_1_p = False')
            self.label_7.setText("")
            self.textEdit.append(QTime.currentTime().toString("hh:mm:ss") +
                                 "ㅣ 전략1호 중지되었습니다.")
            self.mybot.sendMessage(
                self.chat_id,
                text=QTime.currentTime().toString("hh:mm:ss") +
                "ㅣ 전략1호 중지되었습니다.")
            self.ts_1_p = 'False'

    #거래량급증 조회
    def volume_check(self):
        market_list = ['kospi', 'kosdaq']
        print('조회수급등조회시작')
        for market in market_list:
            if market == 'kospi':
                url = 'https://finance.naver.com/sise/sise_quant_high.nhn'
            elif market == 'kosdaq':
                url = 'https://finance.naver.com/sise/sise_quant_high.nhn?sosok=1'
            html = requests.get(url).text

            df = pd.DataFrame()
            df = df.append(pd.read_html(html, header=0)[1])
            df = df.dropna()
            df = df.rename(
                columns={
                    'N': 'num',
                    '증가율': 'rate',
                    '종목명': 'name',
                    '현재가': 'price',
                    '전일비': 'diff',
                    '등락률': 'updown',
                    '매수호가': 'buy_hoga',
                    '매도호가': 'sell_hoga',
                    '거래량': 'volume',
                    '전일거래량': 'yes_volume',
                    'PER': 'PER'
                })
            df = df.set_index(['num'])  #크롤링완료

            #700이상
            df700 = df[[a > 700 for a in df.rate]]
            a700 = list(df700['name'])
            if len(df700) != 0:
                for i in range(len(df700)):
                    a = html.find(a700[i])
                    code = html[a - 22:a - 16]
                    self.list700.append(code)

            #교집합 구하기
            aa = set(self.list700)
            bb = set(self.list600)
            buy_set = aa & bb
            buy_set = list(buy_set)
            if len(buy_set) != 0:
                for i in range(len(buy_set)):
                    self.buy_list.append(buy_set[i])

            #600~700
            self.list600 = []
            df600 = df[[a > 400 and a < 700 for a in df.rate]]
            a600 = list(df600['name'])
            if len(df600) != 0:
                for i in range(len(df600)):
                    a = html.find(a600[i])
                    code = html[a - 22:a - 16]
                    self.list600.append(code)

        print(self.buy_list)

        #buy_list 업데이트
        if len(self.buy_list) == 0:
            pass
        else:
            #print('buy_list: ' + buy_set)
            account_number = self.comboBox.currentText()
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00001_req", "opw00001", 0, "2000")
            buy_q = int(self.kiwoom.d2_deposit[:-3].replace(',', ''))
            buy_q = (buy_q // len(self.buy_list)) // 5
            self.tr += 1

            f = open("buy_list.txt", "wt")
            for code in self.buy_list:
                time.sleep(0.2)
                self.kiwoom.set_input_value("종목코드", code)
                self.kiwoom.comm_rq_data("opt10001_req", "opt10001", 0, "0101")
                self.mybot.sendMessage(self.chat_id,
                                       text="매수선정종목: " +
                                       self.kiwoom.stock_name)
                f.write("매수;%s;시장가;%d;0;매수전\n" %
                        (code, buy_q // self.kiwoom.stock_pv))
            f.close()
            print('buy_list.txt updated')
            self.trade_stocks()

        self.buy_list = []
        self.list700 = []
        print("거래량급증조회완료")

    #목표수익률 도달시 팔기
    def sell_stocks(self):
        self.kiwoom.reset_opw00018_output()
        account_number = self.comboBox.currentText()
        self.kiwoom.set_input_value("계좌번호", account_number)
        self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.remained_data:
            time.sleep(1)
            self.kiwoom.set_input_value("계좌번호", account_number)
            self.kiwoom.comm_rq_data("opw00018_req", "opw00018", 2, "2000")
        self.tr += 1

        list_1 = list(self.kiwoom.opw00018_output['multi'])
        print(list_1)
        a = len(list_1)
        if a != 0:
            f = open('sell_list.txt', 'wt')
            for i in range(a):
                if float(list_1[i][5]) > 5:
                    f.write("매도;%s;시장가;%s;0;매도전\n" %
                            (list_1[i][6],
                             int(list_1[i][1].replace('.00', '').replace(
                                 ',', ''))))
                elif float(list_1[i][5]) < -3:
                    f.write("매도;%s;시장가;%s;0;매도전\n" %
                            (list_1[i][6],
                             int(list_1[i][1].replace('.00', '').replace(
                                 ',', ''))))
            f.close()
            self.trade_stocks()
            print('sell_list.txt updated')