xam1816Там 2000 строк кривого кода, наврядли вам будет интересно его анализировать. Вот один из самых кривых модулей, который втиснут в функцию (как уже писал, я тогда не знал, что def - это функция, я ее применял как модуль, как что-то, что будет много раз повторяться). И таких “модулей 20 на всю программу. Хочется их сделать истинными модулями с правильной передачей переменных, но иначе не умею, только так и с глобальными переменными.
Выложите сюда свой код, который изначально у вас был на одном файле
Вот эта вся фиговина (это модуль парсинга etherscan - блокчейна эфира) и делает кучу реквестов, и считает параметры по монете, и создает словари, и короче всего очень много, потом десяток других ”модулей" (опять же функций) забирают глобальные переменные и делают то же самое. Работать работает, но я уже сам вижу, насколько сложно все выглядит.
def etherscan_parser(condition): global last_eth_block, eth_difficulty, profitability, block_profitability, lowest_theoretical_profitability, lowest_theoretical_profitability_truncated_list_avg, block_rewards_truncated_list_avg, profitability_truncated_list_avg,\ block_rewards_list, flexpool_block_rewards_list, profitability_list, limited_profitability_list, tx_fees_list, tx_fees_list1_avg tx_fees_list = [] block_rewards_list = [] flexpool_block_rewards_list = [] profitability_list = [] limited_profitability_list = [] lowest_theoretical_profitability_list = [] try: if condition is True: etherscan_request = requests.get('https://api.etherscan.io/api?module=proxy&action=eth_blockNumber&apikey=xxxxxx').json() last_eth_block_hex = etherscan_request['result'] last_eth_block = int(last_eth_block_hex, 16) last_eth_block = last_eth_block - 10 # берем чуть более давние блоки, так как данные о самых последних блоках иногда поступают с небольшим опознаднием last_eth_block_hex = hex(last_eth_block) # снова переводим в hex, так как надо будет брать difficulty, а ее из-за запаздывания информации по последнему блоку еще нет last_eth_block_data = requests.get('https://api.etherscan.io/api?module=proxy&action=eth_getBlockByNumber&tag=' + str(last_eth_block_hex) + '&boolean=true&apikey=xxxxxx').json() eth_difficulty = int(last_eth_block_data['result']['difficulty'], 16) etherscan_request = requests.get('https://api.etherscan.io/api?module=block&action=getblockreward&blockno=' + str(last_eth_block) + '&apikey=xxxxxx').json() block_status = (etherscan_request['status']) while block_status == '1': # block_status is str!! blocknumber = int(etherscan_request['result']['blockNumber']) block_data_etherscan_dict[blocknumber] = etherscan_request['result'] last_eth_block += 1 time.sleep(short_iteration_pause) etherscan_request = requests.get('https://api.etherscan.io/api?module=block&action=getblockreward&blockno=' + str(last_eth_block) + '&apikey=xxxxxx').json() block_status = etherscan_request['status'] for blocknumber in block_data_etherscan_dict.keys(): timestamp = int(block_data_etherscan_dict[blocknumber]['timeStamp']) block_reward = int(block_data_etherscan_dict[blocknumber]['blockReward']) / 1000000000000000000 block_profitability = (86400 * 1000000000000 * block_reward * eth_btc_exchange_rate / eth_difficulty) * (1 - orphan_rate) print('Block profitability =', block_profitability, '; block# =', blocknumber, 'reward =', block_reward, 'difficulty =', eth_difficulty) if block_profitability > profitability_limit: limited_block_profitability = profitability_limit else: limited_block_profitability = block_profitability lowest_theoretical_profitability = (1000000000000 * (average_uncle_reward + 0.0625 + (2 - average_uncle_reward - 0.0625) * (1 - uncle_rate)) * (1 - orphan_rate) / eth_difficulty) * 86400 * eth_btc_exchange_rate # 1.8125 = 1.75 + 0.0625 inclusion reward, 0.1875 = 2 - 1.8125. Only 1.75 ETH uncles calculated uncle_inclusion_reward = int(block_data_etherscan_dict[blocknumber]['uncleInclusionReward']) / 1000000000000000000 block_miner = block_data_etherscan_dict[blocknumber]['blockMiner'] my_etherscan_dict[blocknumber] = {'block_reward': block_reward, 'tx_fees': block_reward - 2 - uncle_inclusion_reward, 'timestamp': timestamp, 'block_profitability': block_profitability, 'uncle_reward': [], 'uncle_profitability': [], 'uncle_miner': [], 'lowest_theoretical_profitability': lowest_theoretical_profitability, 'limited_block_profitability': limited_block_profitability, 'limited_uncle_profitability': [], 'uncle_inclusion_reward': uncle_inclusion_reward, 'block_miner': block_miner} tx_fees_list.append(my_etherscan_dict[blocknumber]['tx_fees']) tx_fees_list1 = tx_fees_list[-10:] tx_fees_list1_avg = statistics.mean(tx_fees_list1) for x in range(0, len(block_data_etherscan_dict[blocknumber]['uncles'])): uncle_reward = int(block_data_etherscan_dict[blocknumber]['uncles'][x]['blockreward']) / 1000000000000000000 uncle_profitability = (86400 * 1000000000000 * uncle_reward * eth_btc_exchange_rate / eth_difficulty) * (1 - orphan_rate) uncle_miner = block_data_etherscan_dict[blocknumber]['uncles'][x]['miner'] my_etherscan_dict[blocknumber]['uncle_profitability'].append(uncle_profitability) my_etherscan_dict[blocknumber]['uncle_reward'].append(uncle_reward) my_etherscan_dict[blocknumber]['uncle_miner'].append(uncle_miner) if uncle_profitability > profitability_limit: limited_uncle_profitability = profitability_limit else: limited_uncle_profitability = uncle_profitability my_etherscan_dict[blocknumber]['limited_uncle_profitability'].append(limited_uncle_profitability) for blocknumber in my_etherscan_dict.keys(): block_rewards_list.append(my_etherscan_dict[blocknumber]['block_reward']) if my_etherscan_dict[blocknumber]['block_miner'] == '0x7f101fe45e6649a6fb8f3f8b43ed03d353f2b90c': flexpool_block_rewards_list.append(my_etherscan_dict[blocknumber]['block_reward']) profitability_list.append(my_etherscan_dict[blocknumber]['block_profitability']) limited_profitability_list.append(my_etherscan_dict[blocknumber]['limited_block_profitability']) lowest_theoretical_profitability_list.append(my_etherscan_dict[blocknumber]['lowest_theoretical_profitability']) for x in range(0, len(my_etherscan_dict[blocknumber]['uncle_profitability'])): block_rewards_list.append(my_etherscan_dict[blocknumber]['uncle_reward'][x]) if my_etherscan_dict[blocknumber]['uncle_miner'][x] == '0x7f101fe45e6649a6fb8f3f8b43ed03d353f2b90c': flexpool_block_rewards_list.append(my_etherscan_dict[blocknumber]['uncle_reward'][x]) profitability_list.append(my_etherscan_dict[blocknumber]['uncle_profitability'][x]) limited_profitability_list.append(my_etherscan_dict[blocknumber]['limited_uncle_profitability'][x]) block_reward_truncated_list = block_rewards_list[int(-4.545 * minutes_to_average_for_blockchain_profitability):] profitability_truncated_list = profitability_list[int(-4.545 * minutes_to_average_for_blockchain_profitability):] limited_profitability_truncated_list = limited_profitability_list[int(-4.545 * minutes_to_average_for_blockchain_profitability):] lowest_theoretical_profitability_truncated_list = lowest_theoretical_profitability_list[int(-4.545 * minutes_to_average_for_blockchain_profitability):] # LIST AVERAGES block_rewards_list_avg = round(statistics.mean(block_rewards_list), 3) block_rewards_truncated_list_avg = round(statistics.mean(block_reward_truncated_list), 3) try: flexpool_block_rewards_list_avg = round(statistics.mean(flexpool_block_rewards_list), 3) # если в последних блоках нет блока от flexpool, программа тут останавливается except: pass profitability_truncated_list_avg = round(statistics.mean(profitability_truncated_list), 3) limited_profitability_truncated_list_avg = profitability = round(statistics.mean(limited_profitability_truncated_list), 3) # ТУТ ОСНОВНОЕ ЗНАЧЕНИЕ profitability !!! lowest_theoretical_profitability_truncated_list_avg = round(statistics.mean(lowest_theoretical_profitability_truncated_list), 3) # COLLECTING TO MY OUTPUT DICT output_data_dict['block_rewards_list_avg'] = block_rewards_list_avg try: output_data_dict['flexpool_block_reward_etherscan_avg'] = flexpool_block_rewards_list_avg # если в последних блоках нет блока от flexpool, программа тут останавливается except: pass output_data_dict['block_rewards_truncated_list_avg'] = block_rewards_truncated_list_avg output_data_dict['profitability_truncated_list_avg'] = profitability_truncated_list_avg output_data_dict['profitability'] = profitability output_data_dict['lowest_theoretical_profitability_truncated_list_avg'] = lowest_theoretical_profitability_truncated_list_avg full_profitability_to_lowest_profitability_ratio = round(100 * profitability_truncated_list_avg / lowest_theoretical_profitability_truncated_list_avg, 2) full_profitability_to_lowest_profitability_ratio_list.append(full_profitability_to_lowest_profitability_ratio) reward_and_profitability_avg_by_timestamp_dict[int(time.time())] = {'block_rewards_list_avg': round(statistics.mean(block_rewards_list), 3), 'block_rewards_truncated_list_avg': block_rewards_truncated_list_avg, 'profitability': profitability, 'profitability_truncated_list_avg': profitability_truncated_list_avg, 'lowest_theoretical_profitability_truncated_list_avg': lowest_theoretical_profitability_truncated_list_avg} try: last_eth_block_hex = hex(last_eth_block) last_eth_block_data = requests.get('https://api.etherscan.io/api?module=proxy&action=eth_getBlockByNumber&tag=' + str(last_eth_block_hex) + '&boolean=true&apikey=xxxxxx').json() eth_difficulty = int(last_eth_block_data['result']['difficulty'], 16) except: pass except: print('eth_block_reward_etherscan error')