Beispiel #1
0
 def __init__(self, device, tasklist):
     self.log = MyLogger('Crops', LOG_LEVEL=logging.INFO)
     self.device = device
     self.tasklist = tasklist
     self.data = []
     self.settings = []
     self.updateListData()
Beispiel #2
0
 def on_register_real_all_btn_clicked(self):
     MyLogger.instance().logger().info("")
     잔고_dic = kiwoom.data.잔고_dic
     종목코드_list = 잔고_dic.keys()
     종목코드_list_str = ";".join(종목코드_list)
     MyLogger.instance().logger().info("종목코드_list_str %s", 종목코드_list_str)
     kiwoom.set_real_reg(종목코드_list_str)
Beispiel #3
0
 def on_register_real_all_btn_clicked(self):
     MyLogger.instance().logger().info("")
     잔고_dic = kiwoom.data.잔고_dic
     종목코드_list = 잔고_dic.keys()
     종목코드_list_str = ";".join(종목코드_list)
     MyLogger.instance().logger().info("종목코드_list_str %s", 종목코드_list_str)
     kiwoom.set_real_reg(종목코드_list_str)
Beispiel #4
0
 def __init__(self):
     self.log = MyLogger('ADB', LOG_LEVEL=logging.INFO)
     client = Client(host='127.0.0.1', port=5037)
     self.log.debug(client.version())
     devices = client.devices()
     if len(devices) == 0:
         self.log.debug("no devices")
         quit()
     self.device = devices[0]
     self.log.debug(f'updating info for {self.device}')
     number = 5
     touch_id = 0
     lines = self.device.shell('getevent -p').split("\n")
     for line in lines:
         if "/dev/input" in line:
             number = line[-1]
         if "Touch" in line:
             touch_id = number
             self.touch = f"sendevent /dev/input/event{number}"
         if "max" in line and "ABS" in line and number == touch_id:
             values = line.split(', ')
             for value in values:
                 if "max" in value:
                     self.max = int(value[4:])
                     self.log.debug(f"found max: {self.max}")
Beispiel #5
0
    def _slot_btn_add(self):
        """点击Move button,将左侧列表中选中的控件信息以json的形式写入到右侧的TextEdit控件中
        """
        item_info_dict = {}
        # 添加节点属性
        for item in self.tableWidget.selectedItems():
            mlog.instance().logger.info(
                "Current column name is {}, and current item value is {}".
                format(
                    self.tableWidget.item(0, item.column()).text(),
                    item.text()))

            column_name = self.tableWidget.item(0, item.column()).text()
            item_value = item.text()
            item_info_dict[column_name] = item_value

        # 添加操作属性
        item_info_dict['Action'] = 'click'
        item_info_dict['Pre-wait'] = '0'
        item_info_dict['Post-wait'] = '5'
        # Dump成Json格式
        item_info_json = json.dumps(item_info_dict, sort_keys=False, indent=1)
        # 附加到TextEdit
        # self.jsonTextEdit.append(item_info_json)
        self.scriptVerticalLayout.addWidget(
            self._create_textEdit(item_info_json))
Beispiel #6
0
    def _get_control_infos(self, seconds=3):
        """获取焦点所在应用的所有窗体控件,并便利输出控件信息

        Args:
            seconds (int, optional): 点击后n秒开始分析. Defaults to 3.

        Yields:
            [tuple]: 窗体上所有控件的信息
        """
        time.sleep(seconds)

        control = auto.GetFocusedControl()
        if control:
            for c, d in auto.WalkControl(control, True):
                mlog.instance().logger.info(c.ControlTypeName + " " + str(d))
                yield (
                    c.ControlType,
                    c.ClassName,
                    "[{},{},{},{}]".format(
                        c.BoundingRectangle.left,
                        c.BoundingRectangle.top,
                        c.BoundingRectangle.right,
                        c.BoundingRectangle.bottom,
                    ),
                    c.Name,
                    "0x{0:X}({0})".format(c.NativeWindowHandle),
                    str(d),
                )
Beispiel #7
0
class Room:
    """
    Base class for Room
    """
    def __init__(self, x, y, name, description, exits):
        """
        :param x: room x
        :param y: room y
        :param name: room name
        :param description: room description
        """
        self.x = x
        self.y = y
        self.name = name
        self.description = description
        self.exits = exits
        self.log = MyLogger('Room')

    def __str__(self):
        self.log.warning('__str__')
        return f'{self.name}\n{self.description}'

    def _check_exit(self, direction):
        self.log.info('in init')
        return direction in self.exits
Beispiel #8
0
 def on_condition_apply_btn_clicked(self):
     MyLogger.instance().logger().info("")
     apply_str = self.ui.combo_apply.currentText()
     MyLogger.instance().logger().info("신호종류: %s", apply_str)
     for condition in self.selected_condition:
         condition.적용유무 = apply_str
     self.on_data_updated(["조건식_dic"])
Beispiel #9
0
 def on_condition_signal_btn_clicked(self):
     MyLogger.instance().logger().info("")
     signal_str = self.ui.combo_signal.currentText()
     MyLogger.instance().logger().info("신호종류: %s", signal_str)
     for condition in self.selected_condition:
         condition.신호종류 = signal_str
     self.on_data_updated(["조건식_dic"])
