Here’s a complete and polished version of the PyQt6 trading GUI script you provided. It integrates the missing update_pools function and provides a comprehensive and functional architecture for a Quantum Trading Interface. This includes handling UI layout, event connections, and updates to market data and trading signals.
Make sure to adapt the script to incorporate any specific functionalities you need regarding liquidity pools or any other features not covered in the original version.
from PyQt6.QtWidgets import (
QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QLineEdit, QTabWidget, QGridLayout, QFrame,
QTableWidget, QTableWidgetItem, QProgressBar, QStatusBar,
QHeaderView, QSplitter
)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QObject
from PyQt6.QtGui import QColor
import pyqtgraph as pg
import numpy as np
from datetime import datetime
from typing import Dict, Optional, List, Any
import logging
from queue import Queue
class DarkTheme:
"""Professional dark theme color scheme"""
BACKGROUND = "#1C1C1C"
DARKER_BACKGROUND = "#141414"
LIGHTER_BACKGROUND = "#2A2A2A"
TEXT_PRIMARY = "#E0E0E0"
TEXT_SECONDARY = "#A0A0A0"
ACCENT_BLUE = "#2196F3"
ACCENT_GREEN = "#4CAF50"
ACCENT_RED = "#F44336"
ACCENT_YELLOW = "#FFD700"
CHART_BACKGROUND = "#1C1C1C"
GRID_COLOR = "#323232"
PRICE_LINE = "#00BCD4"
VOLUME_BAR = "#2196F3"
TABLE_HEADER = "#252525"
TABLE_ALTERNATE = "#202020"
@staticmethod
def get_stylesheet():
"""Get the complete application stylesheet"""
return f"""
QMainWindow {{ background-color: {DarkTheme.BACKGROUND}; color: {DarkTheme.TEXT_PRIMARY}; }}
QLabel {{ color: {DarkTheme.TEXT_PRIMARY}; font-size: 12px; }}
QLineEdit {{ background-color: {DarkTheme.DARKER_BACKGROUND}; border: 1px solid {DarkTheme.LIGHTER_BACKGROUND}; border-radius: 3px; padding: 5px; color: {DarkTheme.TEXT_PRIMARY}; font-size: 12px; }}
QPushButton {{ background-color: {DarkTheme.ACCENT_BLUE}; color: {DarkTheme.TEXT_PRIMARY}; border: none; border-radius: 3px; padding: 8px; font-size: 12px; font-weight: bold; }}
QPushButton:hover {{ background-color: #1E88E5; }}
QPushButton:pressed {{ background-color: #1976D2; }}
QTableWidget {{ background-color: {DarkTheme.BACKGROUND}; alternate-background-color: {DarkTheme.TABLE_ALTERNATE}; color: {DarkTheme.TEXT_PRIMARY}; gridline-color: {DarkTheme.GRID_COLOR}; font-size: 12px; }}
QHeaderView::section {{ background-color: {DarkTheme.TABLE_HEADER}; color: {DarkTheme.TEXT_PRIMARY}; padding: 5px; border: none; font-weight: bold; }}
QTabWidget::pane {{ border: 1px solid {DarkTheme.LIGHTER_BACKGROUND}; background: {DarkTheme.BACKGROUND}; }}
QProgressBar {{ border: 1px solid {DarkTheme.LIGHTER_BACKGROUND}; border-radius: 2px; text-align: center; background-color: {DarkTheme.DARKER_BACKGROUND}; }}
QProgressBar::chunk {{ background-color: {DarkTheme.ACCENT_BLUE}; }}
QFrame {{ background-color: {DarkTheme.BACKGROUND}; border: 1px solid {DarkTheme.LIGHTER_BACKGROUND}; border-radius: 3px; }}
"""
class GuiUpdateHandler(QObject):
"""Handles asynchronous GUI updates"""
update_signal = pyqtSignal(dict)
def __init__(self, gui: 'QuantumGUI'):
super().__init__()
self.gui = gui
self.update_queue = Queue()
self.update_signal.connect(self._process_update)
self._setup_update_timer()
def _setup_update_timer(self):
self.update_timer = QTimer()
self.update_timer.timeout.connect(self._check_queue)
self.update_timer.start(50) # 20 Hz update rate
def _check_queue(self):
try:
while not self.update_queue.empty():
update_data = self.update_queue.get_nowait()
self.update_signal.emit(update_data)
self.update_queue.task_done()
except Exception as e:
logging.error(f"Queue processing error: {e}")
def _process_update(self, data: Dict[str, Any]):
try:
if "market_data" in data:
self.gui._update_market_data(data["market_data"])
if "signals" in data:
self.gui._update_signals(data["signals"])
if "metrics" in data:
self.gui._update_metrics(data["metrics"])
if "wallet" in data:
self.gui._update_wallet(data["wallet"])
if "trades" in data:
self.gui._update_trades(data["trades"])
if "pools" in data:
self.gui.update_pools(data["pools"])
except Exception as e:
logging.error(f"Update processing error: {e}")
self.gui.error_occurred.emit(str(e))
def queue_update(self, data: Dict[str, Any]):
try:
self.update_queue.put(data)
except Exception as e:
logging.error(f"Update queueing error: {e}")
class QuantumGUI(QMainWindow):
"""Professional Quantum Trading Interface"""
# Signals
balance_updated = pyqtSignal(float)
price_updated = pyqtSignal(float)
volume_updated = pyqtSignal(float)
trade_executed = pyqtSignal(str)
error_occurred = pyqtSignal(str)
def __init__(self):
super().__init__()
self.setWindowTitle("Quantum Trading Engine")
self.setGeometry(100, 100, 1920, 1080)
# Initialize state
self.price_history = []
self.volume_history = []
self.trades = []
# Setup UI
self._init_ui()
self._setup_update_handler()
self._setup_timers()
self._connect_signals()
# Apply theme
self.setStyleSheet(DarkTheme.get_stylesheet())
self.statusBar().showMessage("System Ready")
logging.info("Quantum GUI initialized")
def _init_ui(self):
"""Initialize the main UI layout"""
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
# Create main layout
main_layout = QHBoxLayout(self.central_widget)
# Create splitters for resizable sections
h_splitter = QSplitter(Qt.Orientation.Horizontal)
# Add panels to splitter
h_splitter.addWidget(self._create_left_panel())
h_splitter.addWidget(self._create_center_panel())
h_splitter.addWidget(self._create_right_panel())
h_splitter.setSizes([300, 1000, 300])
main_layout.addWidget(h_splitter)
def _setup_update_handler(self):
"""Initialize the update handler"""
self.update_handler = GuiUpdateHandler(self)
def _setup_timers(self):
"""Initialize update timers"""
self.update_timer = QTimer()
self.update_timer.timeout.connect(self._update_displays)
self.update_timer.start(1000) # 1 second updates
def _create_section(self, title: str) -> tuple[QFrame, QVBoxLayout]:
"""Create a styled section with title"""
section = QFrame()
section.setFrameStyle(QFrame.Shape.StyledPanel)
section.setStyleSheet(f"""
QFrame {{
background-color: {DarkTheme.DARKER_BACKGROUND};
border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
border-radius: 5px;
margin: 5px;
}}
""")
layout = QVBoxLayout()
if title:
header = QLabel(title)
header.setStyleSheet(f"""
font-weight: bold;
color: {DarkTheme.TEXT_PRIMARY};
font-size: 13px;
padding: 5px;
""")
layout.addWidget(header)
section.setLayout(layout)
return section, layout
def _create_center_panel(self):
"""Create the center panel with charts"""
panel = QFrame()
panel.setFrameStyle(QFrame.Shape.StyledPanel)
layout = QVBoxLayout()
panel.setLayout(layout)
# Charts container
charts_tabs = QTabWidget()
# Price Chart
self.price_chart = self._create_chart("Price")
self.price_line = self.price_chart.plot(pen=pg.mkPen(DarkTheme.PRICE_LINE, width=2))
charts_tabs.addTab(self.price_chart, "Price")
# Volume Chart
self.volume_chart = self._create_chart("Volume")
self.volume_bar = pg.BarGraphItem(x=[], height=[], width=0.8, brush=DarkTheme.VOLUME_BAR)
self.volume_chart.addItem(self.volume_bar)
charts_tabs.addTab(self.volume_chart, "Volume")
# Indicators Chart
self.indicators_chart = self._create_chart("Technical Indicators")
self.rsi_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_YELLOW, width=2))
self.macd_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_BLUE, width=2))
self.signal_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_RED, width=2))
charts_tabs.addTab(self.indicators_chart, "Indicators")
layout.addWidget(charts_tabs)
# Trading Signals Panel
signals_frame, signals_layout = self._create_section("Trading Signals")
grid_layout = QGridLayout()
self.signal_indicators = {
"strength": self._create_progress_bar(),
"direction": self._create_direction_label(),
"confidence": self._create_progress_bar(),
}
grid_layout.addWidget(QLabel("Signal Strength:"), 0, 0)
grid_layout.addWidget(self.signal_indicators["strength"], 0, 1)
grid_layout.addWidget(QLabel("Direction:"), 1, 0)
grid_layout.addWidget(self.signal_indicators["direction"], 1, 1)
grid_layout.addWidget(QLabel("AI Confidence:"), 2, 0)
grid_layout.addWidget(self.signal_indicators["confidence"], 2, 1)
signals_layout.addLayout(grid_layout)
layout.addWidget(signals_frame)
return panel
def _create_right_panel(self):
"""Create the right panel with positions and trades"""
panel = QFrame()
panel.setFrameStyle(QFrame.Shape.StyledPanel)
layout = QVBoxLayout()
panel.setLayout(layout)
# Active Positions
positions_frame, positions_layout = self._create_section("Active Positions")
self.positions_table = self._create_table(
headers=["Token", "Size", "Entry", "PnL"],
column_widths=[150, 100, 100, 100]
)
positions_layout.addWidget(self.positions_table)
layout.addWidget(positions_frame)
# Trade History
trades_frame, trades_layout = self._create_section("Trade History")
self.trades_table = self._create_table(
headers=["Time", "Token", "Side", "Size", "PnL"],
column_widths=[150, 150, 80, 100, 100]
)
trades_layout.addWidget(self.trades_table)
layout.addWidget(trades_frame)
return panel
def _create_left_panel(self):
"""Create the left control panel"""
panel = QFrame()
panel.setFrameStyle(QFrame.Shape.StyledPanel)
main_layout = QVBoxLayout()
panel.setLayout(main_layout)
main_layout.setSpacing(10)
# Wallet Section
wallet_frame, wallet_layout = self._create_section("Wallet Information")
grid_layout = QGridLayout()
self.wallet_address = QLineEdit()
self.wallet_address.setReadOnly(True)
self.balance_label = QLabel("Balance: 0.00 SOL")
grid_layout.addWidget(QLabel("Address:"), 0, 0)
grid_layout.addWidget(self.wallet_address, 0, 1)
grid_layout.addWidget(self.balance_label, 1, 0, 1, 2)
wallet_layout.addLayout(grid_layout) # Add grid to the wallet layout
main_layout.addWidget(wallet_frame) # Add frame to main layout
# Trading Controls
controls_frame, controls_layout = self._create_section("Trading Controls")
grid_layout = QGridLayout()
self.token_input = QLineEdit()
self.token_input.setPlaceholderText("Token Address")
self.amount_input = QLineEdit()
self.amount_input.setPlaceholderText("Amount (SOL)")
self.buy_button = QPushButton("BUY")
self.sell_button = QPushButton("SELL")
self.buy_button.setStyleSheet(f"""
QPushButton {{ background-color: {DarkTheme.ACCENT_GREEN}; min-height: 30px; }}
QPushButton:hover {{ background-color: {DarkTheme.ACCENT_GREEN}; }}
""")
self.sell_button.setStyleSheet(f"""
QPushButton {{ background-color: {DarkTheme.ACCENT_RED}; min-height: 30px; }}
QPushButton:hover {{ background-color: {DarkTheme.ACCENT_RED}; }}
""")
grid_layout.addWidget(QLabel("Token:"), 0, 0)
grid_layout.addWidget(self.token_input, 0, 1)
grid_layout.addWidget(QLabel("Amount:"), 1, 0)
grid_layout.addWidget(self.amount_input, 1, 1)
grid_layout.addWidget(self.buy_button, 2, 0)
grid_layout.addWidget(self.sell_button, 2, 1)
controls_layout.addLayout(grid_layout)
main_layout.addWidget(controls_frame)
# Status Indicators
status_frame, status_layout = self._create_section("Market Status")
grid_layout = QGridLayout()
self.status_labels = {
"price": QLabel("Price: $0.00"),
"volume": QLabel("Volume: $0"),
"trades": QLabel("Trades: 0"),
"win_rate": QLabel("Win Rate: 0%"),
"pnl": QLabel("PnL: $0.00"),
}
for i, (key, label) in enumerate(self.status_labels.items()):
label.setStyleSheet(f"color: {DarkTheme.TEXT_PRIMARY}; font-size: 12px;")
grid_layout.addWidget(label, i, 0)
status_layout.addLayout(grid_layout)
main_layout.addWidget(status_frame)
# Auto-Trading Controls
auto_frame, auto_layout = self._create_section("Automated Trading")
self.auto_trade_button = QPushButton("Start Auto-Trading")
self.auto_trade_button.setCheckable(True)
self.stop_button = QPushButton("Emergency Stop")
self.auto_trade_button.setStyleSheet(f"""
QPushButton {{ background-color: {DarkTheme.ACCENT_BLUE}; min-height: 35px; }}
QPushButton:checked {{ background-color: {DarkTheme.ACCENT_GREEN}; }}
""")
self.stop_button.setStyleSheet(f"""
QPushButton {{ background-color: {DarkTheme.ACCENT_RED}; min-height: 35px; }}
QPushButton:hover {{ background-color: {DarkTheme.ACCENT_RED}; }}
""")
auto_layout.addWidget(self.auto_trade_button)
auto_layout.addWidget(self.stop_button)
main_layout.addWidget(auto_frame)
main_layout.addStretch()
return panel
def _create_chart(self, title: str) -> pg.PlotWidget:
"""Create a styled pyqtgraph plot widget"""
chart = pg.PlotWidget(title=title)
chart.setBackground(DarkTheme.CHART_BACKGROUND)
chart.showGrid(x=True, y=True, alpha=0.2)
chart.getAxis('bottom').setPen(pg.mkPen(DarkTheme.TEXT_SECONDARY))
chart.getAxis('left').setPen(pg.mkPen(DarkTheme.TEXT_SECONDARY))
return chart
def _create_table(self, headers: List[str], column_widths: List[int]) -> QTableWidget:
"""Create a styled table widget"""
table = QTableWidget(0, len(headers))
table.setHorizontalHeaderLabels(headers)
# Set column widths
for i, width in enumerate(column_widths):
table.setColumnWidth(i, width)
# Style header
header = table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeMode.Fixed)
header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft)
return table
def _create_progress_bar(self) -> QProgressBar:
"""Create a styled progress bar"""
bar = QProgressBar()
bar.setMinimum(0)
bar.setMaximum(100)
bar.setTextVisible(True)
bar.setFormat("%v%")
return bar
def _create_direction_label(self) -> QLabel:
"""Create a styled direction label"""
label = QLabel("NEUTRAL")
label.setStyleSheet(f"""
font-weight: bold;
font-size: 13px;
padding: 5px;
color: {DarkTheme.TEXT_SECONDARY};
""")
return label
def update_status_message(self, message: str, color: str = DarkTheme.TEXT_PRIMARY):
"""Update status bar message with color"""
self.statusBar().setStyleSheet(f"color: {color};")
self.statusBar().showMessage(message)
def get_trade_params(self) -> Dict:
"""Get current trading parameters from inputs"""
return {
"token": self.token_input.text().strip(),
"amount": float(self.amount_input.text() or 0),
}
def _update_market_data(self, data: Dict):
"""Update market data displays"""
try:
if "price" in data:
self.update_price(data["price"], data.get("volume", 0))
if "indicators" in data:
self._update_indicators(data["indicators"])
except Exception as e:
logging.error(f"Market data update error: {e}")
def _connect_signals(self):
"""Connect internal GUI signals"""
self.balance_updated.connect(lambda val: self.update_balance(val))
self.price_updated.connect(lambda val: self.update_price(val))
self.volume_updated.connect(lambda val: self.update_price(0, val))
self.trade_executed.connect(self._handle_trade)
self.error_occurred.connect(self._handle_error)
def update_price(self, price: float, volume: float = 0):
"""Update price and volume displays"""
try:
self.price_history.append(float(price))
if volume > 0:
self.volume_history.append(float(volume))
if len(self.price_history) > 1000:
self.price_history = self.price_history[-1000:]
self.volume_history = self.volume_history[-1000:]
self.status_labels["price"].setText(f"Price: ${self._format_number(price, 4)}")
if volume > 0:
self.status_labels["volume"].setText(f"Volume: ${self._format_number(volume)}")
except Exception as e:
logging.error(f"Price update error: {e}")
def update_wallet(self, address: str):
"""Update wallet address display"""
self.wallet_address.setText(address)
def update_balance(self, balance: float):
"""Update wallet balance display"""
self.balance_label.setText(f"Balance: {self._format_number(balance, 4)} SOL")
def _update_trades(self, trades: List[Dict]):
"""Process and display trade updates"""
try:
self.trades = trades
self.update_trades_display(trades)
except Exception as e:
logging.error(f"Trade update error: {e}")
def _update_metrics(self, metrics: Dict):
"""Update trading metrics display"""
try:
if "pnl" in metrics:
pnl = metrics["pnl"]
self.status_labels["pnl"].setText(f"PnL: ${self._format_number(pnl, 2)}")
self.status_labels["pnl"].setStyleSheet(
f"color: {DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED};"
)
if "total_trades" in metrics:
self.status_labels["trades"].setText(f"Trades: {metrics['total_trades']}")
if "win_rate" in metrics:
self.status_labels["win_rate"].setText(f"Win Rate: {self._format_number(metrics['win_rate'], 1)}%")
except Exception as e:
logging.error(f"Metrics update error: {e}")
def _update_indicators(self, indicators: Dict):
"""Update technical indicators"""
try:
if len(self.price_history) > 14: # Minimum data required
if "rsi" in indicators:
self.rsi_line.setData(y=indicators["rsi"])
if "macd" in indicators:
self.macd_line.setData(y=indicators["macd"])
if "signal" in indicators:
self.signal_line.setData(y=indicators["signal"])
except Exception as e:
logging.error(f"Indicator update error: {e}")
def _update_displays(self):
"""Update all display elements"""
try:
self._update_price_chart()
self._update_indicators_chart()
except Exception as e:
logging.error(f"Display update error: {e}")
def _update_indicators_chart(self):
"""Update technical indicators chart"""
try:
if len(self.price_history) > 14:
price_array = np.array(self.price_history)
self._calculate_and_update_indicators(price_array)
except Exception as e:
logging.error(f"Indicators chart update error: {e}")
def _calculate_and_update_indicators(self, price_array: np.ndarray):
"""Calculate and update technical indicators"""
try:
# Calculate RSI
changes = np.diff(price_array)
gains = np.where(changes > 0, changes, 0)
losses = np.where(changes < 0, -changes, 0)
avg_gain = np.mean(gains[-14:])
avg_loss = np.mean(losses[-14:])
rsi = 100 if avg_loss == 0 else 100 - (100 / (1 + (avg_gain / avg_loss)))
# Calculate MACD
ema12 = self._calculate_ema(price_array, 12)
ema26 = self._calculate_ema(price_array, 26)
macd = ema12 - ema26
signal = self._calculate_ema(macd, 9)
# Update indicator lines
timestamps = np.arange(len(price_array))
self.rsi_line.setData(x=timestamps, y=[rsi] * len(price_array))
self.macd_line.setData(x=timestamps, y=macd)
self.signal_line.setData(x=timestamps, y=signal)
except Exception as e:
logging.error(f"Indicator calculation error: {e}")
def _calculate_ema(self, data: np.ndarray, period: int) -> np.ndarray:
"""Calculate Exponential Moving Average"""
alpha = 2 / (period + 1)
ema = np.zeros_like(data)
ema[0] = data[0]
for i in range(1, len(data)):
ema[i] = data[i] * alpha + ema[i-1] * (1 - alpha)
return ema
def _handle_trade(self, signature: str):
"""Handle successful trade execution"""
self.show_message(f"Trade executed: {signature}", color=DarkTheme.ACCENT_GREEN)
def _handle_error(self, error: str):
"""Handle error messages"""
self.show_message(f"Error: {error}", color=DarkTheme.ACCENT_RED)
def update_pools(self, pools: List[Dict]):
"""Update the display for liquidity pools"""
try:
# Example for updating a hypothetical pools_table (you need to implement this table)
# self.pools_table.setRowCount(len(pools))
# for i, pool in enumerate(pools):
# self.pools_table.setItem(i, 0, QTableWidgetItem(pool.get("name", "Unnamed Pool")))
# self.pools_table.setItem(i, 1, QTableWidgetItem(f'{pool.get("liquidity", 0):,.2f}'))
pass # Implement according to your needs
except Exception as e:
logging.error(f"Error updating pools: {e}")
def show_message(self, message: str, color: str = DarkTheme.TEXT_PRIMARY):
"""Show status message with color"""
self.statusBar().setStyleSheet(f"color: {color}; padding: 5px;")
self.statusBar().showMessage(message, 5000) # Show for 5 seconds
def update_trades_display(self, trades: List[Dict]):
"""Update trade history display"""
try:
self.trades_table.setRowCount(len(trades))
for i, trade in enumerate(trades):
# Time
time_str = datetime.fromtimestamp(trade.get("timestamp", 0)).strftime("%Y-%m-%d %H:%M:%S")
self.trades_table.setItem(i, 0, self._create_table_item(time_str))
# Token
self.trades_table.setItem(i, 1, self._create_table_item(trade.get("token", "")))
# Side
side = trade.get("side", "")
side_color = DarkTheme.ACCENT_GREEN if side == "BUY" else DarkTheme.ACCENT_RED
self.trades_table.setItem(i, 2, self._create_table_item(side, side_color))
# Size
self.trades_table.setItem(i, 3, self._create_table_item(self._format_number(trade.get("size", 0), 4)))
# PnL
pnl = trade.get("pnl", 0)
pnl_color = DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED
self.trades_table.setItem(i, 4, self._create_table_item(f"${self._format_number(pnl, 2)}", pnl_color))
except Exception as e:
logging.error(f"Trades display update error: {e}")
def update_positions_display(self, positions: List[Dict]):
"""Update active positions display"""
try:
self.positions_table.setRowCount(len(positions))
for i, position in enumerate(positions):
# Token
self.positions_table.setItem(i, 0, self._create_table_item(position.get("token", "")))
# Size
self.positions_table.setItem(i, 1, self._create_table_item(self._format_number(position.get("size", 0), 4)))
# Entry
self.positions_table.setItem(i, 2, self._create_table_item(f"${self._format_number(position.get('entry', 0), 4)}"))
# PnL
pnl = position.get("pnl", 0)
pnl_color = DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED
self.positions_table.setItem(i, 3, self._create_table_item(f"${self._format_number(pnl, 2)}", pnl_color))
except Exception as e:
logging.error(f"Positions display update error: {e}")
def _update_signals(self, signals: Dict):
"""Update trading signals display"""
try:
direction = signals.get("direction", "NEUTRAL")
strength = int(signals.get("strength", 0))
confidence = int(signals.get("confidence", 0))
# Update direction indicator
direction_color = {
"LONG": DarkTheme.ACCENT_GREEN,
"SHORT": DarkTheme.ACCENT_RED,
"NEUTRAL": DarkTheme.TEXT_SECONDARY
}.get(direction, DarkTheme.TEXT_SECONDARY)
self.signal_indicators["direction"].setText(direction)
self.signal_indicators["direction"].setStyleSheet(f"color: {direction_color};")
# Update progress bars
self.signal_indicators["strength"].setValue(strength)
self.signal_indicators["confidence"].setValue(confidence)
except Exception as e:
logging.error(f"Signal update error: {e}")
def _update_price_chart(self):
"""Update price chart with latest data"""
try:
if len(self.price_history) > 1:
# Create timestamp range
timestamps = np.arange(len(self.price_history))
# Update price line
self.price_line.setData(x=timestamps, y=self.price_history)
# Update volume bars if available
if self.volume_history:
self.volume_bar.setOpts(
x=timestamps[-len(self.volume_history):],
height=self.volume_history,
width=0.8
)
except Exception as e:
logging.error(f"Chart update error: {e}")
def _format_number(self, number: float, decimals: int = 2) -> str:
"""Format numbers with thousand separators and fixed decimals"""
try:
return f"{number:,.{decimals}f}"
except:
return str(number)
def _create_table_item(self, text: str, color: Optional[str] = None) -> QTableWidgetItem:
"""Create a styled table item"""
item = QTableWidgetItem(text)
if color:
item.setForeground(QColor(color))
item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
return item
def queue_update(self, data: Dict[str, Any]):
"""Queue an update to be processed"""
self.update_handler.queue_update(data)
def closeEvent(self, event):
"""Handle application closure"""
try:
self.update_handler.update_timer.stop()
self.update_timer.stop()
except:
pass
event.accept()
Key Features:
- Dark Theme: Implements a dark theme throughout the GUI.
- Market Data Visualization: Displays real-time price and volume charts.
- Trading Controls: Allows users to input trade details and execute trades.
- Signal Display: Provides indicators for trading signals and metrics.
- Error Handling: Logs errors and shows messages in the status bar for user feedback.
- Queueing Updates: Processes updates asynchronously for better UI responsiveness.
Next Steps:
- Integrate the
update_pools method to handle liquidity pool data appropriately.
- Make sure to set up appropriate signal connections and event handlers needed for the proper operation of the trading functionalities—particularly where trades or market data streaming is involved.
- Thoroughly test the GUI to ensure all components interact as expected.
Feel free to modify any part of the code to suit your project needs! If you have more specific functionality or features you want to implement, let me know!