import React, { useState, useEffect, useRef, useMemo, createContext, useContext, useCallback } from 'react'; import Head from 'next/head'; import { createChart, ColorType, IChartApi, ISeriesApi, CandlestickData, HistogramData } from 'lightweight-charts'; import { ArrowUpRight, ArrowDownRight, Activity, BookOpen, BarChart3, Newspaper, Zap, TrendingUp, Search, Menu, Bell, Settings, Wallet, ChevronDown, Layers, AlertTriangle, RefreshCw } from 'lucide-react'; import { clsx, type ClassValue } from 'clsx'; import { twMerge } from 'tailwind-merge'; import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, ReferenceLine } from 'recharts'; // --- Utility --- function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } // --- Types --- type Asset = 'BTC' | 'ETH' | 'XRP' | 'DOGE'; interface KlineData { time: number; open: number; high: number; low: number; close: number; volume: number; } interface TickerData { price: string; change24h: string; change24hPercent: string; } interface OrderBookEntry { price: string; quantity: string; total: string; } interface WhaleAlert { id: number; amount: number; from: string; to: string; asset: string; timestamp: number; } interface NewsItem { title: string; source: string; url: string; publishedOn: number; } // --- Context --- interface MarketContextType { activeAsset: Asset; setActiveAsset: (asset: Asset) => void; livePrice: number; setLivePrice: (price: number) => void; priceChange: number; setPriceChange: (change: number) => void; } const MarketContext = createContext<({ activeAsset: 'BTC', setActiveAsset: () => {}, livePrice: 0, setLivePrice: () => {}, priceChange: 0, setPriceChange: () => {}, }); const useMarket = () => useContext(MarketContext); // --- Helpers --- const formatCurrency = (val: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(val); const formatNumber = (val: number, digits = 2) => new Intl.NumberFormat('en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(val); // --- Math Functions --- const calculateEMA = (data: number[], period: number): number[] => { const k = 2 / (period + 1); const emaArray: number[] = []; let ema = data[0]; emaArray.push(ema); for (let i = 1; i < data.length; i++) { ema = data[i] * k + ema * (1 - k); emaArray.push(ema); } return emaArray; }; const calculateRSI = (closes: number[], period = 14) => { if (closes.length < period + 1) return []; const rsiData: { time: number; value: number }[] = []; let gains = 0; let losses = 0; // Initial averages for (let i = 1; i <= period; i++) { const change = closes[i] - closes[i - 1]; if (change >= 0) gains += change; else losses -= change; } let avgGain = gains / period; let avgLoss = losses / period; for (let i = period + 1; i < closes.length; i++) { const change = closes[i] - closes[i - 1]; if (change >= 0) { avgGain = (avgGain * (period - 1) + change) / period; avgLoss = (avgLoss * (period - 1)) / period; } else { avgGain = (avgGain * (period - 1)) / period; avgLoss = (avgLoss * (period - 1) - change) / period; } const rs = avgGain / avgLoss; const rsi = 100 - (100 / (1 + rs)); rsiData.push({ time: i, value: rsi }); } return rsiData; }; const calculateMACD = (closes: number[]) => { const ema12 = calculateEMA(closes, 12); const ema26 = calculateEMA(closes, 26); const macdLine = ema12.slice(25).map((val, i) => val - ema26[i + 25]); const signalLine = calculateEMA(macdLine, 9); return macdLine.map((val, i) => ({ time: i, macd: val, signal: signalLine[i], histogram: val - signalLine[i] })); }; const calculateCorrelation = (x: number[], y: number[]) => { const n = x.length; const sumX = x.reduce((a, b) => a + b, 0); const sumY = y.reduce((a, b) => a + b, 0); const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0); const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0); const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 0); const numerator = (n * sumXY) - (sumX * sumY); const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY)); if (denominator === 0) return 0; return numerator / denominator; }; // --- Components --- const Header = () => { const { activeAsset, setActiveAsset, livePrice, priceChange } = useMarket(); const assets: Asset[] = ['BTC', 'ETH', 'XRP', 'DOGE']; return (
CryptoQuant
Current Price
{formatCurrency(livePrice)} = 0 ? "bg-green-500/10 text-green-500" : "bg-red-500/10 text-red-500" )}> {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}%
); }; const MainChart = () => { const { activeAsset, setLivePrice, setPriceChange } = useMarket(); const chartContainerRef = useRef<(null); const chartRef = useRef(null); const candlestickSeriesRef = useRef | null>(null); const volumeSeriesRef = useRef | null>(null); // Initialize Chart useEffect(() => { if (!chartContainerRef.current) return; const chart = createChart(chartContainerRef.current, { layout: { background: { type: ColorType.Solid, color: '#0B0E11' }, textColor: '#d1d4dc', }, grid: { vertLines: { color: '#1E2329' }, horzLines: { color: '#1E2329' }, }, crosshair: { mode: 1, }, rightPriceScale: { borderColor: '#2B2B43', }, timeScale: { borderColor: '#2B2B43', timeVisible: true, }, autoSize: true, }); const candlestickSeries = chart.addCandlestickSeries({ upColor: '#16a34a', downColor: '#dc2626', borderVisible: false, wickUpColor: '#16a34a', wickDownColor: '#dc2626', }); const volumeSeries = chart.addHistogramSeries({ color: '#26a69a', priceFormat: { type: 'volume' }, priceScaleId: '', }); volumeSeries.priceScale().applyOptions({ scaleMargins: { top: 0.8, bottom: 0, }, }); chartRef.current = chart; candlestickSeriesRef.current = candlestickSeries; volumeSeriesRef.current = volumeSeries; return () => { chart.remove(); }; }, []); // Fetch Historical Data useEffect(() => { const fetchData = async () => { try { const symbol = `${activeAsset}USDT`; const response = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=1h&limit=200`); const data = await response.json(); const cData: CandlestickData[] = data.map((d: any[]) => ({ time: d[0] / 1000, open: parseFloat(d[1]), high: parseFloat(d[2]), low: parseFloat(d[3]), close: parseFloat(d[4]), })); const vData: HistogramData[] = data.map((d: any[]) => ({ time: d[0] / 1000, value: parseFloat(d[5]), color: parseFloat(d[4]) > parseFloat(d[1]) ? '#16a34a' : '#dc2626' })); candlestickSeriesRef.current?.setData(cData); volumeSeriesRef.current?.setData(vData); // Set initial price const lastClose = cData[cData.length - 1].close; setLivePrice(lastClose); } catch (error) { console.error("Error fetching klines:", error); } }; fetchData(); }, [activeAsset, setLivePrice]); // WebSocket for Live Updates useEffect(() => { const symbol = `${activeAsset.toLowerCase()}usdt`; const ws = new WebSocket(`wss://stream.binance.com:9443/ws/${symbol}@kline_1h`); ws.onmessage = (event) => { const message = JSON.parse(event.data); const k = message.k; const candlestick = { time: k.t / 1000, open: parseFloat(k.o), high: parseFloat(k.h), low: parseFloat(k.l), close: parseFloat(k.c), }; candlestickSeriesRef.current?.update(candlestick); volumeSeriesRef.current?.update({ time: k.t / 1000, value: parseFloat(k.v), color: parseFloat(k.c) > parseFloat(k.o) ? '#16a34a' : '#dc2626' }); setLivePrice(parseFloat(k.c)); }; return () => ws.close(); }, [activeAsset, setLivePrice]); return (
{activeAsset}/USDT • 1H
); }; const OrderBook = () => { const { activeAsset } = useMarket(); const [asks, setAsks] = useState([]); const [bids, setBids] = useState([]); useEffect(() => { const fetchDepth = async () => { try { const symbol = `${activeAsset}USDT`; const res = await fetch(`https://api.binance.com/api/v3/depth?symbol=${symbol}&limit=20`); const data = await res.json(); const process = (orders: [string, string][]) => { let total = 0; return orders.map(([price, qty]) => { total += parseFloat(qty); return { price, quantity: qty, total: total.toFixed(4) }; }); }; setAsks(process(data.asks).reverse()); setBids(process(data.bids)); } catch (e) { console.error(e); } }; fetchDepth(); const interval = setInterval(fetchDepth, 2000); return () => clearInterval(interval); }, [activeAsset]); const maxTotal = Math.max( ...asks.map(a => parseFloat(a.total)), ...bids.map(b => parseFloat(b.total)) ); return (

Order Book

Real-time Spread
{/* Asks (Sells) - Red */}
{asks.map((ask, i) => (
{formatNumber(parseFloat(ask.price), 2)} {parseFloat(ask.quantity).toFixed(4)} {parseFloat(ask.total).toFixed(2)}
))}
{/* Current Price Divider */}
{asks.length > 0 && bids.length > 0 && ( {formatNumber((parseFloat(asks[asks.length-1].price) + parseFloat(bids[0].price)) / 2, 2)} )}
{/* Bids (Buys) - Green */}
{bids.map((bid, i) => (
{formatNumber(parseFloat(bid.price), 2)} {parseFloat(bid.quantity).toFixed(4)} {parseFloat(bid.total).toFixed(2)}
))}
); }; const TechnicalsPanel = () => { const { activeAsset } = useMarket(); const [rsiData, setRsiData] = useState([]); const [macdData, setMacdData] = useState([]); useEffect(() => { const fetchData = async () => { try { const symbol = `${activeAsset}USDT`; const res = await fetch(`https://api.binance.com/api/v3/klines?symbol=${symbol}&interval=1d&limit=100`); const data = await res.json(); const closes = data.map((d: any[]) => parseFloat(d[4])); const rsi = calculateRSI(closes); const macd = calculateMACD(closes); // Format for Recharts setRsiData(rsi.map((d, i) => ({ ...d, time: i }))); setMacdData(macd.map((d, i) => ({ ...d, time: i }))); } catch (e) { console.error(e); } }; fetchData(); }, [activeAsset]); return (

Technicals

RSI (14) MACD
{/* RSI Chart */}
RSI (14)
{/* MACD Chart */}
MACD (12, 26, 9)
{/* Simplified lines for demo */}
); }; const CorrelationMatrix = () => { const [matrix, setMatrix] = useState<{asset: string, corr: number}[]>([]); const assets: Asset[] = ['BTC', 'ETH', 'XRP', 'DOGE']; useEffect(() => { const fetchData = async () => { const closes: Record = {}; await Promise.all(assets.map(async (asset) => { const res = await fetch(`https://api.binance.com/api/v3/klines?symbol=${asset}USDT&interval=1d&limit=30`); const data = await res.json(); closes[asset] = data.map((d: any[]) => parseFloat(d[4])); })); const btcCloses = closes['BTC']; const newMatrix = assets.filter(a => a !== 'BTC').map(asset => ({ asset, corr: calculateCorrelation(btcCloses, closes[asset]) })); setMatrix(newMatrix); }; fetchData(); }, []); return (

30D Correlation vs BTC

{matrix.map((item) => (
{item.asset}
0 ? "bg-green-500" : "bg-red-500" )} style={{ width: `${Math.abs(item.corr) * 100}%` }} />
0 ? "text-green-500" : "text-red-500" )}> {item.corr.toFixed(2)}
))}
); }; const WhaleAlertPanel = () => { const [alerts, setAlerts] = useState<([]); const { activeAsset } = useMarket(); useEffect(() => { const generateAlert = () => { const amount = (Math.random() * 5000 + 1000).toFixed(2); const from = Math.random() > 0.5 ? 'Unknown Wallet' : 'Coinbase'; const to = Math.random() > 0.5 ? 'Binance' : 'OKX'; const newAlert: WhaleAlert = { id: Date.now(), amount: parseFloat(amount), from, to, asset: activeAsset, timestamp: Date.now(), }; setAlerts(prev => [newAlert, ...prev].slice(0, 20)); }; const interval = setInterval(generateAlert, 3500); generateAlert(); // Initial return () => clearInterval(interval); }, [activeAsset]); return (

Whale Alerts

{alerts.map((alert) => (
{alert.amount} {alert.asset} Just now
{alert.from} → {alert.to}
Value: ${(alert.amount * (alert.asset === 'BTC' ? 65000 : alert.asset === 'ETH' ? 3500 : 0.5)).toFixed(0)}
))}
); }; const LiquidityHeatmap = () => { const { livePrice } = useMarket(); const [buckets, setBuckets] = useState([]); useEffect(() => { // Generate mock liquidity clusters around current price const generate = () => { const newBuckets = Array.from({ length: 20 }, (_, i) => { const distance = Math.abs(i - 10); // Higher density closer to price (index 10) const base = Math.max(0, 100 - distance * 8); return base + Math.random() * 50; }); setBuckets(newBuckets); }; generate(); const interval = setInterval(generate, 5000); return () => clearInterval(interval); }, [livePrice]); return (

Liquidity Heatmap

{buckets.map((val, i) => (
{i === 10 ? 'Price' : ''}
{i < 10 ? 'Bid' : i > 10 ? 'Ask' : ''}
))}
); }; const FearGreedIndex = () => { const [index, setIndex] = useState(null); const [classification, setClassification] = useState(''); useEffect(() => { const fetchFearGreed = async () => { try { const res = await fetch('https://api.alternative.me/fng/'); const data = await res.json(); if (data.data && data.data[0]) { setIndex(parseInt(data.data[0].value)); setClassification(data.data[0].value_classification); } } catch (e) { console.error(e); } }; fetchFearGreed(); }, []); const getColor = (val: number) => { if (val <= 20) return 'text-red-500'; if (val <= 40) return 'text-orange-500'; if (val <= 60) return 'text-yellow-500'; if (val <= 80) return 'text-green-400'; return 'text-green-600'; }; return (

Fear & Greed

{index !== null ? (
{index}
{classification}
) : (
)}
); }; const NewsFeed = () => { const { activeAsset } = useMarket(); const [news, setNews] = useState<([]); useEffect(() => { const fetchNews = async () => { // Using a mock approach for CryptoCompare as direct API often requires key or has CORS // In a real app, you'd use a backend proxy. Here we simulate realistic headlines. const mockNews = [ { title: `${activeAsset} Breaks Key Resistance Level`, source: "CoinDesk", publishedOn: Date.now() - 3600000 }, { title: `Institutional Interest in ${activeAsset} Surges`, source: "Bloomberg", publishedOn: Date.now() - 7200000 }, { title: `New Regulatory Framework Proposed for ${activeAsset}`, source: "Reuters", publishedOn: Date.now() - 10800000 }, { title: `Whale Moves $50M in ${activeAsset} to Cold Storage`, source: "CryptoSlate", publishedOn: Date.now() - 14400000 }, ]; setNews(mockNews); }; fetchNews(); }, [activeAsset]); return (

Market News

{news.map((item, i) => (
{item.title}
{item.source} • {Math.floor((Date.now() - item.publishedOn) / 3600000)}h ago
))}
); }; // --- Main Page --- export default function CryptoDashboard() { const [activeAsset, setActiveAsset] = useState<('BTC'); const [livePrice, setLivePrice] = useState(0); const [priceChange, setPriceChange] = useState(0); return (
CryptoQuant | Advanced Market Analyzer
{/* Top Row: Chart & Order Book */}
{/* Middle Row: Stats & Correlation */}
{/* Bottom Row: Advanced Mock Components */}
); }