Beispiel #1
0
 def __init__(self):
     try:
         from core.strategy import Strategy
         self.strategy = Strategy()
     except Exception as e:
         self.strategy = None
         self.instance_exception = e
Beispiel #2
0
class API:
    def __init__(self):
        try:
            from core.strategy import Strategy
            self.strategy = Strategy()
        except Exception as e:
            self.strategy = None
            self.instance_exception = e

    def generate_actions(self, state):
        actions = []
        add_action = lambda action, args: actions.append({'command': action, 'args': args})
        dummy_action = lambda action, args: action

        my_passengers = state['my_passengers']
        enemy_passengers = state['enemy_passengers']
        my_elevators = state['my_elevators']
        enemy_elevators = state['enemy_elevators']
        my_elevators = [Elevator(add_action, **e) for e in my_elevators]
        enemy_elevators = [Elevator(dummy_action, **e) for e in enemy_elevators]
        my_passengers = [Passenger(add_action, **p) for p in my_passengers]
        enemy_passengers = [Passenger(add_action, **p) for p in enemy_passengers]

        debug = Debug(add_action)
        try:
            if self.strategy:
                self.strategy.set_debug(debug)
                self.strategy.on_tick(my_elevators, my_passengers, enemy_elevators, enemy_passengers)
            else:
                if self.instance_exception:
                    debug.exception(self.instance_exception)
                    self.instance_exception = None
        except Exception as e:
            debug.exception(e)
        return actions
Beispiel #3
0
    def __init__(self):
        super().__init__()
        self.runningState = RunningState.STOP
        self.kiwoom: HughKiwoom = HughKiwoom(self, False)
        self.logger = Logging().logger
        self.strategy_list = {"buy": {"simpleBuy": SimpleBuyStrategy}, "sell": {"simpleSell": SimpleSellStrategy}}
        self.buy_strategy = Strategy()
        self.sell_strategy = Strategy()

        with open('config/config.json') as f:
            self.config = json.load(f)

        self.slack = Slack(self, self.config['SLACK_TOKEN'])

        # 리소스 정의
        self.account = Account()
        self.market = Market()
