def PrintBoardToConsole(self): console_print() console_print() for r in self.board_array: for c in r: prnt(c + ' ') prnt('\n')
def fonbet_get_hist(FONBET_USER): global fonbet_bet_min, balance_str, balance_int prnt('Фонбет: делаю выгрузку') is_get_list = list() coupon_list = dict() fonbet = FonbetBot(FONBET_USER) if fonbet.get_balance() >= 0: balance_int += fonbet.get_balance() #+ fonbet.get_balance('in_play') balance_str = balance_str + 'Фонбет: ' + int_to_str(fonbet.get_balance( )) + '' + '\n' #+ int_to_str(fonbet.get_balance('in_play')) + '\n' balance_str = balance_str + 'Группа лимита: ' + str( fonbet.limit_group) + '\n' balance_str = balance_str + 'Блокировки:\n' balance_str = balance_str + '- ставки: ' + str( fonbet.live_blocked) + '\n' balance_str = balance_str + '- вывода: ' + str( fonbet.pay_blocked) + '\n' balance_str = balance_str + '- продажи: ' + str( fonbet.sell_blocked) + '\n' fonbet.sign_in() data = fonbet.get_operations(500) for operation in data.get('operations'): reg_id = operation.get('marker') if reg_id not in is_get_list and reg_id >= fonbet_bet_min: is_get_list.append(reg_id) bet_info = fonbet.get_coupon_info(reg_id) try: val = datetime.fromtimestamp(bet_info.get('regTime')) date_str = val.strftime('%Y-%m-%d %H:%M:%S') oper_time = date_str coupon_list[reg_id] = { 'time': str(oper_time), 'kof': str(bet_info.get('coupons')[0]['bets'][0]['factor']), 'sum_bet': str(bet_info.get('sum')), 'profit': str(bet_info.get('win')), 'result': str(bet_info.get('coupons')[0]['bets'][0]['result']), 'name': str(bet_info.get('coupons')[0]['bets'][0]['eventName']), 'status': str(bet_info.get('state')) } except Exception as e: print(e) finally: time.sleep(random.randint(2, 3)) return coupon_list
def get_kof_olimp(obj, olimp_match, olimp_k, proxies, place): obj['olimp'] = 0 obj['olimp_time_req'] = 0 sc = '' try: r_olimp_coef1, sc, rime_req = get_olimp_info(olimp_match, olimp_k, proxies, place) obj['olimp_time_req'] = rime_req obj['olimp'] = r_olimp_coef1 except Exception as e: prnt( 'FORK_RECHECK.PY - olimp-error: ошибка при повторной проверке коэф-та: ' + str(e)) if obj['olimp'] is None: obj['olimp'] = 0 return obj
def requests_retry_session_post(url: str, headers=None, data=None, json=None, verify=None, timeout=None, proxies=None): prnt('retry_requests: execute requests_retry_session_post, url={}'.format( url)) resp = requests_retry_session().post(url=url, headers=headers, data=data, json=json, verify=False, timeout=timeout, proxies=proxies) cnt_retry = 0 return resp
def inner_wrapper(*args, **kwargs): final_excep = None for counter in range(times): if counter > 0: time.sleep(delay) final_excep = None try: value = function(*args, **kwargs) return value except (exceptions) as e: final_excep = e prnt('retry_requests 1: ' + str(final_excep) + ', args=' + str(*args) + ', kwargs=' + str(**kwargs)) pass if final_excep is not None: prnt('retry_requests 2: ' + str(final_excep) + ', args=' + str(*args) + ', kwargs=' + str(**kwargs)) raise final_excep
def get_kof_fonbet(obj, match_id, factor_id, param): match_id = int(match_id) factor_id = int(factor_id) obj['fonbet'] = 0 obj['fonbet_time_req'] = 0 sc = '' dop_stat = dict() if param: param = int(param) try: obj['fonbet'], sc, rime_req, dop_stat = get_fonbet_info( match_id, factor_id, param) obj['fonbet_time_req'] = rime_req except Exception as e: prnt( 'FORK_RECHECK.PY - fonbet-error: ошибка при повторной проверке коэф-та: ' + str(e)) obj['fonbet'] = 0 if obj['fonbet'] is None: obj['fonbet'] = 0 return obj
def get_olimp_info(id_matche, olimp_k, sport_id, proxies=None, place=None): prnt( 'get_olimp_info: id_matche=' + str(id_matche) + ';sport_id=' + str(sport_id) + ';olimp_k=' + str(olimp_k) + ';proxies=' + str(proxies), 'hide') bet_into = {} olimp_data = copy.deepcopy(ol_payload) olimp_data.update({"live": 1, "sport_id": sport_id}) olimp_data.update({'id': id_matche}) if place == 'pre': olimp_data.update({'live': 0}) olimp_stake_head = copy.deepcopy(ol_headers) olimp_stake_head.update(get_xtoken_bet(olimp_data)) olimp_stake_head.pop('Accept-Language', None) prnt('FORK_RECHECK.PY: get_olimp_info rq: ' + str(olimp_data), 'hide') res = requests_retry_session().post( # ol_url_api.format('10', 'stakes/'), ol_url_api.format('stakes/'), data=olimp_data, headers=olimp_stake_head, timeout=10, verify=False, proxies=proxies) prnt('FORK_RECHECK.PY: get_olimp_info rs: ' + str(res.text), 'hide') resp = res.json() if not resp.get('error', {}).get('err_code', 0): stake = resp.get('data', {}) bet_into['ID'] = id_matche is_block = '' if place == 'pre': if stake: is_block = stake.get('ms', False) else: is_block = False else: if str(stake.get('ms', '')) == '1': is_block = True # 1 - block, 2 - available # prnt('Олимп: ставки приостановлены: http://olimp.com/app/event/live/1/' + str(stake.get('id', ''))) bet_into['BLOCKED'] = is_block prnt('olimp kof is blocked: ' + str(is_block)) minutes = "-1" try: minutes = re.findall('\d{1,2}\"', stake.get('scd', ''))[0].replace('"', '') except: pass bet_into['MINUTES'] = minutes # startTime=datetime.datetime.strptime(stake.get('dt',''), "%d.%m.%Y %H:%M:%S") # currentTime=datetime.datetime.strptime(datetime.datetime.now(pytz.timezone('Europe/Moscow')).strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S") # timeDif = currentTime-startTime # minuts bet_into['SCORE'] = stake.get('sc', '0:0') # .get('sc', '0:0').split(' ')[0] for c in stake.get('it', []): # del: угловые # if c.get('n','') in ['Main Bets', 'Goals', 'Corners', 'Individual total', 'Additional total']: # if c.get('n', '').replace(' ', '').lower() in ['основные', 'голы', 'угловые', 'инд.тотал', 'доп.тотал', 'исходыпотаймам']: group_kof = c.get('n', '').replace(' ', '').lower() group_kof = group_kof.replace('азиатские', '') if group_kof in [ 'основные', 'голы', 'инд.тотал', 'доп.тотал', 'исходыпотаймам', 'победасучетомфоры', 'форы', 'тоталы', 'инд.тоталы' ]: for d in c.get('i', []): if 'обе забьют: '.lower() \ in d.get('n', '').lower() \ or 'забьет: '.lower() \ in d.get('n', '').lower() \ or 'никто не забьет: '.lower() \ in d.get('n', '').lower() \ or 'победа '.lower() \ in d.get('n', '').lower() \ or d.get('n', '').lower().endswith(' бол') \ or d.get('n', '').lower().endswith(' мен') \ or 'с форой'.lower() \ in d.get('n', '').lower() \ or 'первая не проиграет'.lower() \ in d.get('n', '').lower() \ or 'вторая не проиграет'.lower() \ in d.get('n', '').lower() \ or 'ничьей не будет' \ in d.get('n', '').lower() \ or 'ничья'.lower() \ in d.get('n', '').lower() \ or 'форы' in group_kof: if 'форы' in group_kof: key_r = d.get('n', '').replace( stake.get('c1', ''), 'П1сфорой').replace(stake.get('c2', ''), 'П2сфорой') key_r = key_r.replace(' ', '') else: key_r = d.get('n', '').replace( stake.get('c1', ''), 'Т1').replace(stake.get('c2', ''), 'Т2') olimp_factor_short = str([ abbreviations[c.replace(' ', '')] if c.replace( ' ', '') in abbreviations.keys() else c.replace(' ', '') if '(' not in c.replace( ' ', '') else to_abb(c) for c in [key_r] ][0]) val_kof = d.get('v', '') if is_block: val_kof = 0 bet_into[olimp_factor_short] = val_kof else: is_block = True k = bet_into.get(olimp_k, 0) if is_block: k = 0 try: sc = bet_into.get('SCORE', '0:0').split(' ')[0] except: sc = '0' prnt('olimp is_block: ' + str(is_block)) prnt('olimp score: ' + sc) prnt('olimp bet_into: ' + str(bet_into)) prnt('olimp k: ' + str(k)) prnt('FORK_RECHECK.PY: get_olimp_info end work', 'hide') return k, sc, round(res.elapsed.total_seconds(), 2)
def get_fonbet_info(match_id, factor_id, param, bet_type=None): dop_stat = dict() sc1 = None sc2 = None prnt('get_fonbet_info: match_id:{}, factor_id:{}, param:{}, bet_type:{}'. format(match_id, factor_id, param, bet_type)) header = copy.deepcopy(fb_headers) url = url_fonbet + "/line/eventView?eventId=" + str(match_id) + "&lang=ru" prnt('FORK_RECHECK.PY: get_fonbet_info rq: ' + url + ' ' + str(header), 'hide') resp = requests_retry_session().get(url, headers=header, timeout=10, verify=False) prnt('FORK_RECHECK.PY: get_fonbet_info rs: ' + str(resp.text), 'hide') res = resp.json() result = res.get('result') if result == "error": prnt('fonbet err : ' + str(res)) return 0, '0:0', round(resp.elapsed.total_seconds(), 2), {} for event in res.get("events"): if event.get('id') == match_id: sc = event.get('score', '0:0').replace('-', ':') period = 1 time_break_fonbet = False if re.match('\(\d+:\d+\)', event.get('scoreComment', '').replace('-', ':').replace(' ', '')) and \ str(event.get('timer', '')) == '45:00' and \ event.get('timerSeconds', 0) == 45.0: time_break_fonbet = True period = 2 elif re.match('\(\d+:\d+\)', event.get('scoreComment', '').replace('-', ':').replace(' ', '')) and \ event.get('timerSeconds', 0) / 60 > 45.0: period = 2 try: sc1 = int(sc.split(':')[0]) except: pass try: sc2 = int(sc.split(':')[1]) except: pass dop_stat = { 'cur_score': sc, 'sc1': sc1, 'sc2': sc2, '1st_half_score': event.get('scoreComment'), 'minutes': round(event.get('timerSeconds', 0) / 60) + (event.get('timerSeconds', 0) % 60 / 100), 'timer': event.get('timer'), 'period': period, 'timebreak': time_break_fonbet } if bet_type: dop_stat.update({'vector': get_vector(bet_type, sc1, sc2)}) for cat in event.get('subcategories'): for kof in cat.get('quotes'): if kof.get('factorId') == factor_id: if param: err_str = None if kof.get('pValue') != param: prnt( 'Изменилась тотал ставки, param не совпадает: ' + 'new: ' + str(kof.get('pValue')) + ', old: ' + str(param)) if bet_type: prnt('поиск нового id тотала: ' + bet_type) new_wager = get_new_bets_fonbet(match_id, proxies={}) new_wager = new_wager.get( str(match_id), {}).get('kofs', {}).get(bet_type) if new_wager: prnt('Тотал найден: ' + str(new_wager)) k = new_wager.get('value', 0) sc = new_wager.get('score', '0:0').replace( '-', ':') return k, sc, round( resp.elapsed.total_seconds(), 2), dop_stat else: err_str = 'Тотал не найден: ' + str( new_wager) else: err_str = 'Тип ставки, например 1ТМ(2.5) - не задан: bet_type:' + bet_type if err_str: prnt(err_str) raise BetIsLost(err_str) k = kof.get('value', 0) prnt('fonbet kof is blocked ' + str(kof.get('blocked', 'None'))) if kof.get('blocked'): prnt('fonbet kof is blocked ' + str(kof)) k = 0 prnt('fonbet score: ' + sc) dop_stat.update({'val': k}) prnt('FORK_RECHECK.PY: get_olimp_info end work', 'hide') return k, sc, round(resp.elapsed.total_seconds(), 2), dop_stat
def olimp_get_hist(OLIMP_USER): global olimp_bet_min, balance_str, balance_int prnt('Олимп: делаю выгрузку') """ # 0111 не расчитанные, выигранные и проигранные # 0011 выигранные и проигранные # 0001 проигранные # 0010 выигранные и выкупденые # 0100 не расчитанные # 0000 Галки сняты: выиграл и продал """ def get_chank(offset=0): coupot_list_chank = dict() bet_list = olimp.get_history_bet(filter="0111", offset=offset).get('bet_list') for bets in bet_list: if bets.get('bet_id') >= olimp_bet_min: ts = int(bets.get('dttm')) # if you encounter a "year is out of range" error the timestamp # may be in milliseconds, try `ts /= 1000` in that case val = datetime.fromtimestamp(ts) date_str = val.strftime('%Y-%m-%d %H:%M:%S') reg_id = bets.get('bet_id') coupot_list_chank[reg_id] = { 'time': str(date_str), 'kof': str(bets.get('final_odd')), 'sum_bet': str(bets.get('total_bet')), 'profit': str(bets.get('pay_sum')), 'result': str(bets.get('result_text')), 'name': str(bets.get('events')[0].get('matchname')), 'status': str(bets.get('calc_cashout_sum')) } return coupot_list_chank coupot_list = dict() olimp = OlimpBot(OLIMP_USER) if olimp.get_balance() >= 0: in_play = olimp.get_balance('in_play') balance_int += olimp.get_balance() + in_play if in_play: balance_str = balance_str + 'Олимп: ' + int_to_str( olimp.get_balance()) + '/' + int_to_str(in_play) + '\n' else: balance_str = balance_str + 'Олимп: ' + int_to_str( olimp.get_balance()) + '\n' data = olimp.get_history_bet(filter="0011", offset=0) count = data.get('count') offset = ceil(count / 10) + 1 is_break = False for n in range(0, offset): if not is_break: js = get_chank(n) for id in js.keys(): if id <= olimp_bet_min: is_break = True coupot_list.update(js) time.sleep(random.randint(2, 3)) return coupot_list
def export_hist(OLIMP_USER, FONBET_USER): global file_name global olimp_bet_min global fonbet_bet_min global ACC_ID, USER_ID global balance_str, balance_int csv_name = datetime.now().strftime("%d_%m_%Y") + '_' + str( ACC_ID) + '_statistics.csv' cur_date_str = datetime.now().strftime("%d_%m_%Y") if os.path.isfile(file_name): with open(file_name, encoding='utf-8') as f: for line in f.readlines(): fork = json.loads(line) for id, info in fork.items(): if info['fonbet'].get('reg_id', fonbet_bet_min): if int(info['fonbet'].get( 'reg_id', fonbet_bet_min)) < fonbet_bet_min: fonbet_bet_min = info['fonbet'].get('reg_id', '') if info['olimp'].get('reg_id', olimp_bet_min): if int(info['olimp'].get( 'reg_id', olimp_bet_min)) < olimp_bet_min: olimp_bet_min = info['olimp'].get('reg_id', '') out = "" o_list = olimp_get_hist(OLIMP_USER) f_list = fonbet_get_hist(FONBET_USER) all_banalce_str = '*Общий баланс: ' + int_to_str(balance_int) + '*' balance_msg = all_banalce_str + '\n' + balance_str balance_msg = balance_msg.strip() db_model.send_message_bot(USER_ID, str(ACC_ID) + ': ' + balance_msg, ADMINS) ol_list = json.loads(json.dumps(o_list, ensure_ascii=False)) fb_list = json.loads(json.dumps(f_list, ensure_ascii=False)) # print(json.dumps(ol_list, ensure_ascii=False)) # print(json.dumps(fb_list, ensure_ascii=False)) # # fb_list = {"15001529116": {"time": "2019-03-17 08:16:39", "kof": "1.55", "sum_bet": "650.0", "profit": "0.0", "result": "lose", "name": "Саутерн Таблеландс Юн - УК Пумас: Обе забьют", "status": "calculated"}, "15001533448": {"time": "2019-03-17 08:17:23", "kof": "2.90", "sum_bet": "345.0", "profit": "1001.0", "result": "win", "name": "Саутерн Таблеландс Юн - УК Пумас", "status": "calculated"}, "15001349429": {"time": "2019-03-17 07:47:44", "kof": "1.30", "sum_bet": "780.0", "profit": "1014.0", "result": "win", "name": "Альянса - Сонсонате: Сонсонате забьет", "status": "calculated"}, "15000795396": {"time": "2019-03-17 06:18:07", "kof": "1.70", "sum_bet": "595.0", "profit": "1012.0", "result": "win", "name": "Энвигадо - Рионегро Агилас (Дорадос)", "status": "calculated"}, "15001086039": {"time": "2019-03-17 07:03:01", "kof": "20.00", "sum_bet": "50.0", "profit": "0.0", "result": "lose", "name": "Сан Антонио ФК - Портленд-2", "status": "calculated"}, "14999742887": {"time": "2019-03-17 03:50:59", "kof": "2.25", "sum_bet": "450.0", "profit": "1013.0", "result": "win", "name": "Универсидад Католика - Делфин", "status": "calculated"}, "14998113571": {"time": "2019-03-17 01:59:54", "kof": "3.15", "sum_bet": "315.0", "profit": "0.0", "result": "lose", "name": "Унион Комерсио - Универсидад Сан-Мартин: Обе забьют", "status": "calculated"}, "14996690959": {"time": "2019-03-17 00:54:00", "kof": "1.88", "sum_bet": "530.0", "profit": "530.0", "result": "return", "name": "Торино - Болонья", "status": "calculated"}, "14995655551": {"time": "2019-03-17 00:17:53", "kof": "1.90", "sum_bet": "530.0", "profit": "0.0", "result": "lose", "name": "Анжер - Амьен: Амьен забьет", "status": "calculated"}, "14995638289": {"time": "2019-03-17 00:17:14", "kof": "4.20", "sum_bet": "240.0", "profit": "0.0", "result": "lose", "name": "Анжер - Амьен", "status": "calculated"}, "14997716191": {"time": "2019-03-17 01:39:11", "kof": "2.50", "sum_bet": "420.0", "profit": "1050.0", "result": "win", "name": "Ольмедо - Гуаякиль С", "status": "calculated"}, "14994775175": {"time": "2019-03-16 23:45:07", "kof": "1.75", "sum_bet": "585.0", "profit": "0.0", "result": "lose", "name": "Унион Санта-Фе - Ланус: Ланус забьет", "status": "calculated"}, "14994440566": {"time": "2019-03-16 23:31:13", "kof": "3.00", "sum_bet": "335.0", "profit": "0.0", "result": "lose", "name": "Брессюир - Монморийон: Монморийон забьет", "status": "calculated"}, "14993925090": {"time": "2019-03-16 23:13:31", "kof": "1.78", "sum_bet": "570.0", "profit": "1015.0", "result": "win", "name": "Херенвен - Графсхап", "status": "calculated"}, "14994084766": {"time": "2019-03-16 23:19:33", "kof": "1.45", "sum_bet": "700.0", "profit": "1015.0", "result": "win", "name": "Атлетик Бильбао - Атлетико Мадрид", "status": "calculated"}, "14994110354": {"time": "2019-03-16 23:20:22", "kof": "2.10", "sum_bet": "470.0", "profit": "987.0", "result": "win", "name": "Витория Гимарайнш - Боавишта: Боавишта забьет", "status": "calculated"}, "14994170306": {"time": "2019-03-16 23:22:17", "kof": "1.75", "sum_bet": "580.0", "profit": "1015.0", "result": "win", "name": "Суонси - Манчестер С", "status": "calculated"}, "14994146836": {"time": "2019-03-16 23:21:32", "kof": "1.43", "sum_bet": "705.0", "profit": "1008.0", "result": "win", "name": "Суонси - Манчестер С", "status": "calculated"}, "14993741171": {"time": "2019-03-16 23:06:57", "kof": "2.35", "sum_bet": "420.0", "profit": "0.0", "result": "lose", "name": "Атлетик Бильбао - Атлетико Мадрид", "status": "calculated"}, "14993367286": {"time": "2019-03-16 22:54:51", "kof": "1.88", "sum_bet": "530.0", "profit": "0.0", "result": "lose", "name": "Атлетик Бильбао - Атлетико Мадрид", "status": "calculated"}, "14992840796": {"time": "2019-03-16 22:37:34", "kof": "1.14", "sum_bet": "880.0", "profit": "1003.0", "result": "win", "name": "Суонси - Манчестер С", "status": "calculated"}, "14993723581": {"time": "2019-03-16 23:06:17", "kof": "2.75", "sum_bet": "370.0", "profit": "1018.0", "result": "win", "name": "Санлукено - Картахена", "status": "calculated"}, "14994235380": {"time": "2019-03-16 23:24:06", "kof": "1.55", "sum_bet": "650.0", "profit": "1008.0", "result": "win", "name": "Суонси - Манчестер С", "status": "calculated"}, "14992528115": {"time": "2019-03-16 22:27:44", "kof": "1.23", "sum_bet": "825.0", "profit": "0.0", "result": "lose", "name": "Хапоэль Тель-Авив - Ашдод", "status": "calculated"}, "14991503747": {"time": "2019-03-16 21:56:39", "kof": "4.70", "sum_bet": "215.0", "profit": "1011.0", "result": "win", "name": "Хапоэль Тель-Авив - Ашдод: Обе забьют", "status": "calculated"}, "14993029144": {"time": "2019-03-16 22:43:46", "kof": "2.90", "sum_bet": "350.0", "profit": "1015.0", "result": "win", "name": "Суонси - Манчестер С", "status": "calculated"}, "14991662446": {"time": "2019-03-16 22:01:31", "kof": "6.90", "sum_bet": "145.0", "profit": "0.0", "result": "lose", "name": "Эстеглал Тегеран - Нассаджи Мазандаран", "status": "calculated"}, "14989521152": {"time": "2019-03-16 20:49:31", "kof": "1.30", "sum_bet": "775.0", "profit": "1008.0", "result": "win", "name": "Реал Мадрид - Сельта", "status": "calculated"}, "14988526673": {"time": "2019-03-16 20:17:56", "kof": "1.14", "sum_bet": "880.0", "profit": "1003.0", "result": "win", "name": "Реал Мадрид - Сельта", "status": "calculated"}, "14989061179": {"time": "2019-03-16 20:33:47", "kof": "1.50", "sum_bet": "680.0", "profit": "0.0", "result": "lose", "name": "Вест Хэм Юн - Хаддерсфилд Т", "status": "calculated"}, "14989762731": {"time": "2019-03-16 20:57:34", "kof": "1.43", "sum_bet": "700.0", "profit": "1001.0", "result": "win", "name": "Вольфсбург - Фортуна Дюссельдорф", "status": "calculated"}, "14987996257": {"time": "2019-03-16 19:59:01", "kof": "1.45", "sum_bet": "685.0", "profit": "993.0", "result": "win", "name": "Шальке-04 - Лейпциг", "status": "calculated"}, "14989875590": {"time": "2019-03-16 21:01:31", "kof": "12.00", "sum_bet": "85.0", "profit": "43.0", "result": "lose", "name": "Бешикташ - Гезтепе", "status": "completelySold"}, "14986872625": {"time": "2019-03-16 19:22:16", "kof": "1.95", "sum_bet": "525.0", "profit": "0.0", "result": "lose", "name": "Аль-Сайлия - Аль-Садд", "status": "calculated"}, "14988650857": {"time": "2019-03-16 20:22:07", "kof": "2.45", "sum_bet": "415.0", "profit": "1017.0", "result": "win", "name": "Бернли - Лестер С: Обе забьют", "status": "calculated"}, "14987613021": {"time": "2019-03-16 19:46:36", "kof": "1.75", "sum_bet": "575.0", "profit": "1006.0", "result": "win", "name": "Аль-Дафра - Аль-Шарджа: Аль-Шарджа забьет", "status": "calculated"}, "14988582493": {"time": "2019-03-16 20:19:43", "kof": "1.83", "sum_bet": "550.0", "profit": "1007.0", "result": "win", "name": "Бернли - Лестер С: Лестер С забьет", "status": "calculated"}, "14986010340": {"time": "2019-03-16 18:52:49", "kof": "2.10", "sum_bet": "480.0", "profit": "0.0", "result": "lose", "name": "Лудогорец - Септември София", "status": "calculated"}, "14984254198": {"time": "2019-03-16 17:51:41", "kof": "2.45", "sum_bet": "415.0", "profit": "1017.0", "result": "win", "name": "Лидс Юн - Шеффилд Юн", "status": "calculated"}, "14983999456": {"time": "2019-03-16 17:41:45", "kof": "2.80", "sum_bet": "360.0", "profit": "1008.0", "result": "win", "name": "Уотфорд - Кристал Пэлас: Обе забьют", "status": "calculated"}, "14984890829": {"time": "2019-03-16 18:14:01", "kof": "1.14", "sum_bet": "880.0", "profit": "1003.0", "result": "win", "name": "Наньтун Чжиюнь - Ляонин Хувин", "status": "calculated"}, "14984079016": {"time": "2019-03-16 17:44:53", "kof": "7.40", "sum_bet": "140.0", "profit": "0.0", "result": "lose", "name": "Гол Гохар - Персеполис Пакдашт", "status": "calculated"}, "14984118929": {"time": "2019-03-16 17:46:34", "kof": "1.85", "sum_bet": "550.0", "profit": "1018.0", "result": "win", "name": "Гол Гохар - Персеполис Пакдашт", "status": "calculated"}, "14984223520": {"time": "2019-03-16 17:50:31", "kof": "10.00", "sum_bet": "100.0", "profit": "0.0", "result": "lose", "name": "ПСИС Семаранг - ПСМ Макассар: Обе забьют", "status": "calculated"}, "14983860215": {"time": "2019-03-16 17:36:31", "kof": "2.50", "sum_bet": "405.0", "profit": "0.0", "result": "lose", "name": "ПСИС Семаранг - ПСМ Макассар", "status": "calculated"}, "14984062208": {"time": "2019-03-16 17:44:11", "kof": "2.60", "sum_bet": "390.0", "profit": "1014.0", "result": "win", "name": "ПСИС Семаранг - ПСМ Макассар", "status": "calculated"}} # ol_list = {"54": {"time": "2019-03-17 19:10:31", "kof": "1.04", "sum_bet": "970", "profit": "897", "result": "Выиграло", "name": "ФК Данди - Селтик", "status": "897"}, "53": {"time": "2019-03-17 19:07:30", "kof": "1.4", "sum_bet": "710", "profit": "641", "result": "Выиграло", "name": "Локомотив М - ФК Краснодар", "status": "641"}, "52": {"time": "2019-03-17 19:04:11", "kof": "1.55", "sum_bet": "675", "profit": "595", "result": "Выиграло", "name": "Патронато Парана - Дефенса и Хустисия", "status": "595"}, "51": {"time": "2019-03-17 19:00:19", "kof": "2.35", "sum_bet": "430", "profit": "354", "result": "Выиграло", "name": "Локомотив М - ФК Краснодар", "status": "354"}, "50": {"time": "2019-03-17 18:53:46", "kof": "2.98", "sum_bet": "340", "profit": "267", "result": "Проиграло", "name": "Кайсериспор - Истанбул Башакшехир", "status": "267"}, "49": {"time": "2019-03-17 18:39:22", "kof": "1.28", "sum_bet": "795", "profit": "728", "result": "Проиграло", "name": "Арминия - Бохум", "status": "728"}, "48": {"time": "2019-03-17 08:17:22", "kof": "1.54", "sum_bet": "655", "profit": "0", "result": "Проиграло", "name": "Саузерн Тейбландс Юнайтед - ЮС Пумас", "status": "None"}, "47": {"time": "2019-03-17 08:16:38", "kof": "2.89", "sum_bet": "350", "profit": "1012", "result": "Выиграло", "name": "Саузерн Тейбландс Юнайтед - ЮС Пумас", "status": "None"}, "46": {"time": "2019-03-17 07:47:43", "kof": "4.63", "sum_bet": "220", "profit": "0", "result": "Проиграло", "name": "Альянса - Сонсонате", "status": "None"}, "45": {"time": "2019-03-17 07:03:01", "kof": "1.06", "sum_bet": "950", "profit": "1007", "result": "Выиграло", "name": "Сан Антонио ФК - Портленд Тимберс II", "status": "None"}, "44": {"time": "2019-03-17 06:18:06", "kof": "2.5", "sum_bet": "405", "profit": "0", "result": "Проиграло", "name": "Энвигадо - Рионегро Агилас", "status": "None"}, "43": {"time": "2019-03-17 03:50:58", "kof": "1.85", "sum_bet": "550", "profit": "0", "result": "Проиграло", "name": "Универсидад Католика - Дельфин", "status": "None"}, "42": {"time": "2019-03-17 01:59:33", "kof": "1.5", "sum_bet": "685", "profit": "1028", "result": "Выиграло", "name": "Унион Комерсио - Универсидад Сан Мартин", "status": "None"}, "41": {"time": "2019-03-17 01:39:16", "kof": "1.8", "sum_bet": "580", "profit": "0", "result": "Проиграло", "name": "Ольмедо - Гуаякиль Сити", "status": "None"}, "40": {"time": "2019-03-17 00:53:58", "kof": "2.15", "sum_bet": "470", "profit": "470", "result": "Возврат", "name": "Торино - Болонья", "status": "None"}, "39": {"time": "2019-03-17 00:17:51", "kof": "2.15", "sum_bet": "470", "profit": "1011", "result": "Выиграло", "name": "Анже - Амьен", "status": "None"}, "38": {"time": "2019-03-17 00:17:13", "kof": "1.33", "sum_bet": "760", "profit": "1011", "result": "Выиграло", "name": "Анже - Амьен", "status": "None"}, "37": {"time": "2019-03-17 00:15:52", "kof": "2.15", "sum_bet": "470", "profit": "392", "result": "Проиграло", "name": "Экскурсионистас - Сентраль Кордоба", "status": "392"}, "36": {"time": "2019-03-16 23:45:06", "kof": "2.4", "sum_bet": "415", "profit": "996", "result": "Выиграло", "name": "Унион Санта-Фе - Ланус", "status": "None"}, "35": {"time": "2019-03-16 23:31:11", "kof": "1.52", "sum_bet": "665", "profit": "1011", "result": "Выиграло", "name": "Брессер - Монморийон", "status": "None"}, "34": {"time": "2019-03-16 23:24:06", "kof": "2.9", "sum_bet": "350", "profit": "0", "result": "Проиграло", "name": "Суонси Сити - Манчестер Сити", "status": "None"}, "33": {"time": "2019-03-16 23:22:11", "kof": "2.4", "sum_bet": "420", "profit": "0", "result": "Проиграло", "name": "Суонси Сити - Манчестер Сити", "status": "None"}, "32": {"time": "2019-03-16 23:21:34", "kof": "3.4", "sum_bet": "295", "profit": "0", "result": "Проиграло", "name": "Суонси Сити - Манчестер Сити", "status": "None"}, "31": {"time": "2019-03-16 23:20:21", "kof": "1.9", "sum_bet": "530", "profit": "0", "result": "Проиграло", "name": "Гимарайнш - Боавишта", "status": "None"}, "30": {"time": "2019-03-16 23:19:35", "kof": "3.4", "sum_bet": "300", "profit": "0", "result": "Проиграло", "name": "Атлетик Б - Атлетико Мадрид", "status": "None"}, "29": {"time": "2019-03-16 23:13:31", "kof": "2.35", "sum_bet": "430", "profit": "0", "result": "Проиграло", "name": "Херенвен - Де Графсхап", "status": "None"}, "28": {"time": "2019-03-16 23:06:54", "kof": "1.75", "sum_bet": "580", "profit": "1015", "result": "Выиграло", "name": "Атлетик Б - Атлетико Мадрид", "status": "None"}, "27": {"time": "2019-03-16 23:06:16", "kof": "1.6", "sum_bet": "630", "profit": "0", "result": "Проиграло", "name": "Атлетико Санлукено - Картахена", "status": "None"}, "26": {"time": "2019-03-16 22:54:51", "kof": "2.25", "sum_bet": "470", "profit": "1058", "result": "Выиграло", "name": "Атлетик Б - Атлетико Мадрид", "status": "None"}, "25": {"time": "2019-03-16 22:43:46", "kof": "1.57", "sum_bet": "650", "profit": "0", "result": "Проиграло", "name": "Суонси Сити - Манчестер Сити", "status": "None"}, "24": {"time": "2019-03-16 22:37:34", "kof": "8.5", "sum_bet": "120", "profit": "0", "result": "Проиграло", "name": "Суонси Сити - Манчестер Сити", "status": "None"}, "23": {"time": "2019-03-16 22:27:44", "kof": "5.75", "sum_bet": "175", "profit": "1006", "result": "Выиграло", "name": "Хапоэль Тель-Авив - Ашдод", "status": "None"}, "22": {"time": "2019-03-16 22:01:30", "kof": "1.18", "sum_bet": "855", "profit": "1009", "result": "Выиграло", "name": "Эстеглаль Тегеран - Нассаджи Мазендеран", "status": "None"}, "21": {"time": "2019-03-16 21:56:36", "kof": "1.3", "sum_bet": "785", "profit": "0", "result": "Проиграло", "name": "Хапоэль Тель-Авив - Ашдод", "status": "None"}, "20": {"time": "2019-03-16 21:01:33", "kof": "1.1", "sum_bet": "915", "profit": "1007", "result": "Выиграло", "name": "Бешикташ - Гёзтепе", "status": "None"}, "19": {"time": "2019-03-16 20:57:33", "kof": "3.4", "sum_bet": "300", "profit": "0", "result": "Проиграло", "name": "Вольфсбург - Фортуна Д", "status": "None"}, "18": {"time": "2019-03-16 20:49:30", "kof": "4.5", "sum_bet": "225", "profit": "0", "result": "Проиграло", "name": "Реал М - Сельта", "status": "None"}, "17": {"time": "2019-03-16 20:33:46", "kof": "3.2", "sum_bet": "320", "profit": "1024", "result": "Выиграло", "name": "Вест Хэм - Хаддерсфилд", "status": "None"}, "16": {"time": "2019-03-16 20:22:07", "kof": "1.75", "sum_bet": "585", "profit": "0", "result": "Проиграло", "name": "Бернли - Лестер", "status": "None"}, "15": {"time": "2019-03-16 20:19:46", "kof": "2.25", "sum_bet": "450", "profit": "0", "result": "Проиграло", "name": "Бернли - Лестер", "status": "None"}, "14": {"time": "2019-03-16 20:17:55", "kof": "8.5", "sum_bet": "120", "profit": "0", "result": "Проиграло", "name": "Реал М - Сельта", "status": "None"}, "13": {"time": "2019-03-16 20:00:53", "kof": "2", "sum_bet": "480", "profit": "402", "result": "Проиграло", "name": "Штутгарт - Хоффенхайм", "status": "402"}, "12": {"time": "2019-03-16 19:59:01", "kof": "3.2", "sum_bet": "315", "profit": "0", "result": "Проиграло", "name": "Шальке 04 - РБ Лейпциг", "status": "None"}, "11": {"time": "2019-03-16 19:46:38", "kof": "2.37", "sum_bet": "425", "profit": "0", "result": "Проиграло", "name": "Аль-Дафра - Шарджа", "status": "None"}, "10": {"time": "2019-03-16 19:22:15", "kof": "2.15", "sum_bet": "475", "profit": "1021", "result": "Выиграло", "name": "Аль-Сайлия - Аль-Садд", "status": "None"}, "9": {"time": "2019-03-16 18:52:48", "kof": "1.93", "sum_bet": "520", "profit": "1004", "result": "Выиграло", "name": "Лудогорец Разград - Септември София", "status": "None"}, "8": {"time": "2019-03-16 18:14:04", "kof": "8.3", "sum_bet": "120", "profit": "0", "result": "Проиграло", "name": "Нантонг Жиян - Ляонин Хувин", "status": "None"}, "7": {"time": "2019-03-16 17:51:39", "kof": "1.75", "sum_bet": "585", "profit": "0", "result": "Проиграло", "name": "Лидс - Шеффилд Юнайтед", "status": "None"}, "6": {"time": "2019-03-16 17:50:35", "kof": "1.12", "sum_bet": "900", "profit": "1008", "result": "Выиграло", "name": "ПСИС Семаранг - ПСМ Макассар", "status": "None"}, "5": {"time": "2019-03-16 17:46:39", "kof": "2.25", "sum_bet": "450", "profit": "0", "result": "Проиграло", "name": "Гол Гохар - Персеполис Пакдешт", "status": "None"}, "4": {"time": "2019-03-16 17:44:57", "kof": "1.17", "sum_bet": "860", "profit": "1006", "result": "Выиграло", "name": "Гол Гохар - Персеполис Пакдешт", "status": "None"}, "3": {"time": "2019-03-16 17:44:15", "kof": "1.65", "sum_bet": "610", "profit": "0", "result": "Проиграло", "name": "ПСИС Семаранг - ПСМ Макассар", "status": "None"}, "2": {"time": "2019-03-16 17:41:44", "kof": "1.55", "sum_bet": "640", "profit": "0", "result": "Проиграло", "name": "Уотфорд - Кристал Пэлас", "status": "None"}, "1": {"time": "2019-03-16 17:36:35", "kof": "1.65", "sum_bet": "595", "profit": "982", "result": "Выиграло", "name": "ПСИС Семаранг - ПСМ Макассар", "status": "None"}} # print('fb_list=' + str(fb_list)) # print('ol_list=' + str(ol_list)) # READ FORKS INFO with open(file_name, encoding='utf-8') as f: for line in f.readlines(): fork = json.loads(line.strip()) for id, info in fork.items(): ts = int(id) val = datetime.fromtimestamp(ts) time = val.strftime('%Y-%m-%d %H:%M:%S') fb_reg_id = info['fonbet'].get('reg_id', '') fb_info = fb_list.get(str(fb_reg_id), {}) o_reg_id = info['olimp'].get('reg_id', '') o_info = ol_list.get(str(o_reg_id), {}) if fb_info.get('profit', 0.0) == 'None': fb_info_profit = 0.0 else: fb_info_profit = fb_info.get('profit', 0.0) out = out + \ str(id) + ';' + \ str(time) + ';' + \ str(max(info['fonbet'].get('event_type', ''), info['olimp'].get('event_type', ''))) + ';' + \ str(float(info['fonbet'].get('kof', 0.0))).replace('.', ',') + ';' + \ str(float(info['olimp'].get('kof', 0.0))).replace('.', ',') + ';' + \ \ str(int(float(info['fonbet'].get('amount', 0)))) + ';' + \ str(int(float(info['olimp'].get('amount', 0)))) + ';' + \ \ str(info['fonbet'].get('reg_id', '')).replace('None', '') + ';' + \ str(info['olimp'].get('reg_id', '')).replace('None', '') + ';' + \ \ str(fb_info.get('time', '')) + ';' + \ str(o_info.get('time', '')) + ';' + \ \ str(fb_info.get('kof', '')).replace('.', ',') + ';' + \ str(o_info.get('kof', '')).replace('.', ',') + ';' + \ \ str(int(float(fb_info.get('sum_bet', 0)))) + ';' + \ str(int(float(o_info.get('sum_bet', 0)))) + ';' + \ \ str(int(float(fb_info_profit))) + ';' + \ str(o_info.get('profit', '')) + ';' + \ \ str(fb_info.get('result', '')) + ';' + \ str(o_info.get('result', '')) + ';' + \ \ str(fb_info.get('name', '')) + ';' + \ str(o_info.get('name', '')) + ';' + \ \ str(fb_info.get('status', '')) + ';' + \ str(o_info.get('status', '')).replace('None', '') + ';' + \ \ str(info['fonbet'].get('bet_type', '')) + ';' + \ str(info['olimp'].get('bet_type', '')) + ';' + \ \ str(info['fonbet'].get('order_bet', '')) + ';' + \ str(info['fonbet'].get('vector', '')) + ';' + \ str(info['olimp'].get('vector', '')) + ';' + \ str(info['fonbet'].get('first_bet_in', '')) + ';' + \ str(info['fonbet'].get('total_first', '')) + ';' + \ \ str(info['fonbet'].get('time_bet', '')) + ';' + \ str(info['olimp'].get('time_bet', '')) + ';' + \ \ str(info['fonbet'].get('new_bet_sum', '')) + ';' + \ str(info['olimp'].get('new_bet_sum', '')) + ';' + \ \ str(info['fonbet'].get('balance', '')) + ';' + \ str(info['olimp'].get('balance', '')) + ';' + \ \ str(info['fonbet'].get('max_bet', '')) + ';' + \ str(info['fonbet'].get('maxbet_fact', '')) + ';' + \ str(info['fonbet'].get('fonbet_maxbet_fact', '')) + ';' + \ str(info['fonbet'].get('bet_delay', '')) + ';' + \ str(info['fonbet'].get('is_top', '')) + ';' + \ str(info['fonbet'].get('is_hot', '')) + ';' + \ str(info['fonbet'].get('fork_slice', '')) + ';' + \ str(info['fonbet'].get('cnt_act_acc', '')) + ';' + \ str(info['fonbet'].get('place', '')) + ';' + \ \ str(info['fonbet'].get('fork_time_type', '')) + ';' + \ str(info['fonbet'].get('fork_life_time', '')) + ';' + \ str(info['fonbet'].get('fork_life_time_max', '')) + ';' + \ str(info['fonbet'].get('min_proc', '')) + ';' + \ str(info['fonbet'].get('max_proc', '')) + ';' + \ str(info['fonbet'].get('user_id', '')) + ';' + \ str(info['fonbet'].get('fb_bk_type', '')) + ';' + \ str(info['fonbet'].get('group_limit_id', '')) + ';' + \ str(info['fonbet'].get('live_fork', '')) + ';' + \ str(info['fonbet'].get('team_type', '')) + ';' + \ str(info['fonbet'].get('summ_min', '')) + ';' + \ \ str(round((1 - info['fonbet'].get('l', 0.0)) * 100, 3)) + ';' + \ \ str(round((1 - info['fonbet'].get('l_fisrt', 0.0)) * 100, 3)) + ';' + \ \ str(info['fonbet'].get('err', '')) + ';' + \ str(info['olimp'].get('err', '')) + ';' + '\n' header_str = '' for cl in csv_head: if header_str == '': header_str = cl else: header_str = header_str + ';' + cl header = header_str + ';\n' if not os.path.isfile(csv_name): with open(csv_name, 'w', encoding='utf-8') as f: f.write(header + out) else: with open(csv_name, 'a+', encoding='utf-8') as f: f.write(out) file_name_log = str(ACC_ID) + '_client.log' if os.path.isfile(file_name_log): try: new_file_name_log = cur_date_str + '_' + file_name_log if not os.path.isfile(new_file_name_log): os.rename(file_name_log, new_file_name_log) else: os.rename( file_name_log, new_file_name_log.replace( '.', datetime.now().strftime('%H_%M') + '.')) except Exception as e: prnt(e) file_name_hide_log = str(ACC_ID) + '_client_hide.log' if os.path.isfile(file_name_hide_log): try: new_file_name_hide_log = cur_date_str + '_' + file_name_hide_log if not os.path.isfile(new_file_name_hide_log): os.rename(file_name_hide_log, new_file_name_hide_log) else: os.rename( file_name_hide_log, new_file_name_hide_log.replace( '.', datetime.now().strftime('%H_%M') + '.')) except Exception as e: prnt(e) file_name_cl_bet_log = str(ACC_ID) + '_to_cl_bet.log' if os.path.isfile(file_name_cl_bet_log): try: new_file_name_cl_bet_log = cur_date_str + '_' + file_name_hide_log if not os.path.isfile(new_file_name_cl_bet_log): os.rename(file_name_cl_bet_log, new_file_name_cl_bet_log) else: os.rename( file_name_cl_bet_log, new_file_name_cl_bet_log.replace( '.', datetime.now().strftime('%H_%M') + '.')) except Exception as e: prnt(e) file_name_cl_fork_log = str(ACC_ID) + '_to_cl_fork.log' if os.path.isfile(file_name_cl_fork_log): try: new_file_name_cl_fork_log = cur_date_str + '_' + file_name_cl_fork_log if not os.path.isfile(new_file_name_cl_fork_log): os.rename(file_name_cl_fork_log, new_file_name_cl_fork_log) else: os.rename( file_name_cl_fork_log, new_file_name_cl_fork_log.replace( '.', datetime.now().strftime('%H_%M') + '.')) except Exception as e: prnt(e) if os.path.isfile(file_name): try: new_id_fork = cur_date_str + '_' + file_name if not os.path.isfile(new_id_fork): os.rename(file_name, new_id_fork) else: os.rename( file_name, new_id_fork.replace('.', datetime.now().strftime('%H_%M') + '.')) except Exception as e: prnt(e) if os.path.isfile(csv_name): # send to tg with open(csv_name, 'r', encoding='utf-8') as f: db_model.Message.insert({ db_model.Message.to_user: USER_ID, db_model.Message.blob: f.read(), db_model.Message.file_name: csv_name, db_model.Message.file_type: 'document' }).execute() try: join_file_name = join_csv(cur_date_str) except Exception as e: prnt('def join_csv, error: ' + str(e))
def get_new_bets_fonbet(match_id, proxies, time_out=50): key_id = str(match_id) bets_fonbet = {} try: resp = requests_retry_session().get( url_fonbet_match + str(match_id) + "&lang=en", headers=fonbet_header2, timeout=time_out, verify=False, proxies=proxies, ) resp = resp.json() TT = [] for bet in [TTO, TTU, TT1O, TT1U, TT2O, TT2U, FORA]: TT.extend(bet) for event in resp.get("events"): # prnts(jsondumps(event, ensure_ascii=False)) # exit() score = event.get('score', '0:0').replace('-', ':') timer = event.get('timer') minute = event.get('timerSeconds', 0) / 60 skId = event.get('skId') skName = event.get('skName') sport_name = event.get('sportName') name = event.get('name') priority = event.get('priority') score_1st = event.get('scoreComment', '').replace('-', ':') if event.get('parentId') == 0 or 'st half' in name or 'nd half' in name: if event.get('parentId') == 0: try: bets_fonbet[key_id].update({ 'sport_id': skId, 'sport_name': skName, 'league': sport_name, 'name': name, 'priority': priority, 'score': score, 'score_1st': score_1st, 'time': timer, 'minute': minute, 'time_req': round(time.time()) }) except Exception as e: # print(e) bets_fonbet[key_id] = { 'sport_id': skId, 'sport_name': skName, 'league': sport_name, 'name': name, 'priority': priority, 'score': score, 'score_1st': score_1st, 'time': timer, 'minute': minute, 'time_req': round(time.time()), 'time_change_total': round(time.time()), 'avg_change_total': [], 'kofs': {} } # prnts('event_name', event.get('name')) half = '' if 'st half' in name or 'nd half' in name: half = name.replace('st half', '').replace('nd half', '') for cat in event.get('subcategories'): cat_name = cat.get('name') # prnts('cat_name', cat_name) if cat_name in ('1X2 (90 min)', '1X2', 'Goal - no goal', 'Total', 'Totals', 'Team Totals-1', 'Team Totals-2', 'Hcap'): for kof in cat.get('quotes'): factorId = str(kof.get('factorId')) pValue = kof.get('pValue', '') p = kof.get('p', '').replace('+', '') kof_is_block = kof.get('blocked', False) if kof_is_block: value = 0 else: value = kof.get('value') # {'event': '12788610', 'factor': '921', 'param': '', 'score': '1:0', 'value': '1.25'} for vct in VICTS: coef = half + str(vct[0]) if str(vct[1]) == factorId: bets_fonbet[key_id]['kofs'].update( { coef: { 'time_req': round(time.time()), 'event': event.get('id'), 'value': value, 'param': '', 'factor': factorId, 'score': score } } ) for stake in TT: coef = half + str(stake[0].format(p)) # + num_team if str(stake[1]) == factorId: bets_fonbet[key_id]['kofs'].update( { coef: { 'time_req': round(time.time()), 'event': event.get('id'), 'value': value, 'param': pValue, 'factor': factorId, 'score': score }} ) return bets_fonbet except Exception as e: prnt(e) raise ValueError(e)
def get_vect(x, y, x2, y2): y = y[-len(x):] y2 = y2[-len(x2):] kof_cur1 = y[-1] kof_cur2 = y2[-1] arr = list(zip(x, y)) x = [] y = [] n = 1 for p in arr: for t in range(1, p[0]): x.append(n) y.append(p[1]) n += 1 arr2 = list(zip(x2, y2)) x2 = [] y2 = [] n2 = 1 for p2 in arr2: for t2 in range(1, p2[0]): x2.append(n2) y2.append(p2[1]) n2 += 1 regr = linear_model.LinearRegression() regr2 = linear_model.LinearRegression() if x > x2: x2 = x[-len(x2):] n3 = min(x2) else: x = x2[-len(x):] n3 = min(x) x_max = max(x) x2_max = max(x2) p = list(zip(reversed(y), reversed(y2))) x_predict1 = x[-1] + x_max x_predict2 = x2[-1] + x2_max for k in reversed(p): k1, k2 = k[0], k[1] if k1 and k2: l = 1 / k1 + 1 / k2 if l < 1: proc = (1 - l) * 100 if proc > 0: if proc >= 3: color = 'pink' elif proc >= 2: color = 'red' elif proc >= 1: color = 'yellow' elif proc >= 0.5: color = 'orange' elif proc < 0.5: color = 'black' plt.plot([n3, n3], [min(k1, k2) + 0.05, max(k1, k2) - 0.05], color=color, markersize=1) # live += 1 n3 += 1 plt.scatter(x, y, color='blue', marker=',') plt.scatter(x2, y2, color='red', marker=',') x_save, y_save = np.asarray(x).reshape(len(x), 1), np.asarray(y).reshape( len(y), 1) x2_save, y2_save = np.asarray(x2).reshape(len(x2), 1), np.asarray(y2).reshape( len(y2), 1) # x = x[-len(x2):] # y = y[-len(x2):] y, x = del_zerro(y, x) y_for_check_noise = np.asarray(y).reshape(len(y), 1) x_for_check_noise = np.asarray(x).reshape(len(x), 1) # plt.scatter(x, y, color='blue', marker=',') y, x = del_noise(y, x) px, py = x[0], y[0] px2, py2 = x[-1], y[-1] x = np.asarray(x).reshape(len(x), 1) y = np.asarray(y).reshape(len(y), 1) regr.fit(x, y) # x2 = x2[-len(x):] # y2 = y2[-len(x):] y2, x2 = del_zerro(y2, x2) # plt.scatter(x2, y2, color='red', marker=',') y2_for_check_noise = np.asarray(y2).reshape(len(y2), 1) x2_for_check_noise = np.asarray(x2).reshape(len(x2), 1) y2, x2 = del_noise(y2, x2) ppx, ppy = x2[0], y2[0] ppx2, ppy2 = x2[-1], y2[-1] y2 = np.asarray(y2).reshape(len(y2), 1) x2 = np.asarray(x2).reshape(len(x2), 1) regr2.fit(x2, y2) check_noise_up = list( zip(y_for_check_noise, regr.predict(x_for_check_noise) + get_std(y))) check_noise_down = list( zip(y_for_check_noise, regr.predict(x_for_check_noise) - get_std(y))) noise1 = 0 for n1 in check_noise_up: if n1[0].tolist()[0] > n1[1].tolist()[0]: noise1 = n1[0].tolist()[0] break if not noise1: for n1 in check_noise_down: if n1[0].tolist()[0] < n1[1].tolist()[0]: noise1 = n1[0].tolist()[0] break # chech last kof is noise k1_is_noise = 0 prnt('Fonbet: min: {}, cur: {}, max: {}'.format(check_noise_down[-1][1][0], kof_cur1, check_noise_up[-1][1][0])) if check_noise_down[-1][1][0] > kof_cur1 or kof_cur1 > check_noise_up[-1][ 1][0]: k1_is_noise = kof_cur1 plt.plot(x_save, regr.predict(x_save) + get_std(y), color='blue', linestyle='dotted', markersize=1) plt.plot(x_save, regr.predict(x_save), color='black', linestyle='dashed', markersize=1) plt.plot(x_save, regr.predict(x_save) - get_std(y), color='blue', linestyle='dotted', markersize=1) check_noise_up2 = list( zip(y2_for_check_noise, regr2.predict(x2_for_check_noise) + get_std(y2))) check_noise_down2 = list( zip(y2_for_check_noise, regr2.predict(x2_for_check_noise) - get_std(y2))) noise2 = 0 for n2 in check_noise_up2: if n2[0].tolist()[0] > n2[1].tolist()[0]: noise2 = n2[0].tolist()[0] break if not noise2: for n2 in check_noise_down2: if n2[0].tolist()[0] < n2[1].tolist()[0]: noise2 = n2[0].tolist()[0] break # chech last kof is noise k2_is_noise = 0 prnt('Olimp: min: {}, cur: {}, max: {}'.format(check_noise_down2[-1][1][0], kof_cur2, check_noise_up2[-1][1][0])) if check_noise_down2[-1][1][0] > kof_cur2 or kof_cur2 > check_noise_up2[ -1][1][0]: k2_is_noise = kof_cur2 plt.plot(x2_save, regr2.predict(x2_save) + get_std(y2), color='red', linestyle='dotted', markersize=1) plt.plot(x2_save, regr2.predict(x2_save), color='black', linestyle='dashed', markersize=1) plt.plot(x2_save, regr2.predict(x2_save) - get_std(y2), color='red', linestyle='dotted', markersize=1) kof_predict11 = round(float(regr.predict([[x_max]])[0]), 2) kof_predict21 = round(float(regr.predict([[x_predict1]])[0]), 2) kof_predict12 = round(float(regr2.predict([[x2_max]])[0]), 2) kof_predict22 = round(float(regr2.predict([[x_predict2]])[0]), 2) if kof_predict21 > kof_predict11: vect_fb = 'UP' elif kof_predict21 == kof_predict11: vect_fb = 'STAT' else: vect_fb = 'DOWN' prnt('Fonbet: {}, {}->{}. {}. Noise: {}. Last_noise: {}'.format( vect_fb, kof_predict11, kof_predict21, kof_cur1, noise1, k1_is_noise)) if kof_predict22 > kof_predict12: vect_ol = 'UP' elif kof_predict22 == kof_predict12: vect_ol = 'STAT' else: vect_ol = 'DOWN' prnt('Olimp: {}, {}->{}. {}. Noise: {}. Last_noise: {}'.format( vect_ol, kof_predict12, kof_predict22, kof_cur2, noise2, k2_is_noise)) return vect_fb, vect_ol, noise1, noise2, k1_is_noise, k2_is_noise, plt
def reject_outliers(data): data = np.asarray(data) prnt('mean: {}, std: {}, std*noise: {}'.format(np.mean(data), np.std(data), noise * np.std(data))) return data[abs(data - np.mean(data)) <= noise * np.std(data)].tolist()
vect1, vect2 = 'UP', 'DOWN' ACC_ID = 0 ml_ok = False real_vect2, real_vect1, noise2, noise1, k2_is_noise, k1_is_noise, plt = get_vect( x, y, x2, y2) from better import save_plt filename = 'test'.replace('.', '') # ML #1 - CHECK VECTS if check_vect(real_vect1, real_vect2) and check_noise( noise1, noise2) and sum(x) >= 2 <= sum(x2): ml_ok = True prnt( 'Fork key: ' + str(filename) + ', успешно прошел проверку 1 (векторы строго сонаправлены и нет шума)' ) if vect1 != real_vect1: prnt('Вектор в Олимп измнен: {}->{}'.format(vect1, real_vect1)) # shared['olimp']['vect'] = real_vect1 if vect2 != real_vect2: prnt('Вектор в Фонбет измнен: {}->{}'.format(vect2, real_vect2)) # shared['fonbet']['vect'] = real_vect2 save_plt(str(ACC_ID) + '_I_ok', filename, plt) else: prnt('Fork key: ' + str(filename) + ', не прошел проверку 1 (векторы строго сонаправлены и нет шума)') save_plt(str(ACC_ID) + '_I_err', filename, plt) # ML #2 CHECK CREATER-NOISE if not ml_ok: