classCryptoPriceApp:
def __init__(self, root):
self.root = root
self.root.title("实时加密货币价格追踪器")
self.root.geometry("900x700")
self.root.resizable(False, False)
# 初始化支持的交易所
self.exchanges = ["binance", "kraken", "bitfinex", "okx", "kucoin", "gateio"]
self.exchange_instances = {name: getattr(ccxt, name)() for name inself.exchanges}
# 存储交易对和历史价格
self.symbol_map = {}
self.previous_prices = {}
# 创建用户界面
self.create_widgets()
# 启动后台任务
self.start_exchange_threads()
self.start_connection_check_thread()
def create_widgets(self):
# 控制面板
control_frame = tk.Frame(self.root, pady=10)
control_frame.pack(fill="x", padx=20)
tk.Label(control_frame, text="选择交易所:", font=("Helvetica", 12)).grid(row=0, column=0, padx=10)
self.exchange_var = tk.StringVar(value=self.exchanges[0])
self.exchange_dropdown = ttk.Combobox(control_frame, textvariable=self.exchange_var, values=self.exchanges, state="readonly", width=20)
self.exchange_dropdown.grid(row=0, column=1, padx=10)
tk.Label(control_frame, text="选择交易对:", font=("Helvetica", 12)).grid(row=1, column=0, padx=10)
self.symbol_var = tk.StringVar()
self.symbol_dropdown = ttk.Combobox(control_frame, textvariable=self.symbol_var, state="readonly", width=30)
self.symbol_dropdown.grid(row=1, column=1, padx=10)
# 添加和删除按钮
button_frame = tk.Frame(control_frame)
button_frame.grid(row=0, column=2, rowspan=2, padx=20)
ttk.Button(button_frame, text="添加", command=self.add_to_table).pack(side="top", pady=5)
ttk.Button(button_frame, text="删除", command=self.delete_selected).pack(side="top", pady=5)
# 实时价格表
table_frame = tk.Frame(self.root)
table_frame.pack(fill="both", expand=True, padx=20, pady=10)
self.tree = ttk.Treeview(table_frame, columns=("交易所", "交易对", "买入价", "卖出价", "更新时间"), show="headings", height=15)
for col inself.tree["columns"]:
self.tree.heading(col, text=col)
self.tree.column(col, anchor="center")
self.tree.pack(fill="both", expand=True)
# 日志区域
log_frame = tk.Frame(self.root, pady=10)
log_frame.pack(fill="x", padx=20)
tk.Label(log_frame, text="日志", font=("Helvetica", 12, "bold")).pack(anchor="w")
self.log_text = tk.Text(log_frame, height=10, state="disabled", wrap="word", bg="#f0f0f0")
self.log_text.pack(fill="x", padx=5, pady=5)
def update_prices_for_exchange(self, exchange_name):
whileTrue:
for item inself.tree.get_children():
values = self.tree.item(item, "values")
if values[0] == exchange_name:
try:
ticker = self.exchange_instances[exchange_name].fetch_ticker(values[1])
new_bid = ticker.get("bid", "N/A")
new_ask = ticker.get("ask", "N/A")
last_updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.tree.item(item, values=(values[0], values[1], new_bid, new_ask, last_updated))
exceptExceptionas e:
self.log_message(f"价格更新失败:{exchange_name} - {values[1]}:{e}")
time.sleep(1)