Download script.js from has7bro/crypto-arbitrage-radar-pro: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/has7bro/crypto-arbitrage-radar-pro/resolve/main/script.js
- Command line
-
hf download hf://spaces/has7bro/crypto-arbitrage-radar-pro/script.js
-
curl -L -o script.js https://huggingface.co/spaces/has7bro/crypto-arbitrage-radar-pro/resolve/main/script.js
13.5 kB
| // Main Arbitrage Dashboard Logic | |
| function arbitrageDashboard() { | |
| return { | |
| // State | |
| selectedPair: 'BTC/USDT', | |
| selectedExchanges: ['binance', 'okx', 'bybit'], | |
| exchanges: [], | |
| marketData: {}, | |
| connectionStatus: 'disconnected', | |
| activeConnections: 0, | |
| sortBy: 'spread', | |
| lastUpdate: 'Never', | |
| bestSpread: 0, | |
| opportunitiesCount: 0, | |
| arbitrageOpportunities: [], | |
| // Initialize dashboard | |
| async init() { | |
| await this.loadConfiguration(); | |
| await this.initializeExchanges(); | |
| this.startMonitoring(); | |
| this.setupEventListeners(); | |
| }, | |
| // Load exchange configuration | |
| async loadConfiguration() { | |
| try { | |
| const response = await fetch('config.json'); | |
| const config = await response.json(); | |
| this.exchanges = config.exchanges; | |
| this.selectedPair = config.defaultPair || 'BTC/USDT'; | |
| } catch (error) { | |
| console.error('Failed to load configuration:', error); | |
| // Fallback configuration | |
| this.exchanges = [ | |
| { id: 'binance', name: 'Binance', ws: true, connected: false }, | |
| { id: 'okx', name: 'OKX', ws: true, connected: false }, | |
| { id: 'bybit', name: 'Bybit', ws: true, connected: false }, | |
| { id: 'kraken', name: 'Kraken', ws: true, connected: false }, | |
| { id: 'huobi', name: 'Huobi', ws: true, connected: false } | |
| ]; | |
| } | |
| }, | |
| // Initialize exchange instances | |
| async initializeExchanges() { | |
| this.exchanges.forEach(exchange => { | |
| try { | |
| if (window.ccxt && window.ccxt[exchange.id]) { | |
| this.marketData[exchange.id] = { | |
| exchangeName: exchange.name, | |
| bid: 0, | |
| ask: 0, | |
| volume: 0, | |
| spread: 0, | |
| timestamp: 'Never', | |
| connected: false | |
| }; | |
| } catch (error) { | |
| console.error(`Failed to initialize ${exchange.name}:`, error); | |
| } | |
| }); | |
| }, | |
| // Start monitoring selected exchanges | |
| startMonitoring() { | |
| this.selectedExchanges.forEach(exchangeId => { | |
| this.connectToExchange(exchangeId); | |
| }); | |
| }, | |
| // Connect to specific exchange | |
| async connectToExchange(exchangeId) { | |
| const exchange = this.exchanges.find(e => e.id === exchangeId); | |
| if (!exchange) return; | |
| try { | |
| // Simulate WebSocket connection (in real implementation, use CCXT's watchTicker) | |
| this.marketData[exchangeId].connected = true; | |
| this.updateConnectionStatus(); | |
| // Start mock data updates (replace with actual WebSocket) | |
| this.startMockDataUpdates(exchangeId); | |
| } catch (error) { | |
| console.error(`Failed to connect to ${exchange.name}:`, error); | |
| this.marketData[exchangeId].connected = false; | |
| } | |
| }, | |
| // Mock data updates (replace with actual WebSocket) | |
| startMockDataUpdates(exchangeId) { | |
| const updateData = () => { | |
| if (!this.selectedExchanges.includes(exchangeId)) return; | |
| const basePrice = this.getBasePriceForPair(this.selectedPair); | |
| const volatility = this.getVolatilityForExchange(exchangeId); | |
| const bid = basePrice * (1 - Math.random() * 0.001 * volatility); | |
| const ask = basePrice * (1 + Math.random() * 0.001 * volatility); | |
| const volume = Math.random() * 1000000000; | |
| const spread = ((ask - bid) / bid) * 100; | |
| this.marketData[exchangeId] = { | |
| ...this.marketData[exchangeId], | |
| bid: bid, | |
| ask: ask, | |
| volume: volume, | |
| spread: spread, | |
| timestamp: new Date().toLocaleTimeString(), | |
| connected: true | |
| }; | |
| this.updateArbitrageOpportunities(); | |
| this.updateStats(); | |
| }; | |
| // Initial update | |
| updateData(); | |
| // Set up interval for updates | |
| const intervalId = setInterval(updateData, 500); | |
| // Store interval ID for cleanup | |
| if (!this.updateIntervals) this.updateIntervals = {}; | |
| this.updateIntervals[exchangeId] = intervalId; | |
| }, | |
| // Get base price for different pairs | |
| getBasePriceForPair(pair) { | |
| const basePrices = { | |
| 'BTC/USDT': 45000, | |
| 'ETH/USDT': 3000, | |
| 'ADA/USDT': 0.5, | |
| 'DOT/USDT': 7, | |
| 'LINK/USDT': 15 | |
| }; | |
| return basePrices[pair] || 1000; | |
| }, | |
| // Get volatility factor for different exchanges | |
| getVolatilityForExchange(exchangeId) { | |
| const volatilities = { | |
| 'binance': 1.0, | |
| 'okx': 1.1, | |
| 'bybit': 1.2, | |
| 'kraken': 0.9, | |
| 'huobi': 1.3 | |
| }; | |
| return volatilities[exchangeId] || 1.0; | |
| }, | |
| // Update connection status | |
| updateConnectionStatus() { | |
| const connectedCount = this.selectedExchanges.filter(id => | |
| this.marketData[id]?.connected | |
| ).length; | |
| this.activeConnections = connectedCount; | |
| if (connectedCount === 0) { | |
| this.connectionStatus = 'disconnected'; | |
| } else if (connectedCount === this.selectedExchanges.length) { | |
| this.connectionStatus = 'connected'; | |
| } else { | |
| this.connectionStatus = 'connecting'; | |
| } | |
| }, | |
| // Calculate arbitrage opportunities | |
| updateArbitrageOpportunities() { | |
| const opportunities = []; | |
| const connectedExchanges = this.selectedExchanges.filter(id => | |
| this.marketData[id]?.connected && this.marketData[id].bid > 0 | |
| ); | |
| for (let i = 0; i < connectedExchanges.length; i++) { | |
| for (let j = 0; j < connectedExchanges.length; j++) { | |
| if (i === j) continue; | |
| const buyExchange = connectedExchanges[i]; | |
| const sellExchange = connectedExchanges[j]; | |
| const buyData = this.marketData[buyExchange]; | |
| const sellData = this.marketData[sellExchange]; | |
| if (buyData.ask > 0 && sellData.bid > 0) { | |
| const spread = ((sellData.bid - buyData.ask) / buyData.ask) * 100; | |
| if (spread > 0.1) { // Minimum profitable spread | |
| opportunities.push({ | |
| id: `${buyExchange}-${sellExchange}`, | |
| buyExchange: buyData.exchangeName, | |
| sellExchange: sellData.exchangeName, | |
| spread: spread.toFixed(4), | |
| profit: `$${(sellData.bid - buyData.ask).toFixed(2)}` | |
| }); | |
| } | |
| } | |
| } | |
| // Sort by spread descending and take top 5 | |
| this.arbitrageOpportunities = opportunities | |
| .sort((a, b) => b.spread - a.spread) | |
| .slice(0, 5); | |
| this.opportunitiesCount = opportunities.length; | |
| }, | |
| // Update statistics | |
| updateStats() { | |
| const connectedData = Object.values(this.marketData).filter(data => data.connected); | |
| if (connectedData.length > 0) { | |
| this.bestSpread = Math.max(...connectedData.map(data => data.spread)).toFixed(4); | |
| this.lastUpdate = new Date().toLocaleTimeString(); | |
| }, | |
| // Change trading pair | |
| changePair() { | |
| // Clean up existing connections | |
| this.cleanupConnections(); | |
| // Restart monitoring with new pair | |
| this.startMonitoring(); | |
| }, | |
| // Toggle exchange selection | |
| toggleExchange(exchangeId) { | |
| if (this.selectedExchanges.includes(exchangeId)) { | |
| // Disconnect from exchange | |
| this.disconnectFromExchange(exchangeId); | |
| } else { | |
| // Connect to exchange | |
| this.connectToExchange(exchangeId); | |
| } | |
| }, | |
| // Disconnect from exchange | |
| disconnectFromExchange(exchangeId) { | |
| if (this.updateIntervals && this.updateIntervals[exchangeId]) { | |
| clearInterval(this.updateIntervals[exchangeId]); | |
| delete this.updateIntervals[exchangeId]; | |
| } | |
| if (this.marketData[exchangeId]) { | |
| this.marketData[exchangeId].connected = false; | |
| } | |
| this.updateConnectionStatus(); | |
| }, | |
| // Cleanup all connections | |
| cleanupConnections() { | |
| if (this.updateIntervals) { | |
| Object.values(this.updateIntervals).forEach(intervalId => { | |
| clearInterval(intervalId); | |
| }); | |
| this.updateIntervals = {}; | |
| }, | |
| // Get sorted data for table | |
| get sortedData() { | |
| const connectedData = Object.entries(this.marketData) | |
| .filter(([id, data]) => this.selectedExchanges.includes(id) && data.connected); | |
| return connectedData | |
| .map(([id, data]) => data) | |
| .sort((a, b) => { | |
| switch (this.sortBy) { | |
| case 'volume': | |
| return b.volume - a.volume; | |
| case 'spread': | |
| default: | |
| return b.spread - a.spread; | |
| } | |
| }); | |
| }, | |
| // Get color for spread value | |
| getSpreadColor(spread) { | |
| if (spread > 5) return 'bg-red-500 text-white'; | |
| if (spread > 2) return 'bg-yellow-500 text-black'; | |
| if (spread > 1) return 'bg-green-500 text-white'; | |
| return 'bg-gray-500 text-white'; | |
| }, | |
| // Get text color for spread value | |
| getSpreadTextColor(spread) { | |
| if (spread > 5) return 'text-red-400'; | |
| if (spread > 2) return 'text-yellow-400'; | |
| if (spread > 1) return 'text-green-400'; | |
| return 'text-gray-400'; | |
| }, | |
| // Get border color for opportunity cards | |
| getOpportunityBorderColor(spread) { | |
| if (spread > 5) return 'border-red-500'; | |
| if (spread > 2) return 'border-yellow-500'; | |
| if (spread > 1) return 'border-green-500'; | |
| return 'border-gray-500'; | |
| }, | |
| // Get connection status color | |
| getConnectionColor(connected) { | |
| return connected ? 'bg-green-500' : 'bg-red-500'; | |
| }, | |
| // Format numbers with commas | |
| formatNumber(num) { | |
| return num.toLocaleString('en-US', { | |
| minimumFractionDigits: 2, | |
| maximumFractionDigits: 8 | |
| }); | |
| }, | |
| // Format volume | |
| formatVolume(volume) { | |
| if (volume >= 1000000) { | |
| return `$${(volume / 1000000).toFixed(2)}M`; | |
| } | |
| if (volume >= 1000) { | |
| return `$${(volume / 1000).toFixed(2)}K`; | |
| } | |
| return `$${volume.toFixed(2)}`; | |
| }, | |
| // Toggle theme | |
| toggleTheme() { | |
| const html = document.documentElement; | |
| html.classList.toggle('dark'); | |
| }, | |
| // Export data to CSV | |
| exportToCSV() { | |
| const headers = ['Exchange', 'Bid', 'Ask', 'Volume 24h', 'Spread %', 'Updated']; | |
| const csvData = [ | |
| headers.join(','), | |
| ...this.sortedData.map(data => [ | |
| data.exchangeName, | |
| data.bid, | |
| data.ask, | |
| data.volume, | |
| data.spread, | |
| data.timestamp | |
| ].join(',')) | |
| ].join('\n'); | |
| const blob = new Blob([csvData], { type: 'text/csv' }); | |
| const url = window.URL.createObjectURL(blob); | |
| const a = document.createElement('a'); | |
| a.href = url; | |
| a.download = `arbitrage-data-${new Date().toISOString().split('T')[0]}.csv`; | |
| a.click(); | |
| window.URL.revokeObjectURL(url); | |
| }, | |
| // Setup event listeners | |
| setupEventListeners() { | |
| // Handle page visibility changes | |
| document.addEventListener('visibilitychange', () => { | |
| if (document.hidden) { | |
| this.cleanupConnections(); | |
| } else { | |
| this.startMonitoring(); | |
| } | |
| }); | |
| } | |
| }; | |
| } | |
| // Initialize when DOM is loaded | |
| document.addEventListener('DOMContentLoaded', function() { | |
| feather.replace(); | |
| }); |