コード例 #1
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.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")


    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 code_changed(self):
        code = self.lineEdit.text()
        name = self.kiwoom.get_master_code_name(code)
        self.lineEdit_2.setText(name)
コード例 #2
0
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.CommConnect()

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

        # Get Account Number
        accouns_num = int(self.kiwoom.GetLoginInfo("ACCOUNT_CNT"))
        accounts = self.kiwoom.GetLoginInfo("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 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 code_changed(self):
        code = self.lineEdit.text()
        code_name = self.kiwoom.GetMasterCodeName(code)
        self.lineEdit_2.setText(code_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.SendOrder("SendOrder_req", "0101", account, order_type_lookup[order_type], code, num, price, hoga_lookup[hoga], "")
コード例 #3
0
ファイル: pytrader.py プロジェクト: ssehuun/system_trading
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)

    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)
コード例 #4
0
ファイル: StockT.py プロジェクト: 100th/Stock-trading
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()
コード例 #5
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)

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

    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.data_remained:
            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
        ):  # ‘총매입’, ‘총평가’, ‘총손익’, ‘총수익률(%)’, ‘추정자산’을 QTableWidget 의 칼럼에 추가하는 코드
            item = QTableWidgetItem(self.kiwoom.opw00018_output['single'][i -
                                                                          1])
            item.setTextAlignment(Qt.AlignVCenter | Qt.AlignRight)
            self.tableWidget.setItem(0, i, item)

        self.tableWidget.resizeRowsToContents(
        )  # 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 timeout2(self):
        if self.checkBox.isChecked():
            self.check_balance()
コード例 #6
0
ファイル: Trader 0.4.1.py プロジェクト: knh474/my_project
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 종목리스트 저장 완료')
コード例 #7
0
ファイル: Trader 0.1.0.py プロジェクト: knh474/my_project
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()
コード例 #8
0
ファイル: pytrader.py プロジェクト: richon0276/book
class MyWindow(QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.kiwoom = Kiwoom()
        self.kiwoom.CommConnect()

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

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

        # Get Account Number
        accouns_num = int(self.kiwoom.GetLoginInfo("ACCOUNT_CNT"))
        accounts = self.kiwoom.GetLoginInfo("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 timeout2(self):
        if self.checkBox.isChecked() == True:
            self.check_balance()

    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 code_changed(self):
        code = self.lineEdit.text()
        code_name = self.kiwoom.GetMasterCodeName(code)
        self.lineEdit_2.setText(code_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.SendOrder("SendOrder_req", "0101", account,
                              order_type_lookup[order_type], code, num, price,
                              hoga_lookup[hoga], "")

    def check_balance(self):
        self.kiwoom.init_opw00018_data()

        # Request opw00018
        self.kiwoom.SetInputValue("계좌번호", "8080996211")
        self.kiwoom.SetInputValue("비밀번호", "0000")
        self.kiwoom.CommRqData("opw00018_req", "opw00018", 0, "2000")

        while self.kiwoom.prev_next == '2':
            time.sleep(0.2)
            self.kiwoom.SetInputValue("계좌번호", "8080996211")
            self.kiwoom.SetInputValue("비밀번호", "0000")
            self.kiwoom.CommRqData("opw00018_req", "opw00018", 2, "2000")

        # Request opw00001
        self.kiwoom.SetInputValue("계좌번호", "8080996211")
        self.kiwoom.SetInputValue("비밀번호", "0000")
        self.kiwoom.CommRqData("opw00001_req", "opw00001", 0, "2000")

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

        for i in range(1, 6):
            item = QTableWidgetItem(self.kiwoom.data_opw00018['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.data_opw00018['multi'])
        self.tableWidget_2.setRowCount(item_count)

        for j in range(item_count):
            row = self.kiwoom.data_opw00018['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()
コード例 #9
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")
コード例 #10
0
ファイル: pytrader_window.py プロジェクト: mattblk/Study
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()
コード例 #11
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')