Beispiel #4
0
class StockWeek(QObject):
    threadLogEvent = QtCore.pyqtSignal(str)
    threadStateEvent = QtCore.pyqtSignal(RunningState)

    def __init__(self):
        super().__init__()
        self.runningState = RunningState.STOP
        self.kiwoom: HughKiwoom = HughKiwoom(self, False)
        self.logger = Logging().logger
        self.strategy_list = {"buy": {"simpleBuy": SimpleBuyStrategy}, "sell": {"simpleSell": SimpleSellStrategy}}
        self.buy_strategy = Strategy()
        self.sell_strategy = Strategy()

        with open('config/config.json') as f:
            self.config = json.load(f)

        self.slack = Slack(self, self.config['SLACK_TOKEN'])

        # 리소스 정의
        self.account = Account()
        self.market = Market()

        # 로그인 요청용 이벤트루프
        # self.login_event_loop = QEventLoop()

    def login(self):
        self.kiwoom.CommConnect(True)
        # self.login_event_loop.exec_()

    def handler_login(self, err_code):
        self.logging(errors(err_code)[1])
        # self.login_event_loop.exit()
        if errors(err_code)[1] == '정상처리':
            self.change_running_state(RunningState.READY)
        else:
            self.change_running_state(RunningState.ERROR)

    def handler_tr(self, screen, rqname, trcode, record, next):
        pass

    def handler_chejan(self, gubun, item_cnt, fid_list):
        pass

    def handler_msg(self, screen, rqname, trcode, msg):
        pass

    def run(self):
        self.change_running_state(RunningState.RUNNING)

        # self.detail_account_info_event_loop.exec_()

        self.buy_strategy.start()
        self.sell_strategy.start()

    def stop(self):
        self.buy_strategy.stop()
        self.sell_strategy.stop()
        self.change_running_state(RunningState.STOP)

    def pause(self):
        self.buy_strategy.stop()
        self.sell_strategy.stop()
        self.change_running_state(RunningState.READY)

    def logging(self, log):
        self.logger.debug(str(log))
        self.threadLogEvent.emit(str(log))
        # self.ui.logging(log)

    def change_running_state(self, state):
        if isinstance(state, RunningState):
            self.runningState = state
            self.logging("state 변경 : " + self.runningState.value)
            self.threadStateEvent.emit(self.runningState)
            # self.ui.change_state_btn(self.runningState)

    def change_buy_strategy(self, name):
        if self.runningState != RunningState.STOP and self.runningState != RunningState.READY:
            self.logging("Stop Pause 후 변경 : 현재상태:" + self.runningState.value)
            return

        self.buy_strategy = self.strategy_list['buy'][name]()
        self.buy_strategy.threadLogEvent.connect(self.logging)
        self.logging("매수전략 변경 : " + name)

    def change_sell_strategy(self, name):
        if self.runningState != RunningState.STOP and self.runningState != RunningState.READY:
            self.logging("Stop Pause 후 변경 : 현재상태:" + self.runningState.value)
            return

        self.sell_strategy = self.strategy_list['sell'][name]()
        self.sell_strategy.threadLogEvent.connect(self.logging)
        self.logging("매매전략 변경 : " + name)

    def manual_request(self, stock_code, order_type, is_good_price, price, quantity):
        try:
            self.logging(
                f'"stock_code:{stock_code} order_type:{order_type} is_good_price:{is_good_price} price:{price} quantity:{quantity}')
            # "005930"

            # 계좌번호는 11을 붙여서 10자리임
            account_list = self.kiwoom.GetLoginInfo("ACCNO")
            account = account_list[0]
            # opw00001 요청
            df = self.kiwoom.block_request("opw00001", 계좌번호=account, 비밀번호="", 비밀번호입력매체구분="00",
                                           조회구분=1, output="예수금상세현황", next=0)

            df.to_excel('예수금상세현황.xlsx')
            for column in df.columns:
                print(column, df.loc[0][column])
        except Exception as e:
            self.logging("except" + str(e))

    def request_load_account(self):
        account_list = self.kiwoom.GetLoginInfo("ACCNO")  # 계좌번호 반환
        self.logging(f"account_list:{account_list}")

    def onclick_test_btn1(self):
        self.logging('onclick_test_btn1')
        try:

            전일가 = self.kiwoom.GetMasterLastPrice("005930")
            self.logging(전일가)

            종목상태 = self.kiwoom.GetMasterStockState("005930")
            self.logging(종목상태)

            df = self.kiwoom.block_request("opt10001",
                                      종목코드="005930",
                                      output="주식기본정보",
                                      next=0)

            now = datetime.datetime.now()
            date_time = now.strftime('%Y%m%d, %H:%M:%S')
            self.logging(date_time + ' : ' + df['현재가'][0])

        except Exception as e:
            self.logging("except" + str(e))

    def onclick_test_btn2(self):
        self.logging('onclick_test_btn2')
        try:
            account_no = self.kiwoom.GetLoginInfo("ACCNO")[0]
            self.logging(account_no)
            trdata = self.kiwoom.block_request("opw00001", 계좌번호=account_no, 비밀번호="0000", 비밀번호입력매체구분="00", 조회구분=1,output="예수금상세현황", next=0)

        except Exception as e:
            self.logging("except" + str(e))

    def onclick_test_btn3(self):
        self.logging('onclick_test_btn3')
        try:
            self.slack.notification(text="pretext test2")

        except Exception as e:
            self.logging("except slack " + str(e))
        self.logging(self.account.str_account_stock())
