check code and suggest improvement-# DeepBot/core/bot.py import ccxt import tkinter as…
- User
check code and suggest improvement-# DeepBot/core/bot.py import ccxt import tkinter as tk from tkinter import ttk import threading import queue import numpy as np import pandas as pd import os import logging import json from datetime import datetime from pathlib import Path
Konfiguracja ścieżek
BASE_DIR = Path("/Users/time27/Downloads/DeepBot") CONFIG_DIR = BASE_DIR / "config" DATA_DIR = BASE_DIR / "data" LOGS_DIR = BASE_DIR / "logs"
CONFIG_DIR.mkdir(exist_ok=True) DATA_DIR.mkdir(exist_ok=True) LOGS_DIR.mkdir(exist_ok=True)
Inicjalizacja logowania
logging.basicConfig( filename=LOGS_DIR / 'bot_runtime.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filemode='a' )
class StableTradingBot: def init(self, master): self.master = master self.setup_environment() self.init_components() self.setup_ui()
def setup_environment(self): """Inicjalizacja środowiska i konfiguracji""" self.config = self.load_config() self.exchange = self.init_exchange() self.data_queue = queue.Queue(maxsize=100) self.historical_data = [] self.running = False def init_exchange(self): """Inicjalizacja połączenia z giełdą""" try: return ccxt.mexc({ 'apiKey': os.getenv('MEXC_API_KEY'), 'secret': os.getenv('MEXC_SECRET'), 'enableRateLimit': True, 'rateLimit': 3000 # Zwiększony limit dla stabilności }) except Exception as e: logging.critical(f"Exchange init failed: {str(e)}") raise def load_config(self): """Wczytywanie konfiguracji z pliku""" config_path = CONFIG_DIR / 'bot_config.json' try: with open(config_path) as f: return json.load(f) except FileNotFoundError: logging.warning("Using default configuration") return { "risk_percent": 1, "max_leverage": 10, "update_interval": 2.0 } def setup_ui(self): """Inicjalizacja interfejsu użytkownika""" self.master.title("StableBot v2.0") self.create_control_panel() self.create_status_display() def create_control_panel(self): """Panel kontrolny""" frame = ttk.Frame(self.master, padding=10) frame.pack(side=tk.TOP, fill=tk.X) ttk.Button(frame, text="Start", command=self.safe_start).grid(row=0, column=0) ttk.Button(frame, text="Stop", command=self.safe_stop).grid(row=0, column=1) def create_status_display(self): """Panel statusu""" self.status_text = tk.Text(self.master, height=15, width=60) self.status_text.pack(padx=10, pady=10) def init_components(self): """Inicjalizacja komponentów systemu""" self.data_processor = threading.Thread(target=self.process_data) self.data_processor.daemon = True def safe_start(self): """Bezpieczne uruchomienie systemu""" if not self.running: self.running = True self.data_processor.start() threading.Thread(target=self.data_stream).start() logging.info("System started") def safe_stop(self): """Bezpieczne zatrzymanie systemu""" if self.running: self.running = False self.data_processor.join(timeout=5) logging.info("System stopped") def data_stream(self): """Strumień danych z ograniczeniem częstotliwości""" while self.running: try: ticker = self.exchange.fetch_ticker('VIRTUAL/USDT') if self.data_queue.qsize() < 90: # Zapobiegaj przepełnieniu self.data_queue.put(ticker) self.update_display(ticker) threading.Event().wait(self.config['update_interval']) except Exception as e: logging.error(f"Data stream error: {str(e)}") self.handle_error(e) def process_data(self): """Uproszczony proces przetwarzania danych""" while self.running: try: if not self.data_queue.empty(): data = self.data_queue.get() self.store_data(data) self.execute_safety_checks() except queue.Empty: continue except Exception as e: logging.error(f"Processing error: {str(e)}") def store_data(self, data): """Bezpieczne przechowywanie danych z rotacją plików""" file_path = DATA_DIR / 'ticker_data.csv' try: df = pd.DataFrame([{ 'timestamp': datetime.now().isoformat(), 'price': data['last'], 'volume': data['baseVolume'] }]) if file_path.exists(): df.to_csv(file_path, mode='a', header=False, index=False) else: df.to_csv(file_path, index=False) # Rotacja plików co 100MB if file_path.stat().st_size > 100_000_000: backup_path = DATA_DIR / f"ticker_backup_{datetime.now().timestamp()}.csv" file_path.rename(backup_path) except Exception as e: logging.error(f"Data storage failed: {str(e)}") def execute_safety_checks(self): """Automatyczne testy stabilnościowe""" memory_usage = os.getpid().memory_info().rss / 1024 ** 2 if memory_usage > 512: # 512MB limit logging.critical(f"Memory overflow: {memory_usage:.2f}MB") self.safe_stop() def update_display(self, data): """Aktualizacja interfejsu z ograniczeniem częstotliwości""" def _update(): current_text = self.status_text.get("1.0", tk.END) new_entry = f"[{datetime.now().strftime('%H:%M:%S')}] Price: {data['last']:.6f}\n" self.status_text.delete("1.0", tk.END) self.status_text.insert(tk.END, new_entry + current_text[:1000]) if self.running: self.master.after(500, _update) def handle_error(self, error): """Zunifikowana obsługa błędów""" error_msg = f"CRITICAL ERROR: {str(error)}" logging.error(error_msg) self.safe_stop() self.status_text.insert(tk.END, f"\n{error_msg}") Assistant