예제 #1
0
	def run (self):
		fps = FPS
		print(PRESS_SPACE)
		while True:
			sleep(1./fps)
			if msvcrt.kbhit() and msvcrt.getch()==b' ':
				os_exit(1)
예제 #2
0
파일: __main__.py 프로젝트: Sdoof/blueshift
def run(ctx, start_date, end_date, initial_capital, algo_file, run_mode,
        broker, name, platform, output, show_progress, publish, arglist):
    '''
        Set up the context and trigger the run.
    '''
    try:
        args, kwargs = list_to_args_kwargs(arglist)

        configfile = os_path.expanduser(ctx.obj['config'])
        algo_file = algo_file
        trading_environment = BlueShiftEnvironment(
            name=name,
            config_file=configfile,
            algo_file=algo_file,
            start_date=start_date,
            end_date=end_date,
            initial_capital=initial_capital,
            mode=run_mode,
            broker=broker,
            *args,
            **kwargs)

        run_algo(output,
                 show_progress,
                 publish,
                 trading_environment=trading_environment,
                 *args,
                 **kwargs)
    except BlueShiftException as e:
        click.secho(str(e), fg="red")
        sys_exit(1)
        os_exit(1)
예제 #3
0
파일: __main__.py 프로젝트: Sdoof/blueshift
def config(ctx, root, timezone, broker, broker_id, broker_key, broker_secret):
    '''
        Create a template for Blueshift configuration file with
        the given inputs.
    '''
    try:
        # get the base template
        config = json.loads(generate_default_config())

        # update the dict with supplied parameters.
        root = os_path.expanduser(root)
        config['owner'] = os_environ.get('USERNAME')
        config['api_key'] = ctx.obj.get('api_key', None)
        config['user_workspace']['root'] = root

        # create all directories in root if they do not exists already
        for d in config['user_workspace']:
            if d == 'root':
                if not os_path.exists(root): mkdir(root)
            else:
                full_path = os_path.join(root, config['user_workspace'][d])
                if not os_path.exists(full_path): mkdir(full_path)

        click.echo(json.dumps(config))
    except BlueShiftException as e:
        click.secho(str(e), fg="red")
        sys_exit(1)
        os_exit(1)
예제 #4
0
	def alarm (self):
		if self.mode == "-f" or self.mode == "-l":
			KeyEventThread().start()
			sleep(self.time)
			print(ALARM_STARTED)
			play(self.file)
			os_exit(1)
		else:
			print (HELP)
