1
0
mirror of https://github.com/mortdeus/legacy-cc.git synced 2026-10-08 03:42:05 +00:00
This commit is contained in:
cryptoking1106
2025-09-18 18:12:50 -03:00
parent 936e12cfc7
commit 086ec82844
141 changed files with 67491 additions and 6883 deletions

View File

@@ -0,0 +1,427 @@
// Dashboard JavaScript
class TradingBotDashboard {
constructor() {
this.charts = {};
this.refreshInterval = null;
this.init();
}
init() {
this.setupEventListeners();
this.initializeCharts();
this.startAutoRefresh();
this.loadInitialData();
}
setupEventListeners() {
// Refresh button
document.getElementById('refreshBtn').addEventListener('click', () => {
this.refreshAllData();
});
// Emergency close button
document.getElementById('emergencyCloseBtn').addEventListener('click', () => {
this.showEmergencyModal();
});
// Emergency modal
document.getElementById('confirmEmergencyClose').addEventListener('click', () => {
this.emergencyCloseAll();
});
document.getElementById('cancelEmergencyClose').addEventListener('click', () => {
this.hideEmergencyModal();
});
// Close modal on outside click
document.getElementById('emergencyModal').addEventListener('click', (e) => {
if (e.target.id === 'emergencyModal') {
this.hideEmergencyModal();
}
});
}
initializeCharts() {
// PnL Chart
const pnlCtx = document.getElementById('pnlChart').getContext('2d');
this.charts.pnl = new Chart(pnlCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Daily PnL (SOL)',
data: [],
borderColor: '#10b981',
backgroundColor: 'rgba(16, 185, 129, 0.1)',
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
labels: { color: '#ffffff' }
}
},
scales: {
x: {
ticks: { color: '#9ca3af' },
grid: { color: 'rgba(156, 163, 175, 0.2)' }
},
y: {
ticks: { color: '#9ca3af' },
grid: { color: 'rgba(156, 163, 175, 0.2)' }
}
}
}
});
// Positions Chart
const positionsCtx = document.getElementById('positionsChart').getContext('2d');
this.charts.positions = new Chart(positionsCtx, {
type: 'doughnut',
data: {
labels: ['Active', 'Closed'],
datasets: [{
data: [0, 0],
backgroundColor: ['#3b82f6', '#6b7280'],
borderWidth: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
labels: { color: '#ffffff' }
}
}
}
});
}
async loadInitialData() {
try {
await Promise.all([
this.loadStatus(),
this.loadRiskMetrics(),
this.loadPositions(),
this.loadHistory(),
this.loadConfiguration()
]);
} catch (error) {
console.error('Error loading initial data:', error);
this.showError('Failed to load dashboard data');
}
}
async refreshAllData() {
const refreshBtn = document.getElementById('refreshBtn');
refreshBtn.classList.add('animate-spin');
try {
await this.loadInitialData();
this.showSuccess('Dashboard refreshed successfully');
} catch (error) {
console.error('Error refreshing data:', error);
this.showError('Failed to refresh dashboard');
} finally {
refreshBtn.classList.remove('animate-spin');
}
}
startAutoRefresh() {
// Refresh data every 30 seconds
this.refreshInterval = setInterval(() => {
this.loadStatus();
this.loadRiskMetrics();
this.loadPositions();
}, 30000);
}
async loadStatus() {
try {
const response = await fetch('/api/status');
const data = await response.json();
// Update bot status
const statusElement = document.getElementById('botStatus');
statusElement.innerHTML = `
<i class="fas fa-circle mr-2"></i>${data.bot.status}
`;
statusElement.className = `font-bold status-${data.bot.status}`;
} catch (error) {
console.error('Error loading status:', error);
}
}
async loadRiskMetrics() {
try {
const response = await fetch('/api/risk');
const data = await response.json();
// Update quick stats
document.getElementById('activePositions').textContent = data.positionSummary.activePositions;
document.getElementById('dailyPnL').textContent = `${data.dailyStats.netPnL.toFixed(4)} SOL`;
document.getElementById('winRate').textContent = `${data.dailyStats.winRate}%`;
document.getElementById('riskLevel').textContent = data.riskLevel;
// Update PnL chart
this.updatePnLChart(data.dailyStats);
// Update positions chart
this.updatePositionsChart(data.positionSummary);
} catch (error) {
console.error('Error loading risk metrics:', error);
}
}
async loadPositions() {
try {
const response = await fetch('/api/positions');
const data = await response.json();
this.updatePositionsTable(data.positions);
} catch (error) {
console.error('Error loading positions:', error);
}
}
async loadHistory() {
try {
const response = await fetch('/api/history');
const data = await response.json();
this.updateHistoryTable(data.history);
} catch (error) {
console.error('Error loading history:', error);
}
}
async loadConfiguration() {
try {
const response = await fetch('/api/config');
const data = await response.json();
this.updateConfigurationGrid(data);
} catch (error) {
console.error('Error loading configuration:', error);
}
}
updatePnLChart(dailyStats) {
const chart = this.charts.pnl;
// Add current data point
const now = new Date();
const timeLabel = now.toLocaleTimeString();
chart.data.labels.push(timeLabel);
chart.data.datasets[0].data.push(dailyStats.netPnL);
// Keep only last 20 data points
if (chart.data.labels.length > 20) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
chart.update();
}
updatePositionsChart(positionSummary) {
const chart = this.charts.positions;
chart.data.datasets[0].data = [
positionSummary.activePositions,
positionSummary.totalPositions || 0
];
chart.update();
}
updatePositionsTable(positions) {
const tbody = document.getElementById('positionsTableBody');
if (positions.length === 0) {
tbody.innerHTML = `
<tr>
<td colspan="6" class="text-center p-6 text-gray-400">No active positions</td>
</tr>
`;
return;
}
tbody.innerHTML = positions.map(position => `
<tr class="border-b border-gray-700">
<td class="p-3">
<div class="flex items-center space-x-2">
<span class="font-mono text-sm">${position.mint.substring(0, 8)}...</span>
<button class="text-blue-400 hover:text-blue-300" onclick="copyToClipboard('${position.mint}')">
<i class="fas fa-copy"></i>
</button>
</div>
</td>
<td class="p-3">${position.entryPrice.toFixed(6)}</td>
<td class="p-3">${(position.currentPrice || position.entryPrice).toFixed(6)}</td>
<td class="p-3 ${position.pnl >= 0 ? 'text-green-400' : 'text-red-400'}">
${(position.pnl || 0).toFixed(4)} SOL
</td>
<td class="p-3">${this.formatDuration(position.holdTime)}</td>
<td class="p-3">
<button class="bg-red-600 hover:bg-red-700 px-3 py-1 rounded text-sm transition-colors"
onclick="closePosition('${position.mint}')">
Close
</button>
</td>
</tr>
`).join('');
}
updateHistoryTable(history) {
const tbody = document.getElementById('historyTableBody');
if (history.length === 0) {
tbody.innerHTML = `
<tr>
<td colspan="6" class="text-center p-6 text-gray-400">No trading history</td>
</tr>
`;
return;
}
tbody.innerHTML = history.slice(-10).reverse().map(trade => `
<tr class="border-b border-gray-700">
<td class="p-3">${new Date(trade.timestamp).toLocaleString()}</td>
<td class="p-3">
<span class="px-2 py-1 rounded text-xs ${trade.type === 'buy' ? 'bg-green-600' : 'bg-red-600'}">
${trade.type.toUpperCase()}
</span>
</td>
<td class="p-3">
<span class="font-mono text-sm">${trade.tokenMint.substring(0, 8)}...</span>
</td>
<td class="p-3">${trade.amount.toFixed(4)}</td>
<td class="p-3">${trade.price.toFixed(6)}</td>
<td class="p-3 ${trade.pnl >= 0 ? 'text-green-400' : 'text-red-400'}">
${trade.pnl ? trade.pnl.toFixed(4) : '-'}
</td>
</tr>
`).join('');
}
updateConfigurationGrid(config) {
const grid = document.getElementById('configGrid');
const configItems = [
{ label: 'Sniper Amount', value: `${config.trading.sniperAmount} SOL` },
{ label: 'Profit Target', value: `${config.trading.profitTarget}x` },
{ label: 'Stop Loss', value: `${config.trading.stopLoss}x` },
{ label: 'Max Hold Time', value: `${config.trading.maxHoldTime / 1000}s` },
{ label: 'Max Positions', value: config.trading.maxPositions },
{ label: 'Max Daily Loss', value: `${config.risk.maxDailyLoss} SOL` },
{ label: 'Swap Method', value: config.swap.method },
{ label: 'Slippage', value: `${config.swap.slippageTolerance}%` },
{ label: 'Priority Fee', value: `${config.swap.priorityFee} lamports` }
];
grid.innerHTML = configItems.map(item => `
<div class="bg-gray-800 p-4 rounded-lg">
<div class="text-sm text-gray-400">${item.label}</div>
<div class="text-lg font-semibold">${item.value}</div>
</div>
`).join('');
}
showEmergencyModal() {
document.getElementById('emergencyModal').classList.remove('hidden');
document.getElementById('emergencyModal').classList.add('flex');
}
hideEmergencyModal() {
document.getElementById('emergencyModal').classList.add('hidden');
document.getElementById('emergencyModal').classList.remove('flex');
}
async emergencyCloseAll() {
try {
this.hideEmergencyModal();
const response = await fetch('/api/emergency/close-all', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: 'dashboard_emergency' })
});
const result = await response.json();
if (result.success) {
this.showSuccess('Emergency closure initiated');
this.refreshAllData();
} else {
this.showError('Failed to initiate emergency closure');
}
} catch (error) {
console.error('Error during emergency closure:', error);
this.showError('Error during emergency closure');
}
}
formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
}
showSuccess(message) {
this.showNotification(message, 'success');
}
showError(message) {
this.showNotification(message, 'error');
}
showNotification(message, type) {
const notification = document.createElement('div');
notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
type === 'success' ? 'bg-green-600' : 'bg-red-600'
}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 3000);
}
}
// Global functions for table actions
window.copyToClipboard = function(text) {
navigator.clipboard.writeText(text).then(() => {
// Could show a toast notification here
});
};
window.closePosition = function(mint) {
// Implement individual position closure
console.log('Closing position for:', mint);
};
// Initialize dashboard when page loads
document.addEventListener('DOMContentLoaded', () => {
window.dashboard = new TradingBotDashboard();
});

