trader.py 4.29 KB
from library.open_api import *
from PyQt5.QtWidgets import *

class Trader(QMainWindow):
    def __init__(self):
        super().__init__()
        self.open_api=open_api()
        self.current_time=QTime.currentTime()
        self.variable_setting()

    # 변수 설정
    def variable_setting(self):
        self.open_api.py_gubun="trader"

        self.market_start_time=QTime(9,0,0)     # 장시작 시간
        self.market_end_time=QTime(15,30,0)     # 장마감 시간
        self.buy_end_time=QTime(15,31,0)        # 매수를 몇 시까지 할지

    # 매수 함수
    def auto_trade_stock(self):
        logger.debug("auto_trade_stock 함수")
        self.open_api.get_today_buy_list()

    # 매도 리스트를 저장하는 함수
    def get_sell_list_trade(self):
        logger.debug("get_sell_list 함수")

        # 매도 리스트를 가져오기 전에 이전에 매도완료한 항목을 DB 업데이트
        self.open_api.check_chegyul()
        self.open_api.rate_check()

        self.open_api.sf.get_date_for_simul()
        self.sell_list=self.open_api.sf.get_sell_list(len(self.open_api.sf.date_rows))      # 매도리스트

    # 매도 함수
    def auto_trade_sell_stock(self):
        # 잔고정보 저장
        self.open_api.check_balance()
        # 보유항목 리스트 저장
        self.open_api.db_to_possessed_item()
        # 매도를 진행하기 전, 이전에 매도 완료한 항목에 대해 DB 업데이트
        self.open_api.final_chegyul_check()
        # 매도리스트 저장
        self.get_sell_list_trade()
        print(self.sell_list)

        for i in range(len(self.sell_list)):
            get_sell_code=self.sell_list[i][0]                              # 종목코드
            get_sell_rate=self.sell_list[i][1]                              # 매도수익률
            get_sell_num=self.open_api.get_holding_amount(get_sell_code)    # 매도수량

            if get_sell_num==False:
                continue

            logger.debug("매도 종목 코드 : "+str(get_sell_code))
            logger.debug("매도 수익률 : "+str(get_sell_rate))
            logger.debug("매도 수량량 : "+str(get_sell_num))

            # 매도할 종목 코드가 정상적일 경우
            if get_sell_code!=False and get_sell_code!='0' and get_sell_code!=0:
                if get_sell_rate<0:
                    # 03 : 시장가매도
                    logger.debug("손절매도--------"+str(get_sell_code)+"-------------")
                    self.open_api.send_order("send_order_req","0101",self.open_api.account_no,2,get_sell_code,get_sell_num,0,"03","")
                else:
                    logger.debug("익절매도--------"+str(get_sell_code)+"-------------")
                    self.open_api.send_order("send_order_req","0101",self.open_api.account_no,2,get_sell_code,get_sell_num,0,"03","")
            else:
                sys.exit()

    # 현재 시간에 장이 열려있는지 확인하는 함수
    def market_time_check(self):
        self.current_time=QTime.currentTime()
        if self.current_time>self.market_start_time and self.current_time<self.market_end_time:
            logger.debug('장시간입니다.')
            return True
        else:
            logger.debug("장시간이 아닙니다.")
            return False

    # 현재 시간이 설정해놓은 매수 시간 범위인지 확인하는 함수
    def buy_time_check(self):
        self.current_time=QTime.currentTime()
        if self.current_time<self.buy_end_time:
            return True
        else:
            return False

    # 거래 함수
    def run(self):
        while True:
            time.sleep(0.3)
            # 날짜 저장
            self.open_api.date_setting()
            # 장이 서있는 시간인 경우
            if self.market_time_check():
                # 매도
                self.auto_trade_sell_stock()
                # 1. 잔액이 존재하고 / 2. 매수 가능한 시간대이고 / 3. 매수 정지 옵션이 체크되어있지 않으면
                # 매수
                if self.open_api.jango_check() and self.buy_time_check() and self.open_api.buy_check():
                    self.auto_trade_stock()

            else:
                break

if __name__ == "__main__":
    app = QApplication(sys.argv)
    trader = Trader()
    trader.run()