Beispiel #10
0
    def __init__(self):

        self.global_config = parse_json(default_config_path)
        self.total_stock = self.global_config["target_stock"]
        self.total_index = self.global_config["target_index"]
        self.total_mao = self.global_config["target_mao"]
        self.logger = MyLogger("monitor.py - Stock Monitor").get_logger()
 def __init__(self, config_file='/config/switch.txt'):
     config_loader = ConfigurationLoader(config_file)
     configs = config_loader.load_configuration('mqtt_broker', 'mqtt_topic',
                                                'mqtt_id', 'switch_pin',
                                                'switch_update_period')
     self.config_file = config_file
     self.switch_update_period = int(configs['switch_update_period'])
     self.mqtt_client = MQTTClient(configs['mqtt_id'],
                                   configs['mqtt_broker'])
     self.mqtt_client.DEBUG = True
     self.mqtt_topic = configs['mqtt_topic']
     self.switch_pin_num = int(configs['switch_pin'])
     self.switch_pin = Pin(self.switch_pin_num, Pin.IN)
     self.id = configs['mqtt_id']
     self.mqtt_broker = configs['mqtt_broker']
     self.logger = MyLogger(False)
     self.logger.log('DEBUG', self.id,
                     'Connecting to {}...'.format(self.mqtt_broker))
     try:
         self.mqtt_client.connect()
         self.logger.log('INFO', self.id,
                         'Reconnected to {}'.format(self.mqtt_broker))
     except:
         self.logger.log(
             'ERROR', self.id,
             'Connection failure to {}'.format(self.mqtt_broker))
     self.last_switch_position = self.switch_pin.value()
     self.mqtt_messages_sent = 0
     self.debounce_time = 0.5
     self.timer = None
     self.init_timer()
Beispiel #12
0
 def set_real_reg(self, the_종목코드_list_str):
     MyLogger.instance().logger().info("the_종목코드_list_str %s", the_종목코드_list_str)
     fid = "9001;10;13"  # 종목코드,업종코드;현재가;누적거래량
     ret = self.ocx.dynamicCall("SetRealReg(QString, QString, QString, QString)",
                                [constant.SN_실시간조회, the_종목코드_list_str, fid, "1"])  # "1" 종목 추가, "0" 기존 종목은 제외
     MyLogger.instance().logger().info("call SetRealReg(). ret: %d", ret)
     return ret
Beispiel #13
0
 def on_condition_apply_btn_clicked(self):
     MyLogger.instance().logger().info("")
     apply_str = self.ui.combo_apply.currentText()
     MyLogger.instance().logger().info("신호종류: %s", apply_str)
     for condition in self.selected_condition:
         condition.적용유무 = apply_str
     self.on_data_updated(["조건식_dic"])
Beispiel #14
0
 def tr_multi_code(self, the_종목코드_list_str, the_종목수):
     MyLogger.instance().logger().debug("the_종목코드_list_str %s, the_종목수 %d",
                                        the_종목코드_list_str, the_종목수)
     ret = self.ocx.dynamicCall(
         "CommKwRqData(QString, int, int, int, QString, QString)",
         the_종목코드_list_str, 0, the_종목수, 0, "관심종목", constant.SN_관심종목조회)
     MyLogger.instance().logger().debug("ret %d", ret)
Beispiel #15
0
 def on_condition_signal_btn_clicked(self):
     MyLogger.instance().logger().info("")
     signal_str = self.ui.combo_signal.currentText()
     MyLogger.instance().logger().info("신호종류: %s", signal_str)
     for condition in self.selected_condition:
         condition.신호종류 = signal_str
     self.on_data_updated(["조건식_dic"])
Beispiel #16
0
    def solve(self):
        answer_file_name = "Answer_" + self._file_name
        with open(answer_file_name, 'w+') as fp_answer:
            with open(self._file_name, 'r') as fp:
                lines = fp.readlines()

                for index, line in enumerate(lines):
                    line = line.replace('\n', '')
                    items = self._clear_line(line.split(' '))
                    item_count = len(items)

                    if item_count < 4:
                        mlog.instance().logger.error(
                            f"{self.__class__.__name__} {sys._getframe().f_code.co_name}: line {index} is invalid"
                        )

                    answer = self._calc_answer(items)
                    answer_str = u"answer " + f"{answer}"

                    result_str = "    "

                    if item_count == 5:
                        # 带回答的情况
                        if int(items[4]) == answer:
                            result_str = u" right "
                            content = f"{line}\n"
                        else:
                            result_str = u" wrong "
                            content = f"{line}{result_str}{answer_str}\n"
                    fp_answer.write(content)
                    print(content)
Beispiel #17
0
 def _slot_btn_select(self):
     """slot of choose_button, 选择要分析的可执行程序
     """
     file_name, file_type = QFileDialog.getOpenFileName(
         self, "选取文件", os.getcwd(), "Exe Files (*.exe)")
     mlog.instance().logger.info("Choose File {}", file_name)
     if file_name != "":
         self.textBrowser.setText(file_name)
