def filter_symbols():
search_text = entry_search.get().lower()
filtered_symbols = [symbol for symbol in symbols if search_text in symbol.lower()]
menu = symbol_menu['menu']
menu.delete(0, 'end')
for symbol in filtered_symbols:
menu.add_command(label=symbol, command=lambda value=symbol: selected_symbol.set(value) or update_units())
if filtered_symbols:
selected_symbol.set(filtered_symbols[0])
update_units()
The error message indicates that the script is attempting to fetch the current price for a symbol that is not recognized by the MEXC exchange API. This typically happens when the symbol used is not available or not formatted correctly for the exchange you're connecting to.
Here are a few steps you can take to troubleshoot and potentially resolve the issue:
Функция для обновления минимального объема торговли
def update_min_trade_volume(symbol):
try:
market = exchange.market(symbol)
min_volume = market['limits']['amount']['min']
label_min_volume.config(text=f"Мин. объем для {symbol}: {min_volume}")
except Exception as e:
logging.error("Ошибка получения минимального объема: %s", e)
label_min_volume.config(text="Ошибка получения минимального объема")
Функция для обновления UI
def update_ui():
symbol = selected_symbol.get()
current_price = get_current_price(symbol)
if current_price:
label_current_price.config(text=f"Текущая цена: {current_price:.2f}")
code
if session_start_time:
elapsed_time = datetime.now() - session_start_time
label_session_time.config(text=f"Время сессии: {str(elapsed_time).split('.')[0]}")
connection_status.config(bg="green" if connected else "red")
update_open_positions_display()
root.after(1000, update_ui)
def buy(symbol, cost):
try:
# Проверка на то, что сумма положительна
if cost <= 0:
messagebox.showerror("Ошибка", "Сумма должна быть положительной.")
return None
code
current_price = get_current_price(symbol)
# Проверка, что текущая цена корректна и положительна
if current_price is None or current_price <= 0:
messagebox.showerror("Ошибка", "Не удалось получить корректную текущую цену.")
return None
# Извлечение минимального объема торговли для проверки
market = exchange.market(symbol)
min_volume = market['limits']['amount']['min']
# Рассчитываем количество единиц
amount_units = cost / current_price
# Проверка расчета объема
if amount_units < min_volume:
messagebox.showerror("Ошибка", f"Минимальный объем для торговли: {min_volume}. Невозможно купить на {amount_units}.")
return None
# Повторная проверка объема
if amount_units <= 0:
messagebox.showerror("Ошибка", "Количество единиц должно быть положительным.")
return None
# Выполняем ордер на покупку
order = exchange.create_order(symbol, 'market', 'buy', amount_units)
logging.info("Покупка: %s", order)
save_trade_state('buy', order)
open_positions.append(order)
log_trade('buy', order)
return order['price']
except Exception as e:
logging.error("Ошибка покупки: %s", e)
messagebox.showerror("Ошибка", f"Не удалось купить: {e}")
return None
Функция для продажи на заданную сумму в валюте
def sell(symbol, cost):
try:
# Проверка на то, что сумма положительна
if cost <= 0:
messagebox.showerror("Ошибка", "Сумма должна быть положительной.")
return None
code
current_price = get_current_price(symbol)
# Проверка, что текущая цена корректна и положительна
if current_price is None or current_price <= 0:
messagebox.showerror("Ошибка", "Не удалось получить корректную текущую цену.")
return None
# Извлечение минимального объема торговли для проверки
market = exchange.market(symbol)
min_volume = market['limits']['amount']['min']
# Рассчитываем количество единиц
amount_units = cost / current_price
# Проверка расчета объема
if amount_units < min_volume:
messagebox.showerror("Ошибка", f"Минимальный объем для торговли: {min_volume}. Невозможно продать {amount_units}.")
return None
# Повторная проверка объема
if amount_units <= 0:
messagebox.showerror("Ошибка", "Количество единиц должно быть положительным.")
return None
# Выполняем ордер на продажу
order = exchange.create_market_sell_order(symbol, amount_units)
logging.info("Продажа: %s", order)
if open_positions:
last_buy_order = open_positions.pop()
profit = (order['price'] - last_buy_order['price']) * amount_units
save_trade_state('sell', order, profit)
log_trade('sell', order, profit)
return order['price']
except Exception as e:
logging.error("Ошибка продажи: %s", e)
messagebox.showerror("Ошибка", f"Не удалось продать: {e}")
return None
def save_trade_state(action, order, profit=0):
with open('trading_bot_state.log', 'a') as f:
f.write(f"{action},{order['symbol']},{order['amount']},{order['price']},{profit}\n")
Загрузка состояния торговли из логов
def load_trade_state():
global session_profit, open_positions
try:
with open('trading_bot_state.log', 'r') as f:
lines = f.readlines()
open_positions = []
for line in lines:
action, symbol, amount, price, profit = line.strip().split(',')
if action == 'buy':
open_positions.append({'symbol': symbol, 'amount': float(amount), 'price': float(price)})
session_profit += float(profit)
except FileNotFoundError:
logging.info("Лог состояния торговли не найден.")
def update_trade_history_display():
text_history.delete(1.0, tk.END)
for trade in trade_history:
text_history.insert(tk.END, f"{trade['timestamp']} {trade['action'].upper()} {trade['amount']} {trade['symbol']} @ {trade['price']} Profit: {trade['profit']}\n")
Функция для обновления открытых позиций
def update_open_positions_display():
open_orders_text.delete(1.0, tk.END)
for position in open_positions:
current_profit = calculate_current_profit(position)
open_orders_text.insert(tk.END, f"{position['symbol']} {position['amount']} @ {position['price']} Current Profit: {current_profit:.2f}\n")
label_amount = tk.Label(root, text='Сумма (в фиатной или криптовалюте):')
label_amount.pack()
entry_amount = tk.Entry(root)
entry_amount.pack()
entry_amount.insert(tk.END, '10') # Пример значения суммы
update_ui()
root.mainloop() ERROR:root:Ошибка при получении текущей цены: mexc does not have market symbol
ERROR:root:Ошибка при получении текущей цены: mexc does not have market symbol
Verify Symbol Format: The format of the symbol should be exactly as expected by the exchange, usually something like BTC/USDT. Ensure that the symbol provided in your code matches the format used by MEXC.
Load and Inspect Market Data: After loading the markets with exchange.load_markets(), inspect the markets object to see what symbols are available and ensure that the symbol you're trying to access is listed.
Update the Symbol List: Make sure that the symbols list is populated correctly when loading markets. Use a print statement or logging to confirm the list of symbols retrieved:
python
print(symbols)
Check Case Sensitivity: Symbols in crypto exchanges can be case-sensitive. Ensure that the symbol you're using (e.g., BTC/USDT) matches the case of symbols provided by the exchange.
Error Handling: Use better error handling to catch and display issues with missing or unrecognized symbols, allowing for easier debugging:
python
try:
symbol = selected_symbol.get()
if symbol not in markets:
raise ValueError("Symbol not found")
except ValueError as ve:
logging.error("Invalid symbol: %s", ve)
Network and API Key Issues: Ensure that your network connection is stable and that your API keys are correctly set up with the necessary permissions. Sometimes, connectivity or authentication issues might prevent accessing exchange data correctly.
Exchange Updates: Occasionally, exchanges update their APIs or remove certain pairs. Check if MEXC has made any such changes by visiting their official API documentation or support channels.
If these steps do not resolve the issue, review the MEXC API documentation for any additional requirements or updates related to market symbol usage.