gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Вывод комис с хуоби url = 'https://api.huobi.pro/v2/reference/currencies' headers =…
- User
Вывод комис с хуоби
code - Assistant
url = 'https://api.huobi.pro/v2/reference/currencies'
headers = {'Content-Type': 'text/html', }
response = requests.get(url, headers=headers)
html = response.text
with open('huobi_fee_html', 'w', encoding='utf-8') as r:
r.write(html)
local = 'file:///C:/Users/user/PycharmProjects/pythonProject/huobi_fee_html'
response = urlopen(local)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
DataSetNotProcessedFee_HB = tree.xpath('//body/descendant::node()/text()')
resFee_HB = json.loads(str(*DataSetNotProcessedFee_HB))
res_2Fee_HB = resFee_HB['data']
Currency_HB = [] #coin
Chains_HB = [] #networkList
ChainAll_HB = []
Chain_displayName_HB = [] #displayName
Chain_fullName_HB = [] #fullName
Chain_baseChain_HB = [] #baseChain
DepositStatus_HB = [] #depositEnable
WithdrawStatus_HB = [] #withdrawEnable
for slovar in res_2Fee_HB:
Currency_HB.append(slovar['currency'].upper())
Chains_HB.append(slovar['chains'])
for i in range(len(Chains_HB)):
Chains1_HB = Chains_HB[i]
Chain1_displayName_HB = []
Chain1_fullName_HB = []
Chain1_baseChain_HB = []
DepositStatus1_HB = []
WithdrawStatus1_HB = []
ChainAll1_HB = []
for slovar in Chains1_HB:
Chain1_displayName_HB.append(slovar['displayName'])
Chain1_fullName_HB.append((slovar['fullName']).upper().replace(' ',''))
if 'baseChain' in slovar:
Chain1_baseChain_HB.append(slovar['baseChain'])
else:
Chain1_baseChain_HB.append('')
DepositStatus1_HB.append(slovar['depositStatus'])
WithdrawStatus1_HB.append(slovar['withdrawStatus'])
ChainAll1_HB = list(Chain1_displayName_HB+Chain1_fullName_HB+Chain1_baseChain_HB)
DepositStatus1_HB = list(DepositStatus1_HB + DepositStatus1_HB + WithdrawStatus1_HB)
WithdrawStatus1_HB = list(WithdrawStatus1_HB + WithdrawStatus1_HB + WithdrawStatus1_HB)
# Chain_displayName_HB.append(Chain1_displayName_HB)
# Chain_fullName_HB.append(Chain1_fullName_HB)
# Chain_baseChain_HB.append(Chain1_baseChain_HB)
ChainAll_HB.append(ChainAll1_HB)
DepositStatus_HB.append(DepositStatus1_HB)
WithdrawStatus_HB.append(WithdrawStatus1_HB)
# Вывод комис с бинанса
try:
client = ClientBN(config.api_key, config.api_secret)
info = client.get_all_coins_info()
except Exception as e:
print(e)
# print(info)
Currency_BN = [] #coin
Chains_BN = [] #networkList
ChainAll_BN = []
# Chain_name_BN = [] #name
# Chain_network_BN = [] #network
DepositStatus_BN = [] #depositEnable
WithdrawStatus_BN = [] #withdrawEnable
for slovar in info:
Currency_BN.append(slovar['coin'])
Chains_BN.append(slovar['networkList'])
for i in range(len(Chains_BN)):
Chains1_BN = Chains_BN[i]
Chain1_name_BN = []
Chain1_network_BN = []
DepositStatus1_BN = []
WithdrawStatus1_BN = []
ChainAll1_BN = []
for slovar in Chains1_BN:
DepositStatus1_BN.append(str(slovar['depositEnable']))
WithdrawStatus1_BN.append(str(slovar['withdrawEnable']))
_ = slovar['name'].split()
if '(' in _[-1]:
Chain1_name_BN.append(_[-1].replace('(','').replace(')',''))
else:
Chain1_name_BN.append(''.join(_[:len(_)]).replace('-','').upper())
Chain1_network_BN.append(slovar['network'])
ChainAll1_BN = list(Chain1_network_BN + Chain1_name_BN)
DepositStatus1_BN = list(DepositStatus1_BN + DepositStatus1_BN)
WithdrawStatus1_BN = list(WithdrawStatus1_BN + WithdrawStatus1_BN)
# Chain_name_BN.append(Chain1_name_BN)
# Chain_network_BN.append(Chain1_network_BN)
DepositStatus_BN.append(DepositStatus1_BN)
WithdrawStatus_BN.append(WithdrawStatus1_BN)
ChainAll_BN.append(ChainAll1_BN)
# Вывод комис с гейта
url = 'https://api.gateio.ws/api/v4/spot/currencies'
headers = {'Content-Type': 'text/html', }
response = requests.get(url, headers=headers)
html = response.text
with open('gate_fee_html', 'w', encoding='utf-8') as g:
g.write(html)
local = 'file:///C:/Users/user/PycharmProjects/pythonProject/gate_fee_html'
response = urlopen(local)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
DataSetNotProcessedFee_GT = tree.xpath('//body/descendant::node()/text()')
resFee_GT = json.loads(str(*DataSetNotProcessedFee_GT))
Currency_GT1 = []
res2Fee_GT = []
for slovar in resFee_GT:
Currency_GT_Сomparison1 = []
ChainAll1_GT = []
d = {}
Currency_GT_Сomparison1.append(slovar['currency'].replace('_',' ').split()[0])
if Currency_GT_Сomparison1 not in Currency_GT1:
Currency_GT1.append(Currency_GT_Сomparison1)
for item in resFee_GT:
Currency_GT_Сomparison2 = []
Currency_GT_Сomparison2.append(item['currency'].replace('_',' ').split()[0])
if Currency_GT_Сomparison2 == Currency_GT_Сomparison1:
ChainAll1_GT.append(item)
else:
Currency_GT_Сomparison1 = []
if Currency_GT_Сomparison1 != []:
Currency_GT_Сomparison3 = ''.join(Currency_GT_Сomparison1)
d = dict(currency = Currency_GT_Сomparison3 , Chains = ChainAll1_GT)
res2Fee_GT.append(d)
Currency_GT = []
Chains_GT = []
ChainAll_GT = []
DepositStatus_GT = []
WithdrawStatus_GT = []
for slovar in res2Fee_GT:
Currency_GT.append(slovar['currency'])
Chains_GT.append(slovar['Chains'])
for i in range(len(Chains_GT)):
Chains1_GT = Chains_GT[i]
Chain1_GT = []
DepositStatus1_GT = []
WithdrawStatus1_GT = []
for slovar in Chains1_GT:
Chain1_GT.append(slovar['chain'])
DepositStatus1_GT.append(str(slovar['deposit_disabled']))
WithdrawStatus1_GT.append(str(slovar['withdraw_disabled']))
ChainAll_GT.append(Chain1_GT)
DepositStatus_GT.append(DepositStatus1_GT)
WithdrawStatus_GT.append(WithdrawStatus1_GT)
# Вывод комис с мекса
mexc = MexcAPI(config.api_key_MX, config.api_secret_MX)
resFee_MX = mexc.get_currency_information().json()
Currency_MX = [] #coin
Chains_MX = [] #networkList
ChainAll_MX = []
DepositStatus_MX = [] #depositEnable
WithdrawStatus_MX = [] #withdrawEnable
for slovar in resFee_MX:
Currency_MX.append(slovar['coin'])
Chains_MX.append(slovar['networkList'])
for i in range(len(Chains_MX)):
Chains1_MX = Chains_MX[i]
Chain1_name_MX = []
DepositStatus1_MX = []
WithdrawStatus1_MX = []
for item in Chains1_MX:
DepositStatus1_MX.append(str(item['depositEnable']))
WithdrawStatus1_MX.append(str(item['withdrawEnable']))
_ = item['network'].split('(')
if ')' in _[-1]:
Chain1_name_MX.append(_[0])
else:
Chain1_name_MX.append(''.join(_[:len(_)]).replace('-','').upper())
ChainAll_MX.append(Chain1_name_MX)
DepositStatus_MX.append(DepositStatus1_MX)
WithdrawStatus_MX.append(WithdrawStatus1_MX) переработай эту часть кода улучши её
Конечно, давайте улучшим ваш код для получения комиссий с нескольких криптовалютных бирж: Huobi, Binance, Gate.io, и MEXC. Основными улучшениями будут:
Я перепишу ваш код с учетом этих улучшений.
import requests
import json
from binance.client import Client as ClientBN # Убедитесь, что у вас установлен binance-python
from lxml import etree
from urllib.request import urlopen
from mexc_api import MexcAPI # Убедитесь, что у вас установлен mexc_api
import config # Файл с ключами API
# Функция для получения и парсинга данных с URL-адреса
def fetch_parse_data(url, headers=None):
response = requests.get(url, headers=headers)
return json.loads(response.text)
# Функция для чтения и парсинга локального HTML файла
def parse_local_html(local_path):
response = urlopen(local_path)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
return json.loads(str(*tree.xpath('//body/descendant::node()/text()')))
# Функция для обработки данных Huobi
def process_huobi_data(raw_data):
currencies = []
all_chains = []
deposit_status = []
withdraw_status = []
for currency_info in raw_data['data']:
currency = currency_info['currency'].upper()
chains = currency_info['chains']
currencies.append(currency)
processed_chains = []
dep_status = []
with_status = []
for chain in chains:
processed_chains.extend([chain['displayName'], chain['fullName'].upper().replace(' ', '')])
processed_chains.append(chain.get('baseChain', ''))
dep_status.extend([chain['depositStatus']] * 3)
with_status.extend([chain['withdrawStatus']] * 3)
all_chains.append(processed_chains)
deposit_status.append(dep_status)
withdraw_status.append(with_status)
return currencies, all_chains, deposit_status, withdraw_status
# Функция для обработки данных Binance
def process_binance_data(raw_data):
currencies = []
all_chains = []
deposit_status = []
withdraw_status = []
for coin_info in raw_data:
currency = coin_info['coin']
networks = coin_info['networkList']
currencies.append(currency)
processed_chains = []
dep_status = []
with_status = []
for network in networks:
network_name = network['network'].split('(')[0].replace('-', '').upper()
processed_chains.append(network_name)
dep_status.append(str(network['depositEnable']))
with_status.append(str(network['withdrawEnable']))
all_chains.append(processed_chains)
deposit_status.append(dep_status)
withdraw_status.append(with_status)
return currencies, all_chains, deposit_status, withdraw_status
# Функция для обработки данных Gate.io
def process_gate_data(raw_data):
seen_currencies = set()
currencies = []
all_chains = []
deposit_status = []
withdraw_status = []
for currency_info in raw_data:
currency = currency_info['currency'].replace('_', ' ').split()[0]
if currency not in seen_currencies:
seen_currencies.add(currency)
currencies.append(currency)
filtered_chains = [info for info in raw_data if info['currency'].replace('_', ' ').split()[0] == currency]
processed_chains = [item['chain'] for item in filtered_chains]
dep_status = [str(item['deposit_disabled']) for item in filtered_chains]
with_status = [str(item['withdraw_disabled']) for item in filtered_chains]
all_chains.append(processed_chains)
deposit_status.append(dep_status)
withdraw_status.append(with_status)
return currencies, all_chains, deposit_status, withdraw_status
# Функция для обработки данных MEXC
def process_mexc_data(raw_data):
currencies = []
all_chains = []
deposit_status = []
withdraw_status = []
for currency_info in raw_data:
currency = currency_info['coin']
networks = currency_info['networkList']
currencies.append(currency)
processed_chains = []
dep_status = []
with_status = []
for network in networks:
network_name = network['network'].split('(')[0].replace('-', '').upper()
processed_chains.append(network_name)
dep_status.append(str(network['depositEnable']))
with_status.append(str(network['withdrawEnable']))
all_chains.append(processed_chains)
deposit_status.append(dep_status)
withdraw_status.append(with_status)
return currencies, all_chains, deposit_status, withdraw_status
# Обработка данных Huobi
huobi_url = 'https://api.huobi.pro/v2/reference/currencies'
huobi_data = fetch_parse_data(huobi_url)
huobi_currencies, huobi_all_chains, huobi_deposit_status, huobi_withdraw_status = process_huobi_data(huobi_data)
# Обработка данных Binance
client_binance = ClientBN(config.api_key, config.api_secret)
binance_data = client_binance.get_all_coins_info()
binance_currencies, binance_all_chains, binance_deposit_status, binance_withdraw_status = process_binance_data(binance_data)
# Обработка данных Gate.io
gate_url = 'https://api.gateio.ws/api/v4/spot/currencies'
gate_data = fetch_parse_data(gate_url)
gate_currencies, gate_all_chains, gate_deposit_status, gate_withdraw_status = process_gate_data(gate_data)
# Обработка данных MEXC
mexc = MexcAPI(config.api_key_MX, config.api_secret_MX)
mexc_data = mexc.get_currency_information().json()
mexc_currencies, mexc_all_chains, mexc_deposit_status, mexc_withdraw_status = process_mexc_data(mexc_data)
Теперь ваш код более структурирован и легко читаем. Мы создали функции для повторяющихся задач, что позволило избежать дублирования кода. Подобный подход упрощает добавление новых криптобирж в будущем.
Not yet included in a published release.