Beispiel #18
0
 def send_order(self, 주문유형, 종목코드, 주문수량, 주문단가, 거래구분):
     MyLogger.instance().logger().info("%d, %s, %d, %d, %s", 주문유형, 종목코드, 주문수량, 주문단가, 거래구분)
     sRQName = "주식주문"
     sScreenNo = constant.SN_주식주문
     ret = self.ocx.dynamicCall("SendOrder(QString, QString, QString, int, QString, int, int, QString, QString)",
                                [sRQName, sScreenNo, self.data.계좌번호, 주문유형, 종목코드, 주문수량, 주문단가, 거래구분, ""])
     MyLogger.instance().logger().info("call SendOrder(). ret: %d", ret)
     return ret
Beispiel #19
0
    def __init__(self, map):
        self.log = MyLogger('Game')
        self.player_x = 0
        self.player_y = 0
        self.map = map
        self.current_room = self._get_room(0, 0)

        self._look_at(self.current_room)
Beispiel #20
0
 def on_sell_signal(self, 주문수량):
     MyLogger.instance().logger().info("종목명: %s, 주문수량: %d",
                                       self.balance.종목명, 주문수량)
     kiwoom = Kiwoom.instance()
     job = Job(kiwoom.send_order, 2, self.balance.종목코드, 주문수량, 0,
               "03")  # 시장가로 매도
     kiwoom.job_queue.put(job)
     self.is_queued = True
Beispiel #21
0
    def collect_day_data(self):
        MyLogger.instance().logger().debug("")

        class DayData(threading.Thread):
            def __init__(self, the_ocx, the_condition_value):
                super().__init__()
                self.ocx = the_ocx
                self.condition_value = the_condition_value

            def run(self):
                kospi_code_list_str = self.ocx.dynamicCall(
                    "GetCodeListByMarket(QString)", ["0"])
                kospi_code_list = kospi_code_list_str.split(';')
                MyLogger.instance().logger().info("kospi_code_list. len: %d",
                                                  len(kospi_code_list))
                kosdaq_code_list_str = self.ocx.dynamicCall(
                    "GetCodeListByMarket(QString)", ["10"])
                kosdaq_code_list = kosdaq_code_list_str.split(';')
                MyLogger.instance().logger().info("kosdaq_code_list. len: %d",
                                                  len(kosdaq_code_list))
                code_list = kospi_code_list + kosdaq_code_list
                from datetime import datetime
                기준일자 = datetime.today().strftime("%Y%m%d")
                from glob import glob

                for code in code_list:
                    if len(code) < 3:
                        MyLogger.instance().logger().warning(
                            "unexpected code: %s", code)
                        continue

                    temp_list = glob('data/day/' + code + '*.csv')
                    if len(temp_list) >= 1:
                        MyLogger.instance().logger().warning(
                            "%s already exist", code)
                        continue

                    time.sleep(1)
                    self.condition_value.acquire()
                    self.ocx.dynamicCall("SetInputValue(QString, QString)",
                                         "종목코드", code)
                    self.ocx.dynamicCall("SetInputValue(QString, QString)",
                                         "기준일자", 기준일자)
                    self.ocx.dynamicCall("SetInputValue(QString, QString)",
                                         "수정주가구분", "1")
                    ret = self.ocx.dynamicCall(
                        "CommRqData(QString, QString, int, QString)", "주식일봉조회",
                        "opt10081", 0, constant.SN_데이터_일봉조회)
                    MyLogger.instance().logger().info(
                        "CommRqData. code: %s, ret: %d", code, ret)
                    self.condition_value.wait()

                self.condition_value.release()
                MyLogger.instance().logger().info("the end of run()")

        self.condition_value = threading.Condition()
        test_thread = DayData(self.ocx, self.condition_value)
        test_thread.start()
Beispiel #22
0
 def perform_test(self):
     MyLogger.instance().logger().debug("")
     self.ocx.dynamicCall("SetInputValue(QString, QString)", "종목코드",
                          "005930")
     self.ocx.dynamicCall("SetInputValue(QString, QString)", "틱범위", "1")
     self.ocx.dynamicCall("SetInputValue(QString, QString)", "수정주가구분", "1")
     ret = self.ocx.dynamicCall(
         "CommRqData(QString, QString, int, QString)", "주식분봉조회", "opt10080",
         0, constant.SN_잔고조회)
Beispiel #23
0
 def on_save_balance_btn_clicked(self):
     MyLogger.instance().logger().info("")
     f = open("my_list.txt", "w", encoding='utf8')
     list_data = []
     for balance in kiwoom.data.잔고_dic.values():
         list_data.append(balance.get_dic())
     data = json.dumps(list_data, ensure_ascii=False, indent=4)
     f.write(data)
     f.close()
Beispiel #24
0
 def on_condition_result_add_btn_clicked(self):
     MyLogger.instance().logger().info("")
     code_text = self.ui.txt_condition_result.toPlainText()
     if len(code_text) > 4:
         code_list = (eval(code_text))
         code_list_str = ";".join(code_list)
         kiwoom.tr_multi_code(code_list_str, len(code_list))
     else:
         MyLogger.instance().logger().error("self.ui.txt_condition_result is too short.")
