Esempio n. 1
0
 def __init__(self):
     service = Providers.config().launch_service
     print(service)
     if service == "core":
         srv_thread = Thread(target=Core.start, args=(123, ))
         srv_thread.setDaemon(True)
         srv_thread.start()
         # Ждем окончания
         srv_thread.join()
     elif service == "api":
         pass
Esempio n. 2
0
	def __init__(self):
		service = Providers.config().launch_service
		if service == "api":
			print("Started on 8089")
			waitress.serve(app, port=8089, _quiet=True)
			#
			# Создаем свой логгер
			logger = logging.getLogger('waitress2')
			formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
			ch = logging.StreamHandler()
			ch.setLevel(logging.DEBUG)
			ch.setFormatter(formatter)
			logger.addHandler(ch)
Esempio n. 3
0
 def up(worker_id):
     config = Providers.config()
     service = config.launch_service
     if service:
         task = Task()
         task.user_id = 0  # TODO: Create real users
         task.setting_id = Setting.get_default().id
         task.worker_id = worker_id
         task.is_enabled = True
         task.service_name = service
         task.params = Tasks.get_params(service)
         task.start_at = time.time()
         task.save()
Esempio n. 4
0
    def __init__(self, task):
        self.task = task
        self.instrument = task.setting.instrument
        start = self.task.get_param("start")
        end = self.task.get_param("end")
        quotations = Quotation.get_from_interval(start, end,
                                                 self.instrument.id)
        self.task.update_status("checker_total_quotations", len(quotations))
        last_quotation = None

        if Providers.config().flush_history:
            Prediction.empty_table(task)
            Pattern.empty_table(task)

        Signal.empty_table(task)

        if len(quotations) > 0:
            checked_quotations = self.task.get_param(
                "checker_checked_quotations")
            if not checked_quotations:
                checked_quotations = 0

            for row in quotations:

                analyzer = Analyzer(task)
                analyzer.quotation = row
                analyzer.do_analysis()

                last_quotation = analyzer.quotation

                Prediction.calculation_cost_for_topical(task, last_quotation)
                Controller.update_expired_signals(self.task, last_quotation)

                checked_quotations += 1
                if checked_quotations % 10 == 0:
                    # Обновляем параметры стоимости прогнозов
                    self.task.update_status("checker_checked_quotations",
                                            checked_quotations)

                # Запускаем демона для проверки кеша и получения результата торгов
                self.checker_predictions(last_quotation)
                if checked_quotations % 100 == 0:
                    success_percent = Signal.get_success_percent(self.task)
                    print(datetime.datetime.fromtimestamp(last_quotation.ts),
                          success_percent)

            # Обновляем параметры стоимости прогнозов
            if last_quotation:
                self.checker_predictions(last_quotation)
Esempio n. 5
0
 def save_many(patterns: list):
     incr = 1
     if Providers.config().no_write:
         incr = 0
     cursor = Providers.db().get_cursor()
     query = 'INSERT INTO patterns (setting_id,task_id,time_bid,sequence,sequence_duration,' \
             'used_count,calls_count,' + \
             'puts_count,same_count,trend,range_max_change_cost,' + \
             'range_max_avg_change_cost,call_max_change_cost,put_max_change_cost,' + \
             'call_max_avg_change_cost, put_max_avg_change_cost,range_sum_max_change_cost,' + \
             'call_sum_max_change_cost, put_sum_max_change_cost,count_change_cost,' + \
             'delay,expires,history_num,created_at,trend_max_call_count,trend_max_put_count) VALUES ' + \
             ','.join(v.__tuple_str() for v in patterns) + \
             'ON CONFLICT (sequence,setting_id,time_bid,expires,history_num)' + \
             'DO UPDATE SET used_count=patterns.used_count + ' + str(incr) + ' RETURNING *'
     cursor.execute(query)
     Providers.db().commit()
     res = cursor.fetchall()
     if res:
         return res
     return []
Esempio n. 6
0
 def __init__(self):
     self.launch()
     try:
         if self.worker:
             Fixtures.execute_fixtures()
             Fixtures.create_test_task(self.worker.id)
             Dispatcher(self.worker.id).start_tracking()
     finally:
         ex_type, ex, tb = sys.exc_info()
         tb_list = traceback.extract_tb(tb)
         code = "WithoutErrors"
         if ex_type:
             code = str(ex_type.__name__)
         description = ""
         if ex:
             description = str(ex)
         if self.worker:
             self.terminate(code, tb_list, description)
         if Providers.config().debug:
             traceback.print_tb(tb)
             if ex_type:
                 print(code, description)
         sys.exit(0)
Esempio n. 7
0
    def check_expired_predictions(task, quotation):
        timestamp = quotation.ts

        if Providers.config().no_write:
            Prediction.get_expired(task, timestamp)
        else:
            ended_predictions = Prediction.get_expired(task, timestamp)
            if ended_predictions:
                # Формируем массив патернов для исключения повторения
                taken_patterns = {}
                for prediction in ended_predictions:
                    # Закрываем стоимость прогноза
                    prediction.expiration_cost = quotation.value
                    prediction.expiration_ask = quotation.ask
                    prediction.expiration_bid = quotation.bid

                    # Получаем паттерн с массива полученных патернов
                    if prediction.pattern_id not in taken_patterns:
                        taken_patterns[
                            prediction.pattern_id] = prediction.pattern

                    pattern = taken_patterns[prediction.pattern_id]
                    # Рассчитываем аттрибуты стоимости
                    pattern.calculation_cost_from_prediction(prediction)

                    if quotation.value < prediction.created_cost:
                        pattern.puts_count += 1
                        if pattern.trend < 0:
                            pattern.trend -= 1
                        else:
                            pattern.trend = -1

                        if pattern.trend_max_put_count < abs(pattern.trend):
                            pattern.trend_max_put_count = abs(pattern.trend)

                    if quotation.value > prediction.created_cost:
                        pattern.calls_count += 1
                        if pattern.trend > 0:
                            pattern.trend += 1
                        else:
                            pattern.trend = 1

                        if pattern.trend_max_call_count < pattern.trend:
                            pattern.trend_max_call_count = pattern.trend

                    if quotation.value == prediction.created_cost:
                        pattern.same_count += 1
                        pattern.trend = 0

                    if abs(
                            pattern.trend
                    ) >= task.setting.signaler_min_repeats and pattern.delay == 0:
                        pattern.delay = task.setting.signaler_delay_on_trend
                    if pattern.delay > 0:
                        pattern.delay -= 1

                Prediction.save_many(ended_predictions)

                # Обновляем паттерн и устанавливаем счетчики
                if len(taken_patterns) > 0:
                    for item in taken_patterns:
                        taken_patterns[item].update()