View File

@@ -0,0 +1,192 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solana Trading Bot Dashboard</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.gradient-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.card {
backdrop-filter: blur(10px);
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
}
.status-running { color: #10b981; }
.status-stopped { color: #ef4444; }
.status-warning { color: #f59e0b; }
.refresh-btn:hover { transform: rotate(180deg); transition: transform 0.3s ease; }
</style>
</head>
<body class="bg-gray-900 text-white min-h-screen">
<!-- Header -->
<header class="gradient-bg p-6 shadow-lg">
<div class="container mx-auto flex justify-between items-center">
<div class="flex items-center space-x-4">
<i class="fas fa-robot text-3xl"></i>
<div>
<h1 class="text-2xl font-bold">Solana Trading Bot</h1>
<p class="text-blue-100">Advanced MEV Protection & Risk Management</p>
</div>
</div>
<div class="flex items-center space-x-4">
<div class="text-right">
<div class="text-sm text-blue-100">Status</div>
<div id="botStatus" class="font-bold status-running">
<i class="fas fa-circle mr-2"></i>Running
</div>
</div>
<button id="refreshBtn" class="refresh-btn bg-white bg-opacity-20 p-3 rounded-full hover:bg-opacity-30 transition-all">
<i class="fas fa-sync-alt text-white"></i>
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="container mx-auto p-6 space-y-6">
<!-- Quick Stats -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div class="card rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-blue-200 text-sm">Active Positions</p>
<p id="activePositions" class="text-2xl font-bold">-</p>
</div>
<i class="fas fa-chart-line text-2xl text-blue-400"></i>
</div>
</div>
<div class="card rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-blue-200 text-sm">Daily PnL</p>
<p id="dailyPnL" class="text-2xl font-bold">-</p>
</div>
<i class="fas fa-coins text-2xl text-green-400"></i>
</div>
</div>
<div class="card rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-blue-200 text-sm">Win Rate</p>
<p id="winRate" class="text-2xl font-bold">-</p>
</div>
<i class="fas fa-trophy text-2xl text-yellow-400"></i>
</div>
</div>
<div class="card rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-blue-200 text-sm">Risk Level</p>
<p id="riskLevel" class="text-2xl font-bold">-</p>
</div>
<i class="fas fa-shield-alt text-2xl text-red-400"></i>
</div>
</div>
</div>
<!-- Charts Row -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- PnL Chart -->
<div class="card rounded-lg p-6">
<h3 class="text-lg font-semibold mb-4">Daily PnL Trend</h3>
<canvas id="pnlChart" height="200"></canvas>
</div>
<!-- Positions Chart -->
<div class="card rounded-lg p-6">
<h3 class="text-lg font-semibold mb-4">Active Positions</h3>
<canvas id="positionsChart" height="200"></canvas>
</div>
</div>
<!-- Active Positions Table -->
<div class="card rounded-lg p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold">Active Positions</h3>
<button id="emergencyCloseBtn" class="bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg transition-colors">
<i class="fas fa-exclamation-triangle mr-2"></i>Emergency Close All
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full">
<thead>
<tr class="border-b border-gray-700">
<th class="text-left p-3">Token</th>
<th class="text-left p-3">Entry Price</th>
<th class="text-left p-3">Current Price</th>
<th class="text-left p-3">PnL</th>
<th class="text-left p-3">Hold Time</th>
<th class="text-left p-3">Actions</th>
</tr>
</thead>
<tbody id="positionsTableBody">
<tr>
<td colspan="6" class="text-center p-6 text-gray-400">Loading positions...</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Trading History -->
<div class="card rounded-lg p-6">
<h3 class="text-lg font-semibold mb-4">Recent Trades</h3>
<div class="overflow-x-auto">
<table class="w-full">
<thead>
<tr class="border-b border-gray-700">
<th class="text-left p-3">Time</th>
<th class="text-left p-3">Type</th>
<th class="text-left p-3">Token</th>
<th class="text-left p-3">Amount</th>
<th class="text-left p-3">Price</th>
<th class="text-left p-3">PnL</th>
</tr>
</thead>
<tbody id="historyTableBody">
<tr>
<td colspan="6" class="text-center p-6 text-gray-400">Loading history...</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Configuration -->
<div class="card rounded-lg p-6">
<h3 class="text-lg font-semibold mb-4">Bot Configuration</h3>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="configGrid">
<!-- Configuration will be populated here -->
</div>
</div>
</main>
<!-- Emergency Close Modal -->
<div id="emergencyModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
<div class="bg-gray-800 p-6 rounded-lg max-w-md w-full mx-4">
<h3 class="text-xl font-bold text-red-400 mb-4">
<i class="fas fa-exclamation-triangle mr-2"></i>Emergency Close All
</h3>
<p class="text-gray-300 mb-4">This will immediately close all active positions. Are you sure?</p>
<div class="flex space-x-3">
<button id="confirmEmergencyClose" class="bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg transition-colors">
Yes, Close All
</button>
<button id="cancelEmergencyClose" class="bg-gray-600 hover:bg-gray-700 px-4 py-2 rounded-lg transition-colors">
Cancel
</button>
</div>
</div>
</div>
<script src="dashboard.js"></script>
</body>
</html>

View File

@@ -0,0 +1,237 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import { config } from '../config.js';
import logger from '../utils/logger.js';
import riskManager from '../services/riskManager.js';
import notificationService from '../services/notifications.js';
const app = express();
const PORT = process.env.DASHBOARD_PORT || 3000;
// Rate limiting
const rateLimiter = new RateLimiterMemory({
keyGenerator: (req) => req.ip,
points: config.security.maxRequestsPerMinute,
duration: 60,
});
// Middleware
app.use(helmet());
app.use(cors());
app.use(compression());
app.use(express.json());
app.use(express.static('dashboard/public'));
// Rate limiting middleware
app.use(async (req, res, next) => {
try {
await rateLimiter.consume(req.ip);
next();
} catch (rejRes) {
res.status(429).json({
error: 'Too many requests',
retryAfter: Math.round(rejRes.msBeforeNext / 1000),
});
}
});
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
});
});
// Get bot status and configuration
app.get('/api/status', (req, res) => {
try {
const status = {
bot: {
status: 'running',
uptime: process.uptime(),
version: '2.0.0',
timestamp: new Date().toISOString(),
},
config: {
trading: config.trading,
risk: config.risk,
pools: config.pools,
},
};
res.json(status);
} catch (error) {
logger.error('Error getting bot status', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Get risk metrics
app.get('/api/risk', (req, res) => {
try {
const riskMetrics = riskManager.getRiskMetrics();
res.json(riskMetrics);
} catch (error) {
logger.error('Error getting risk metrics', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Get active positions
app.get('/api/positions', (req, res) => {
try {
const positions = riskManager.getActivePositions();
const summary = riskManager.getPositionSummary();
res.json({
positions,
summary,
timestamp: new Date().toISOString(),
});
} catch (error) {
logger.error('Error getting positions', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Get trading history
app.get('/api/history', (req, res) => {
try {
const history = riskManager.tradeHistory || [];
const dailyStats = riskManager.getDailyStats();
res.json({
history,
dailyStats,
timestamp: new Date().toISOString(),
});
} catch (error) {
logger.error('Error getting trading history', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Get daily statistics
app.get('/api/stats', (req, res) => {
try {
const dailyStats = riskManager.getDailyStats();
res.json(dailyStats);
} catch (error) {
logger.error('Error getting daily stats', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Emergency actions
app.post('/api/emergency/close-all', async (req, res) => {
try {
const { reason } = req.body;
const results = await riskManager.emergencyCloseAll(reason || 'dashboard_request');
res.json({
success: true,
message: 'Emergency closure initiated',
results,
timestamp: new Date().toISOString(),
});
} catch (error) {
logger.error('Error initiating emergency closure', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Send test notification
app.post('/api/notifications/test', async (req, res) => {
try {
const { message, type } = req.body;
await notificationService.sendNotification(
message || 'Test notification from dashboard',
type || 'info',
{ source: 'dashboard' }
);
res.json({
success: true,
message: 'Test notification sent',
timestamp: new Date().toISOString(),
});
} catch (error) {
logger.error('Error sending test notification', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Update configuration (read-only for now, could be extended)
app.get('/api/config', (req, res) => {
try {
// Return safe configuration (no sensitive data)
const safeConfig = {
trading: config.trading,
risk: config.risk,
pools: config.pools,
swap: config.swap,
logging: config.logging,
};
res.json(safeConfig);
} catch (error) {
logger.error('Error getting configuration', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// WebSocket endpoint for real-time updates (placeholder)
app.get('/api/ws', (req, res) => {
res.json({
message: 'WebSocket endpoint - implement with Socket.IO for real-time updates',
timestamp: new Date().toISOString(),
});
});
// Error handling middleware
app.use((error, req, res, next) => {
logger.error('Dashboard error', error);
res.status(500).json({
error: 'Internal server error',
message: error.message,
timestamp: new Date().toISOString(),
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
error: 'Endpoint not found',
timestamp: new Date().toISOString(),
});
});
// Start server
const server = app.listen(PORT, () => {
logger.info(`Dashboard server started on port ${PORT}`);
logger.info(`Dashboard available at: http://localhost:${PORT}`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
logger.info('SIGTERM received, shutting down dashboard server');
server.close(() => {
logger.info('Dashboard server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
logger.info('SIGINT received, shutting down dashboard server');
server.close(() => {
logger.info('Dashboard server closed');
process.exit(0);
});
});
export default app;