Beispiel #25
0
 def on_save_balance_btn_clicked(self):
     MyLogger.instance().logger().info("")
     f = open("my_list.txt", "w", encoding='utf8')
     list_data = []
     for balance in kiwoom.data.잔고_dic.values():
         list_data.append(balance.get_dic())
     data = json.dumps(list_data, ensure_ascii=False, indent=4)
     f.write(data)
     f.close()
Beispiel #26
0
 def tr_balance(self):
     MyLogger.instance().logger().debug("계좌번호 %s", self.data.계좌번호)
     self.ocx.dynamicCall("SetInputValue(QString, QString)", "계좌번호",
                          self.data.계좌번호)
     self.ocx.dynamicCall("SetInputValue(QString, QString)", "조회구분", 2)
     ret = self.ocx.dynamicCall(
         "CommRqData(QString, QString, int, QString)", "계좌평가잔고내역요청",
         "opw00018", 0, constant.SN_잔고조회)
     MyLogger.instance().logger().debug("ret %d", ret)
Beispiel #27
0
 def __init__(self, device, tasklist):
     HD.__init__(self, device, tasklist, 'money')
     self.log=MyLogger('shop', LOG_LEVEL=logging.DEBUG)
     self.tasklist.addtask(20, f"checking for items to sell", self.image, self.checkItems)
     self.shoplist=Shoplist(self)
     self.position=HD.getPos([-15,0])
     self.slots=4
     self.max_slots=4
     self.atshop=False
     self.temp_shop=self.device.loadTemplates('shop','')
Beispiel #28
0
 def OnEventConnect(self, nErrCode):
     if nErrCode == 0:
         MyLogger.instance().logger().debug("로그인 성공")
         account_num = self.ocx.dynamicCall("GetLoginInfo(QString)", ["ACCNO"])
         account_num = account_num[:-1]
         account_list = account_num.split(";")
         self.data.계좌번호_list = account_list
         self.data.계좌번호 = account_list[0]
         self.callback.on_data_updated(["계좌번호"])
         self.callback.on_connected()
Beispiel #29
0
 def on_sell_strategy_add_btn_clicked(self):
     strategy_str = self.ui.combo_sell.currentText()
     MyLogger.instance().logger().info("전략: %s", strategy_str)
     for balance in self.selected_balance:
         param = eval(self.ui.txt_sell_param.text())
         if not type(param) == dict:
             MyLogger.instance().logger().error("wrong param text: %s", self.ui.txt_sell_param.text())
             param = {}
         balance.add_sell_strategy(strategy_str, param)
     self.on_data_updated(["잔고_dic"])
Beispiel #30
0
 def set_real_reg(self, the_종목코드_list_str):
     MyLogger.instance().logger().info("the_종목코드_list_str %s",
                                       the_종목코드_list_str)
     fid = "9001;10;13"  # 종목코드,업종코드;현재가;누적거래량
     ret = self.ocx.dynamicCall(
         "SetRealReg(QString, QString, QString, QString)",
         [constant.SN_실시간조회, the_종목코드_list_str, fid, "1"
          ])  # "1" 종목 추가, "0" 기존 종목은 제외
     MyLogger.instance().logger().info("call SetRealReg(). ret: %d", ret)
     return ret
Beispiel #31
0
 def on_condition_result_add_btn_clicked(self):
     MyLogger.instance().logger().info("")
     code_text = self.ui.txt_condition_result.toPlainText()
     if len(code_text) > 4:
         code_list = (eval(code_text))
         code_list_str = ";".join(code_list)
         kiwoom.tr_multi_code(code_list_str, len(code_list))
     else:
         MyLogger.instance().logger().error(
             "self.ui.txt_condition_result is too short.")
Beispiel #32
0
 def __init__(self, config_file):
     self.config_loader = ConfigurationLoader(config_file)
     configs = self.config_loader.load_configuration(
         'check_delay', 'broker', 'topic', 'mqtt_id',
         'installed_version_file', 'mqtt_logger_conf')
     self.check_delay = int(configs['check_delay'])
     self.logger = MyLogger(True, configs['mqtt_logger_conf'])
     self.mqtt_client = MQTTClient(configs['mqtt_id'], configs['broker'])
     self.mqtt_client.DEBUG = True
     self.mqtt_client.set_callback(self.read_update)
     self.mqtt_topic = configs['topic']
Beispiel #33
0
 def refresh_interest_balance(self):
     MyLogger.instance().logger().debug("")
     code_list = []
     for balance in self.data.잔고_dic.values():
         if balance.보유수량 == 0:
             code_list.append(balance.종목코드)
     if len(code_list) > 0:
         code_list_str = ";".join(code_list)
         self.tr_multi_code(code_list_str, len(code_list))
     else:
         MyLogger.instance().logger().debug("code_list len: %d", len(code_list))
Beispiel #34
0
 def __init__(self, device, tasklist, item):
     self.log = MyLogger('HD', LOG_LEVEL=logging.INFO)
     self.device = device
     self.tasklist = tasklist
     self.scheduled = False
     file = path.join('images', 'products', f'{item}.png')
     self.image = file if path.isfile(file) else path.join(
         'images', 'no_image.png')
     self.jobs = 0
     self.waiting = 0
     self.loadImages()