def exit_on_error(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except:
        try:
            print 'exit_on_error: there was an exception. Printing stacktrace will be tried and then exit'
            print_exc()
        except:
            pass

        # sys.exit() is not used, since that throws an exception, which does not lead to a program
        # halt when used in a dbus callback, see connection.py in the Python/Dbus libraries, line 230.
        os_exit(1)
예제 #6
0
def exit_on_error(func, *args, **kwargs):
	try:
		return func(*args, **kwargs)
	except:
		try:
			print 'exit_on_error: there was an exception. Printing stacktrace will be tryed and then exit'
			print_exc()
		except:
			pass

		# sys.exit() is not used, since that throws an exception, which does not lead to a program
		# halt when used in a dbus callback, see connection.py in the Python/Dbus libraries, line 230.
		os_exit(1)
예제 #7
0
    def restart(self, *args, **kwargs):
        shutdown_msg = 'restart failed, shutting down...'
        try:
            p = Process(getpid())
            for handler in p.get_open_files() + p.connections():
                close(handler.fd)
        except Exception as e:
            self.logger.error(shutdown_msg, 'BlueShift')
            self.graceful_exit(*args, **kwargs)

        python = sys_executable
        execl(python, python, *sys_argv)
        sys_exit(1)
        os_exit(1)
예제 #8
0
    def _create(self, *args, **kwargs):
        '''
            Function to create a trading environment with all objects
            necessary to run the algo.
        '''
        name = kwargs.pop("name", None)
        if name:
            self.name = name
        else:
            self.name = str(uuid.uuid4())

        if if_notebook():
            self.platform = Platform.NOTEBOOK
        elif if_docker():
            self.platform = Platform.CONTAINER
        else:
            self.platform = Platform.CONSOLE

        register_env(self)
        try:
            self.create_config(*args, **kwargs)
            self.extract_env_vars()
            self.create_logger(*args, **kwargs)
            self.create_alert_manager(*args, **kwargs)

            algo_file = kwargs.get("algo_file", None)
            self.get_algo_file(algo_file)

            self.create_calendar()

            # create the broker based on config details.
            mode = kwargs.pop("mode", MODE.BACKTEST)
            mode = self.RUN_MODE_MAP.get(mode, mode)
            self.mode = mode
            self.create_broker(*args, **kwargs)
            self.save_env_vars()
        except BlueShiftException as e:
            print_msg(str(e), _type="error", platform=self.platform)
            sys_exit(1)
            os_exit(1)
예제 #9
0
파일: run.py 프로젝트: Sdoof/blueshift
def run_algo(output, show_progress=False, publish=False, *args, **kwargs):
    """ run algo from parameters """

    trading_environment = kwargs.pop("trading_environment", None)

    if not trading_environment:
        # try to create an environment from the parameters
        try:
            trading_environment = BlueShiftEnvironment(*args, **kwargs)
        except BaseException as e:
            print_msg(str(e), _type="error",
                      platform=Platform.NOTEBOOK if if_notebook() else \
                      Platform.CONSOLE)

            sys_exit(1)
            os_exit(1)

    if not trading_environment:
        print_msg("failed to create a trading environment",
                  _type="error",
                  platform=Platform.NOTEBOOK if if_notebook() else \
                  Platform.CONSOLE)
        sys_exit(1)
        os_exit(1)

    register_env(trading_environment)
    platform = trading_environment.platform

    alert_manager = get_alert_manager()
    broker = trading_environment.broker_tuple
    mode = trading_environment.mode
    algo_file = trading_environment.algo_file

    try:
        algo = TradingAlgorithm(name=trading_environment.name,
                                broker=broker,
                                algo=algo_file,
                                mode=mode)
    except BaseException as e:
        print_msg(str(e), _type="error",
                  platform=Platform.NOTEBOOK if if_notebook() else \
                  Platform.CONSOLE)

        sys_exit(1)
        os_exit(1)

    broker_name = str(broker.broker._name)
    tz = broker.clock.trading_calendar.tz

    if mode == MODE.BACKTEST:
        '''
            print initial messages and run the algo object backtest.
        '''
        length = len(broker.clock.session_nanos)
        print_msg(f"\nStarting backtest with {basename(algo_file)}",
                  _type="warn",
                  platform=platform)

        msg = f"algo: {trading_environment.name}, broker:{broker_name}, timezone:{tz}, total sessions:{length}\n"
        print_msg(msg, _type="info2", platform=platform)
        perfs = algo.back_test_run(alert_manager, publish, show_progress)

        print_msg(f"backtest run complete", _type="info", platform=platform)

        if output:
            perfs.to_csv(output)

        return perfs

    elif mode == MODE.LIVE:
        '''
            For live run, there is no generator. We run the main 
            async event loop inside the Algorithm object itself.
            So all messaging has to be handled there. Here we just
            call the main function and leave it alone to complete.
        '''
        print_msg("\nstarting LIVE", _type="warn", platform=platform)
        msg = "starting LIVE, algo:"+ basename(algo_file) +\
                " with broker:" + broker_name + ", timezone:" + tz + "\n"
        print_msg(msg, _type="none", platform=platform)
        algo.live_run(alert_manager=alert_manager, publish_packets=publish)

    else:
        '''
            Somehow we ended up with unknown mode.
        '''
        print_msg(f"illegal mode supplied.", _type="error", platform=platform)
        sys_exit(1)
        os_exit(1)
예제 #10
0
 def on_close(self, a=''):
     self.running.set()
     print 'close'
     sys_exit()
     os_exit() 
예제 #11
0
 def graceful_exit(self, *args, **kwargs):
     shutdown_msg = 'cannot recover from error, shutting down...'
     self.logger.error(shutdown_msg, 'BlueShift')
     self.run_callbacks()
     sys_exit(1)
     os_exit(1)