Beispiel #5
0
def run(config, source_code=None, user_funcs=None):
    env = Environment(config)
    persist_helper = None
    init_succeed = False
    mod_handler = ModHandler()

    try:
        if source_code is not None:
            env.set_strategy_loader(SourceCodeStrategyLoader(source_code))
        elif user_funcs is not None:
            env.set_strategy_loader(UserFuncStrategyLoader(user_funcs))
        else:
            env.set_strategy_loader(
                FileStrategyLoader(config.base.strategy_file))
        env.set_global_vars(GlobalVars())
        mod_handler.set_env(env)
        mod_handler.start_up()

        if not env.data_source:
            env.set_data_source(BaseDataSource(config.base.data_bundle_path))

        env.set_data_proxy(DataProxy(env.data_source))
        Scheduler.set_trading_dates_(env.data_source.get_trading_calendar())
        scheduler = Scheduler(config.base.frequency)
        mod_scheduler._scheduler = scheduler

        env._universe = StrategyUniverse()

        _adjust_start_date(env.config, env.data_proxy)

        _validate_benchmark(env.config, env.data_proxy)

        broker = env.broker
        assert broker is not None
        env.portfolio = broker.get_portfolio()
        env.benchmark_portfolio = create_benchmark_portfolio(env)

        event_source = env.event_source
        assert event_source is not None

        bar_dict = BarMap(env.data_proxy, config.base.frequency)
        env.set_bar_dict(bar_dict)

        if env.price_board is None:
            from core.bar_dict_price_board import BarDictPriceBoard
            env.price_board = BarDictPriceBoard()

        ctx = ExecutionContext(const.EXECUTION_PHASE.GLOBAL)
        ctx._push()

        # FIXME
        start_dt = datetime.datetime.combine(config.base.start_date,
                                             datetime.datetime.min.time())
        env.calendar_dt = start_dt
        env.trading_dt = start_dt

        env.event_bus.publish_event(Event(EVENT.POST_SYSTEM_INIT))

        scope = create_base_scope()
        scope.update({"g": env.global_vars})

        apis = api_helper.get_apis(config.base.account_list)
        scope.update(apis)

        scope = env.strategy_loader.load(scope)

        if env.config.extra.enable_profiler:
            enable_profiler(env, scope)

        ucontext = StrategyContext()
        user_strategy = Strategy(env.event_bus, scope, ucontext)
        scheduler.set_user_context(ucontext)

        if not config.extra.force_run_init_when_pt_resume:
            with run_with_user_log_disabled(disabled=config.base.resume_mode):
                user_strategy.init()

        if config.extra.context_vars:
            for k, v in six.iteritems(config.extra.context_vars):
                setattr(ucontext, k, v)

        if config.base.persist:
            persist_provider = env.persist_provider
            persist_helper = PersistHelper(persist_provider, env.event_bus,
                                           config.base.persist_mode)
            persist_helper.register('core', CoreObjectsPersistProxy(scheduler))
            persist_helper.register('user_context', ucontext)
            persist_helper.register('global_vars', env.global_vars)
            persist_helper.register('universe', env._universe)
            if isinstance(event_source, Persistable):
                persist_helper.register('event_source', event_source)
            persist_helper.register('portfolio', env.portfolio)
            if env.benchmark_portfolio:
                persist_helper.register('benchmark_portfolio',
                                        env.benchmark_portfolio)
            for name, module in six.iteritems(env.mod_dict):
                if isinstance(module, Persistable):
                    persist_helper.register('mod_{}'.format(name), module)
            # broker will restore open orders from account
            if isinstance(broker, Persistable):
                persist_helper.register('broker', broker)

            persist_helper.restore()
            env.event_bus.publish_event(Event(EVENT.POST_SYSTEM_RESTORED))

        init_succeed = True

        # When force_run_init_when_pt_resume is active,
        # we should run `init` after restore persist data
        if config.extra.force_run_init_when_pt_resume:
            assert config.base.resume_mode == True
            with run_with_user_log_disabled(disabled=False):
                user_strategy.init()

        from core.executor import Executor
        Executor(env).run(bar_dict)
        # print(env.__dict__)
        if env.profile_deco:
            output_profile_result(env)

        result = mod_handler.tear_down(const.EXIT_CODE.EXIT_SUCCESS)
        system_log.debug(_(u"strategy run successfully, normal exit"))
        return result
    except CustomException as e:
        if init_succeed and env.config.base.persist and persist_helper:
            persist_helper.persist()

        user_detail_log.exception(_(u"strategy execute exception"))
        user_system_log.error(e.error)

        better_exceptions.excepthook(e.error.exc_type, e.error.exc_val,
                                     e.error.exc_tb)

        mod_handler.tear_down(const.EXIT_CODE.EXIT_USER_ERROR, e)
    except Exception as e:
        if init_succeed and env.config.base.persist and persist_helper:
            persist_helper.persist()

        exc_type, exc_val, exc_tb = sys.exc_info()
        user_exc = create_custom_exception(exc_type, exc_val, exc_tb,
                                           config.base.strategy_file)

        better_exceptions.excepthook(exc_type, exc_val, exc_tb)
        user_system_log.error(user_exc.error)
        code = const.EXIT_CODE.EXIT_USER_ERROR
        if not is_user_exc(exc_val):
            system_log.exception(_(u"strategy execute exception"))
            code = const.EXIT_CODE.EXIT_INTERNAL_ERROR
        else:
            user_detail_log.exception(_(u"strategy execute exception"))

        mod_handler.tear_down(code, user_exc)