Beispiel #35
0
 def OnEventConnect(self, nErrCode):
     if nErrCode == 0:
         MyLogger.instance().logger().debug("로그인 성공")
         account_num = self.ocx.dynamicCall("GetLoginInfo(QString)",
                                            ["ACCNO"])
         account_num = account_num[:-1]
         account_list = account_num.split(";")
         self.data.계좌번호_list = account_list
         self.data.계좌번호 = account_list[0]
         self.callback.on_data_updated(["계좌번호"])
         self.callback.on_connected()
Beispiel #36
0
 def on_sell_strategy_add_btn_clicked(self):
     strategy_str = self.ui.combo_sell.currentText()
     MyLogger.instance().logger().info("전략: %s", strategy_str)
     for balance in self.selected_balance:
         param = eval(self.ui.txt_sell_param.text())
         if not type(param) == dict:
             MyLogger.instance().logger().error(
                 "wrong param text: %s", self.ui.txt_sell_param.text())
             param = {}
         balance.add_sell_strategy(strategy_str, param)
     self.on_data_updated(["잔고_dic"])
Beispiel #37
0
 def on_buy_strategy_changed(self, strategy):
     from kiwoom.strategy.just_buy import JustBuy
     from kiwoom.strategy.buy_on_opening import BuyOnOpening
     if strategy == "buy_just_buy":
         default_param = JustBuy.get_default_param()
     elif strategy == "buy_on_opening":
         default_param = BuyOnOpening.get_default_param()
     else:
         MyLogger.instance().logger().warning("unknown strategy. ignore %s", strategy)
     MyLogger.instance().logger().warning("strategy %s, default_param %s", strategy, str(default_param))
     self.ui.txt_buy_param.setText(str(default_param))
	def __init__(self, loggerfile, modelfile = False):
			
		self.logger = MyLogger(loggerfile)
		self.trafficLights = ni.trafficLights
		self.linkEdges = ni.linkEdges
		if modelfile == False:
			self.model = self.createModel()
		else:
			self.logger.debug(' load model : ' + modelfile)
			self.model = torch.load(modelfile)
		self.actionMap = self.createActionMap()
Beispiel #39
0
    def reload_condition(self):
        MyLogger.instance().logger().info("")

        # 잔고 갱신 요청
        job = Job(self.tr_balance)
        self.job_queue.put(job)

        for condition in self.data.조건식_dic.values():
            if condition.적용유무 == "1":
                # 조건식 실시간 재등록
                job = Job(self.send_condition, condition)
                self.job_queue.put(job)
Beispiel #40
0
    def reload_condition(self):
        MyLogger.instance().logger().info("")

        # 잔고 갱신 요청
        job = Job(self.tr_balance)
        self.job_queue.put(job)

        for condition in self.data.조건식_dic.values():
            if condition.적용유무 == "1":
                # 조건식 실시간 재등록
                job = Job(self.send_condition, condition)
                self.job_queue.put(job)
Beispiel #41
0
 def refresh_interest_balance(self):
     MyLogger.instance().logger().debug("")
     code_list = []
     for balance in self.data.잔고_dic.values():
         if balance.보유수량 == 0:
             code_list.append(balance.종목코드)
     if len(code_list) > 0:
         code_list_str = ";".join(code_list)
         self.tr_multi_code(code_list_str, len(code_list))
     else:
         MyLogger.instance().logger().debug("code_list len: %d",
                                            len(code_list))
Beispiel #42
0
 def on_buy_strategy_changed(self, strategy):
     from kiwoom.strategy.just_buy import JustBuy
     from kiwoom.strategy.buy_on_opening import BuyOnOpening
     if strategy == "buy_just_buy":
         default_param = JustBuy.get_default_param()
     elif strategy == "buy_on_opening":
         default_param = BuyOnOpening.get_default_param()
     else:
         MyLogger.instance().logger().warning("unknown strategy. ignore %s",
                                              strategy)
     MyLogger.instance().logger().warning("strategy %s, default_param %s",
                                          strategy, str(default_param))
     self.ui.txt_buy_param.setText(str(default_param))
Beispiel #43
0
 def on_sell_strategy_changed(self, strategy):
     from kiwoom.strategy.stop_loss import StopLoss
     from kiwoom.strategy.condition_sell import ConditionSell
     from kiwoom.strategy.sell_on_closing import SellOnClosing
     if strategy == "sell_stop_loss":
         default_param = StopLoss.get_default_param()
     elif strategy == "sell_condition_sell":
         default_param = ConditionSell.get_default_param()
     elif strategy == "sell_on_closing":
         default_param = SellOnClosing.get_default_param()
     else:
         MyLogger.instance().logger().warning("unknown strategy. ignore %s", strategy)
     MyLogger.instance().logger().warning("strategy %s, default_param %s", strategy, str(default_param))
     self.ui.txt_sell_param.setText(str(default_param))
Beispiel #44
0
    def OnReceiveRealCondition(self, strCode, strType, strConditionName, strConditionIndex):
        MyLogger.instance().logger().info("%s, %s, %s, %s, %s", strCode, self.get_master_code_name(strCode), strType, strConditionName, strConditionIndex)
        condition = self.data.get_condition(int(strConditionIndex))

        if condition.신호종류 == "매도신호" and strType == 'I':  # 매도 조건식 편입
            if strCode not in self.data.잔고_dic:
                MyLogger.instance().logger().warning("보유 종목 아님. %s", strCode)
                return
            balance = self.data.get_balance(strCode)
            for 매도전략 in balance.매도전략.values():
                매도전략.on_condition(int(strConditionIndex), strConditionName)

        elif condition.신호종류 == "매수신호" and strType == "I":  # 매수 조건식 편입
            pass
Beispiel #45
0
 def OnReceiveConditionVer(self, lRet, sMsg):
     MyLogger.instance().logger().debug("%d %s", lRet, sMsg)
     condition_ret = self.ocx.dynamicCall("GetConditionNameList()")
     condition_ret = condition_ret[:-1]  # 마지막 ";" 제거
     condition_list_raw = condition_ret.split(";")
     self.data.조건식_dic.clear()
     for condition_with_index in condition_list_raw:
         if condition_with_index == "":
             continue
         cur = condition_with_index.split("^")
         인덱스 = int(cur[0])
         조건명 = cur[1]
         condition_instance = self.data.get_condition(인덱스)
         condition_instance.조건명 = 조건명
     self.callback.on_data_updated(["조건식_dic"])
Beispiel #46
0
    def on_real_data(self, sJongmokCode, sRealType, sRealData):
        MyLogger.instance().logger().debug("StopLoss. %s", self.balance.종목명)
        if self.is_queued:
            MyLogger.instance().logger().info("is_queued. do nothing")
            return

        if self.balance.보유수량 == 0:
            MyLogger.instance().logger().debug("보유수량 == 0. do nothing")
            return

        수익률 = self.balance.get_return_rate()
        MyLogger.instance().logger().debug("종목명: %s, 수익률: %f, 현재가: %d, 매입가: %d, 보유수량: %d", self.balance.종목명, 수익률, self.balance.현재가, self.balance.매입가, self.balance.보유수량)

        if 수익률 < self.threshold:
            MyLogger.instance().logger().info("StopLoss!!!! 종목명: %s, 보유수량: %d. 수익률: %f < threshold: %f", self.balance.종목명, self.balance.보유수량, 수익률, self.threshold)
            self.on_sell_signal(self.balance.보유수량)
Beispiel #47
0
    def on_balance_item_changed(self, item):
        if not self.is_user_changing_balance:
            return
        row = item.row()
        col = item.column()
        value = item.text()
        MyLogger.instance().logger().info("row:%d, col:%d, val:%s", row, col, value)

        종목코드_item = self.ui.table_current.item(row, 0)
        종목코드 = 종목코드_item.text()
        balance = kiwoom.data.get_balance(종목코드)
        changed_key = Balance.get_table_header()[col]
        if changed_key == "목표보유수량":
            balance.목표보유수량 = int(value)
        else:
            return
Beispiel #48
0
    def on_real_data(self, sJongmokCode, sRealType, sRealData):
        MyLogger.instance().logger().info("StopLoss. %s", self.balance.종목명)
        if self.is_done:
            MyLogger.instance().logger().info("is_done. do nothing")
            return

        if self.balance.보유수량 == 0:
            MyLogger.instance().logger().info("보유수량 == 0. do nothing")
            return

        수익률 = (self.balance.현재가 - self.balance.매입가) / self.balance.매입가
        MyLogger.instance().logger().debug("수익률: %f, 현재가: %d, 매입가: %d, 보유수량: %d", 수익률, self.balance.현재가, self.balance.매입가, self.balance.보유수량)

        if 수익률 < self.threshold:
            MyLogger.instance().logger().info("StopLoss!!!! 보유수량: %d. 수익률: %f < threshold: %f", self.balance.보유수량, 수익률, self.threshold)
            self.on_sell_signal(self.balance.보유수량)
Beispiel #49
0
    def on_condition(self, condition_index, condition_name):
        MyLogger.instance().logger().info("index: %d, name: %s", condition_index, condition_name)
        if self.is_done:
            MyLogger.instance().logger().info("is_done. do nothing")
            return

        if self.balance.보유수량 == 0:
            MyLogger.instance().logger().info("보유수량 == 0. do nothing")
            return

        수익률 = (self.balance.현재가 - self.balance.매입가) / self.balance.매입가
        MyLogger.instance().logger().debug("수익률: %f, 현재가: %d, 매입가: %d, 보유수량: %d", 수익률, self.balance.현재가, self.balance.매입가, self.balance.보유수량)

        if 수익률 > self.threshold:
            MyLogger.instance().logger().info("ConditionSell!!!! 보유수량: %d. 수익률: %f > threshold: %f", self.balance.보유수량, 수익률, self.threshold)
            self.on_sell_signal(self.balance.보유수량)
Beispiel #50
0
    def collect_day_data(self):
        MyLogger.instance().logger().debug("")

        class DayData(threading.Thread):
            def __init__(self, the_ocx, the_condition_value):
                super().__init__()
                self.ocx = the_ocx
                self.condition_value = the_condition_value

            def run(self):
                kospi_code_list_str = self.ocx.dynamicCall("GetCodeListByMarket(QString)", ["0"])
                kospi_code_list = kospi_code_list_str.split(';')
                MyLogger.instance().logger().info("kospi_code_list. len: %d", len(kospi_code_list))
                kosdaq_code_list_str = self.ocx.dynamicCall("GetCodeListByMarket(QString)", ["10"])
                kosdaq_code_list = kosdaq_code_list_str.split(';')
                MyLogger.instance().logger().info("kosdaq_code_list. len: %d", len(kosdaq_code_list))
                code_list = kospi_code_list + kosdaq_code_list
                from datetime import datetime
                기준일자 = datetime.today().strftime("%Y%m%d")
                from glob import glob

                for code in code_list:
                    if len(code) < 3:
                        MyLogger.instance().logger().warning("unexpected code: %s", code)
                        continue

                    temp_list = glob('data/day/' + code + '*.csv')
                    if len(temp_list) >= 1:
                        MyLogger.instance().logger().warning("%s already exist", code)
                        continue

                    time.sleep(1)
                    self.condition_value.acquire()
                    self.ocx.dynamicCall("SetInputValue(QString, QString)", "종목코드", code)
                    self.ocx.dynamicCall("SetInputValue(QString, QString)", "기준일자", 기준일자)
                    self.ocx.dynamicCall("SetInputValue(QString, QString)", "수정주가구분", "1")
                    ret = self.ocx.dynamicCall("CommRqData(QString, QString, int, QString)", "주식일봉조회", "opt10081", 0, constant.SN_데이터_일봉조회)
                    MyLogger.instance().logger().info("CommRqData. code: %s, ret: %d", code, ret)
                    self.condition_value.wait()

                self.condition_value.release()
                MyLogger.instance().logger().info("the end of run()")

        self.condition_value = threading.Condition()
        test_thread = DayData(self.ocx, self.condition_value)
        test_thread.start()
Beispiel #51
0
    def on_load_balance_btn_clicked(self):
        MyLogger.instance().logger().info("")
        f = open("my_list.txt", "r", encoding='utf8')
        data = json.load(f)
        print(data)

        for item in data:
            balance = kiwoom.data.get_balance(item['종목코드'])
            balance.종목명 = item['종목명']
            if not item['목표보유수량']:
                balance.목표보유수량 = item['목표보유수량']
            for k, v in item['매수전략_dic'].items():
                balance.add_buy_strategy(k, v)
            for k, v in item['매도전략_dic'].items():
                balance.add_sell_strategy(k, v)

        self.on_data_updated(["잔고_dic"])
        kiwoom.refresh_interest_balance()
Beispiel #52
0
    def on_real_data(self, sJongmokCode, sRealType, sRealData):
        MyLogger.instance().logger().info("JustBuy")
        if self.is_queued:
            MyLogger.instance().logger().info("is_queued. do nothing")
            return

        if self.balance.목표보유수량 == 0 or self.balance.목표보유수량 <= self.balance.보유수량:
            MyLogger.instance().logger().info("목표보유수량: %d, 보유수량: %d. do nothing", self.balance.목표보유수량, self.balance.보유수량)
            return
        else:
            MyLogger.instance().logger().info("JustBuy!!!! 주문수량: %d", self.balance.목표보유수량 - self.balance.보유수량)
            self.on_buy_signal(self.balance.목표보유수량 - self.balance.보유수량)
Beispiel #53
0
    def OnReceiveRealData(self, sJongmokCode, sRealType, sRealData):
        MyLogger.instance().logger().info("%s, %s, %s", sJongmokCode, sRealType, sRealData)

        if sRealType == "장시작시간":
            MyLogger.instance().logger().info("장시작시간")
            현재시간_str = self.ocx.dynamicCall("GetCommRealData(QString, int)", "장시작시간", 20)  # 체결시간
            현재시간_str = 현재시간_str.strip()
            MyLogger.instance().logger().info("체결시간: %s", 현재시간_str)

            # TODO 현재는 시장가로 주문. 좀 더 나은 전략 필요
            if 현재시간_str == "085500":  ## 8시 55분. 31분터 신호 옴
                for balance in self.data.잔고_dic.values():
                    for 매수전략 in balance.매수전략.values():
                        매수전략.on_time(현재시간_str)

        if sJongmokCode in self.data.잔고_dic:
            if (sRealType == "주식체결"):
                현재가_str = self.ocx.dynamicCall("GetCommRealData(QString, int)", "주식체결", 10)
                현재가 = int(현재가_str.strip())
                현재가 = 현재가 if 현재가 >= 0 else 현재가 * (-1)

                balance = self.data.get_balance(sJongmokCode)
                balance.현재가 = 현재가

                for 매수전략 in balance.매수전략.values():
                    매수전략.on_real_data(sJongmokCode, sRealType, sRealData)

                for 매도전략 in balance.매도전략.values():
                    매도전략.on_real_data(sJongmokCode, sRealType, sRealData)
Beispiel #54
0
    def on_balance_section_clicked(self, row):
        MyLogger.instance().logger().info("row: %d", row)
        rows = []
        for idx in self.ui.table_current.selectedIndexes():
            current_row = idx.row()
            if current_row not in rows:
                rows.append(current_row)

        self.selected_balance.clear()
        for row in rows:
            종목코드_item = self.ui.table_current.item(row, 0)
            if not 종목코드_item:  # 빈칸(None)인 경우
                continue
            종목코드 = 종목코드_item.text()
            balance = kiwoom.data.get_balance(종목코드)
            self.selected_balance.append(balance)

        종목명_list = []
        for balance in self.selected_balance:
            종목명_list.append(balance.종목명)
        selected_balance_str = ",".join(종목명_list)
        self.ui.txt_balance.setText(selected_balance_str)
Beispiel #55
0
 def OnReceiveTrCondition(self, sScrNo, strCodeList, strConditionName, nIndex, nNext):
     MyLogger.instance().logger().info("%s, %s, %s, %d, %d", sScrNo, strCodeList, strConditionName, nIndex, nNext)
     code_list_str = strCodeList[:-1]  # 마지막 ";" 제거
     code_list = code_list_str.split(';')
     MyLogger.instance().logger().info("code_list: %s", code_list)
     for code in code_list:
         name = self.ocx.dynamicCall("GetMasterCodeName(QString)", [code])
         MyLogger.instance().logger().info("code: %s, name: %s", code, name)
Beispiel #56
0
    def on_condition_section_clicked(self, row):
        MyLogger.instance().logger().info("row: %d", row)
        rows = []
        for idx in self.ui.table_condition.selectedIndexes():
            current_row = idx.row()
            if current_row not in rows:
                rows.append(current_row)

        self.selected_condition.clear()
        for row in rows:

            인덱스_item = self.ui.table_condition.item(row, 0)
            if not 인덱스_item:  # 빈칸(None)인 경우
                continue
            인덱스 = int(인덱스_item.text())
            condition = kiwoom.data.get_condition(인덱스)
            self.selected_condition.append(condition)

        조건식_list = []
        for condition in self.selected_condition:
            조건식_list.append(condition.조건명)
        selected_condition_str = ",".join(조건식_list)
        self.ui.txt_condition_select.setText(selected_condition_str)
Beispiel #57
0
    def on_time(self, cur_time_str):
        MyLogger.instance().logger().info("SellOnClosing. time: %s. %s", cur_time_str, self.balance.종목명)
        if self.is_queued:
            MyLogger.instance().logger().info("is_queued. do nothing")
            return

        if self.balance.보유수량 > 0:
            MyLogger.instance().logger().info("SellOnClosing!!!! 주문수량: %d", self.balance.보유수량)
            self.on_sell_signal(self.balance.보유수량)
Beispiel #58
0
    def on_time(self, cur_time_str):
        MyLogger.instance().logger().info("BuyOnOpening. time: %s. %s", cur_time_str, self.balance.종목명)
        if self.is_done:
            MyLogger.instance().logger().info("is_done. do nothing")
            return

        if not self.balance.목표보유수량:
            return

        주문수량 = self.balance.목표보유수량 - self.balance.보유수량

        if self.balance.목표보유수량 == 0 or 주문수량 <= 0:
            MyLogger.instance().logger().info("목표보유수량: %d, 보유수량: %d. do nothing", self.balance.목표보유수량, self.balance.보유수량)
            return

        else:
            MyLogger.instance().logger().info("BuyOnOpening!!!! 주문수량: %d", 주문수량)
            self.on_buy_signal(주문수량)
Beispiel #59
0
 def on_register_real_all_btn_clicked(self):
     MyLogger.instance().logger().info("")
     종목코드_list = []
     for balance in kiwoom.data.잔고_dic.values():
         if len(balance.매도전략) or len(balance.매수전략):
             종목코드_list.append(balance.종목코드)
     if len(종목코드_list):
         종목코드_list_str = ";".join(종목코드_list)
         MyLogger.instance().logger().info("종목코드_list_str %s", 종목코드_list_str)
         kiwoom.set_real_reg(종목코드_list_str)
     else:
         MyLogger.instance().logger().error("전략 있는 종목 없음")
Beispiel #60
0
 def add_sell_strategy(self, the_전략명):
     from kiwoom.strategy.stop_loss import StopLoss
     from kiwoom.strategy.condition_sell import ConditionSell
     if the_전략명 not in self.매도전략:
         if the_전략명 == "sell_stop_loss":
             sell_stop_loss = StopLoss(self)
             self.매도전략[the_전략명] = sell_stop_loss
             MyLogger.instance().logger().info("sell_stop_loss 추가됨. %s", self.종목명)
         elif the_전략명 == "sell_condition_sell":
             sell_condition_sell = ConditionSell(self)
             self.매도전략[the_전략명] = sell_condition_sell
             MyLogger.instance().logger().info("sell_condition_sell 추가됨. %s", self.종목명)
         else:
             MyLogger.instance().logger().wanning("unknown strategy. ignore %s. %s", the_전략명, self.종목명)