Spaces:
Running

anycoder-2c38454f / index.html
BNQ2k's picture
Upload folder using huggingface_hub
a487578 verified
Raw History Blame Contribute Delete
30.4 kB
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<<MarketContextType>({
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 (
<header className="h-16 border-b border-[#2B2B43] bg-[#0B0E11] flex items-center justify-between px-6 sticky top-0 z-50">
<div className="flex items-center gap-8">
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-indigo-600 rounded-lg flex items-center justify-center">
<Layers className="text-white w-5 h-5" />
</div>
<span className="text-white font-bold text-xl tracking-tight">Crypto<span className="text-indigo-500">Quant</span></span>
</div>
<nav className="hidden md:flex items-center gap-1">
{assets.map((asset) => (
<button
key={asset}
onClick={() => setActiveAsset(asset)}
className={cn(
"px-4 py-2 rounded-md text-sm font-medium transition-all",
activeAsset === asset
? "bg-[#1E2329] text-white shadow-sm ring-1 ring-[#2B2B43]"
: "text-gray-400 hover:text-white hover:bg-[#1E2329]/50"
)}
>
{asset}/USDT
</button>
))}
</nav>
</div>
<div className="flex items-center gap-6">
<div className="hidden lg:block text-right">
<div className="text-xs text-gray-400">Current Price</div>
<div className="flex items-center gap-2">
<span className="text-white font-mono font-bold text-lg">{formatCurrency(livePrice)}</span>
<span className={cn(
"text-xs font-medium px-1.5 py-0.5 rounded",
priceChange >= 0 ? "bg-green-500/10 text-green-500" : "bg-red-500/10 text-red-500"
)}>
{priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)}%
</span>
</div>
</div>
<div className="flex items-center gap-3 border-l border-[#2B2B43] pl-6">
<button className="p-2 text-gray-400 hover:text-white transition-colors">
<Search className="w-5 h-5" />
</button>
<button className="p-2 text-gray-400 hover:text-white transition-colors">
<Bell className="w-5 h-5" />
</button>
<button className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors">
<Wallet className="w-4 h-4" />
<span>Connect</span>
</button>
</div>
</div>
</header>
);
};
const MainChart = () => {
const { activeAsset, setLivePrice, setPriceChange } = useMarket();
const chartContainerRef = useRef<<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
const candlestickSeriesRef = useRef<ISeriesApi<<"Candlestick"> | null>(null);
const volumeSeriesRef = useRef<ISeriesApi<<"Histogram"> | 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 (
<div className="h-[500px] w-full bg-[#0B0E11] rounded-xl border border-[#2B2B43] overflow-hidden relative">
<div ref={chartContainerRef} className="h-full w-full" />
<div className="absolute top-4 left-4 bg-[#0B0E11]/80 backdrop-blur px-3 py-1 rounded border border-[#2B2B43] text-xs text-gray-400">
{activeAsset}/USDT • 1H
</div>
</div>
);
};
const OrderBook = () => {
const { activeAsset } = useMarket();
const [asks, setAsks] = useState<OrderBookEntry[]>([]);
const [bids, setBids] = useState<OrderBookEntry[]>([]);
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] h-[500px] flex flex-col">
<div className="p-4 border-b border-[#2B2B43] flex items-center justify-between">
<h3 className="text-white font-medium flex items-center gap-2">
<BookOpen className="w-4 h-4 text-indigo-500" />
Order Book
</h3>
<span className="text-xs text-gray-500">Real-time Spread</span>
</div>
<div className="flex-1 overflow-hidden flex flex-col text-xs font-mono">
{/* Asks (Sells) - Red */}
<div className="flex-1 overflow-y-auto scrollbar-hide flex flex-col-reverse">
{asks.map((ask, i) => (
<div key={i} className="flex relative py-0.5 px-4 hover:bg-[#1E2329] transition-colors">
<div
className="absolute right-0 top-0 bottom-0 bg-red-500/10"
style={{ width: `${(parseFloat(ask.total) / maxTotal) * 100}%` }}
/>
<span className="w-1/3 text-red-500 relative z-10">{formatNumber(parseFloat(ask.price), 2)}</span>
<span className="w-1/3 text-gray-400 text-right relative z-10">{parseFloat(ask.quantity).toFixed(4)}</span>
<span className="w-1/3 text-gray-500 text-right relative z-10">{parseFloat(ask.total).toFixed(2)}</span>
</div>
))}
</div>
{/* Current Price Divider */}
<div className="py-2 bg-[#1E2329] text-center text-white font-bold border-y border-[#2B2B43]">
{asks.length > 0 && bids.length > 0 && (
<span className="flex items-center justify-center gap-2">
{formatNumber((parseFloat(asks[asks.length-1].price) + parseFloat(bids[0].price)) / 2, 2)}
<ArrowUpRight className="w-3 h-3 text-green-500" />
</span>
)}
</div>
{/* Bids (Buys) - Green */}
<div className="flex-1 overflow-y-auto scrollbar-hide">
{bids.map((bid, i) => (
<div key={i} className="flex relative py-0.5 px-4 hover:bg-[#1E2329] transition-colors">
<div
className="absolute right-0 top-0 bottom-0 bg-green-500/10"
style={{ width: `${(parseFloat(bid.total) / maxTotal) * 100}%` }}
/>
<span className="w-1/3 text-green-500 relative z-10">{formatNumber(parseFloat(bid.price), 2)}</span>
<span className="w-1/3 text-gray-400 text-right relative z-10">{parseFloat(bid.quantity).toFixed(4)}</span>
<span className="w-1/3 text-gray-500 text-right relative z-10">{parseFloat(bid.total).toFixed(2)}</span>
</div>
))}
</div>
</div>
</div>
);
};
const TechnicalsPanel = () => {
const { activeAsset } = useMarket();
const [rsiData, setRsiData] = useState<any[]>([]);
const [macdData, setMacdData] = useState<any[]>([]);
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4">
<div className="flex items-center justify-between mb-4">
<h3 className="text-white font-medium flex items-center gap-2">
<Activity className="w-4 h-4 text-indigo-500" />
Technicals
</h3>
<div className="flex gap-2">
<span className="text-xs px-2 py-1 rounded bg-[#1E2329] text-gray-400">RSI (14)</span>
<span className="text-xs px-2 py-1 rounded bg-[#1E2329] text-gray-400">MACD</span>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{/* RSI Chart */}
<div className="h-[200px]">
<div className="text-xs text-gray-500 mb-1">RSI (14)</div>
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={rsiData}>
<defs>
<linearGradient id="colorRsi" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.3}/>
<stop offset="95%" stopColor="#6366f1" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#1E2329" vertical={false} />
<XAxis dataKey="time" hide />
<YAxis domain={[0, 100]} hide />
<Tooltip
contentStyle={{ backgroundColor: '#1E2329', borderColor: '#2B2B43', color: '#fff' }}
itemStyle={{ color: '#6366f1' }}
/>
<ReferenceLine y={70} stroke="#dc2626" strokeDasharray="3 3" />
<ReferenceLine y={30} stroke="#16a34a" strokeDasharray="3 3" />
<Area type="monotone" dataKey="value" stroke="#6366f1" fillOpacity={1} fill="url(#colorRsi)" />
</AreaChart>
</ResponsiveContainer>
</div>
{/* MACD Chart */}
<div className="h-[200px]">
<div className="text-xs text-gray-500 mb-1">MACD (12, 26, 9)</div>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={macdData}>
<CartesianGrid strokeDasharray="3 3" stroke="#1E2329" vertical={false} />
<XAxis dataKey="time" hide />
<YAxis hide />
<Tooltip
contentStyle={{ backgroundColor: '#1E2329', borderColor: '#2B2B43', color: '#fff' }}
/>
<Bar dataKey="histogram" fill="#6366f1" />
{/* Simplified lines for demo */}
</BarChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
};
const CorrelationMatrix = () => {
const [matrix, setMatrix] = useState<{asset: string, corr: number}[]>([]);
const assets: Asset[] = ['BTC', 'ETH', 'XRP', 'DOGE'];
useEffect(() => {
const fetchData = async () => {
const closes: Record<string, number[]> = {};
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4">
<h3 className="text-white font-medium flex items-center gap-2 mb-4">
<BarChart3 className="w-4 h-4 text-indigo-500" />
30D Correlation vs BTC
</h3>
<div className="space-y-3">
{matrix.map((item) => (
<div key={item.asset} className="flex items-center gap-3">
<span className="text-sm text-gray-400 w-12">{item.asset}</span>
<div className="flex-1 h-2 bg-[#1E2329] rounded-full overflow-hidden">
<div
className={cn(
"h-full rounded-full transition-all duration-1000",
item.corr > 0 ? "bg-green-500" : "bg-red-500"
)}
style={{ width: `${Math.abs(item.corr) * 100}%` }}
/>
</div>
<span className={cn(
"text-sm font-mono w-12 text-right",
item.corr > 0 ? "text-green-500" : "text-red-500"
)}>
{item.corr.toFixed(2)}
</span>
</div>
))}
</div>
</div>
);
};
const WhaleAlertPanel = () => {
const [alerts, setAlerts] = useState<<WhaleAlert[]>([]);
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4 h-[400px] flex flex-col">
<h3 className="text-white font-medium flex items-center gap-2 mb-4">
<Zap className="w-4 h-4 text-yellow-500" />
Whale Alerts
</h3>
<div className="flex-1 overflow-y-auto space-y-3 pr-2">
{alerts.map((alert) => (
<div key={alert.id} className="bg-[#1E2329] p-3 rounded-lg border border-[#2B2B43] text-sm">
<div className="flex justify-between items-start mb-1">
<span className="text-white font-medium">{alert.amount} {alert.asset}</span>
<span className="text-xs text-gray-500">Just now</span>
</div>
<div className="text-gray-400 text-xs">
<span className="text-red-400">{alert.from}</span>
<span className="mx-1">→</span>
<span className="text-green-400">{alert.to}</span>
</div>
<div className="mt-2 text-xs text-gray-500 font-mono">
Value: ${(alert.amount * (alert.asset === 'BTC' ? 65000 : alert.asset === 'ETH' ? 3500 : 0.5)).toFixed(0)}
</div>
</div>
))}
</div>
</div>
);
};
const LiquidityHeatmap = () => {
const { livePrice } = useMarket();
const [buckets, setBuckets] = useState<number[]>([]);
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4 h-[400px] flex flex-col">
<h3 className="text-white font-medium flex items-center gap-2 mb-4">
<Layers className="w-4 h-4 text-blue-500" />
Liquidity Heatmap
</h3>
<div className="flex-1 flex flex-col justify-center gap-1">
{buckets.map((val, i) => (
<div key={i} className="flex items-center gap-2">
<div className="w-12 text-xs text-gray-500 text-right font-mono">
{i === 10 ? 'Price' : ''}
</div>
<div className="flex-1 h-6 bg-[#1E2329] rounded-sm overflow-hidden relative">
<div
className={cn(
"absolute top-0 bottom-0 transition-all duration-1000",
i === 10 ? "bg-indigo-500 left-1/2 right-1/2 w-1" :
i < 10 ? "bg-red-500/40 right-0" : "bg-green-500/40 left-0"
)}
style={{
width: i === 10 ? '2px' : `${val}%`,
opacity: i === 10 ? 1 : 0.3 + (val / 200)
}}
/>
</div>
<div className="w-12 text-xs text-gray-500 font-mono">
{i < 10 ? 'Bid' : i > 10 ? 'Ask' : ''}
</div>
</div>
))}
</div>
</div>
);
};
const FearGreedIndex = () => {
const [index, setIndex] = useState<number | null>(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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4">
<h3 className="text-white font-medium flex items-center gap-2 mb-2">
<AlertTriangle className="w-4 h-4 text-yellow-500" />
Fear & Greed
</h3>
{index !== null ? (
<div className="flex flex-col items-center justify-center py-4">
<div className={cn("text-4xl font-bold font-mono", getColor(index))}>
{index}
</div>
<div className="text-sm text-gray-400 mt-1 capitalize">{classification}</div>
<div className="w-full h-2 bg-[#1E2329] rounded-full mt-4 overflow-hidden">
<div
className={cn("h-full transition-all duration-1000", getColor(index).replace('text-', 'bg-'))}
style={{ width: `${index}%` }}
/>
</div>
</div>
) : (
<div className="h-24 flex items-center justify-center text-gray-500">
<RefreshCw className="w-5 h-5 animate-spin" />
</div>
)}
</div>
);
};
const NewsFeed = () => {
const { activeAsset } = useMarket();
const [news, setNews] = useState<<NewsItem[]>([]);
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 (
<div className="bg-[#0B0E11] rounded-xl border border-[#2B2B43] p-4">
<h3 className="text-white font-medium flex items-center gap-2 mb-4">
<Newspaper className="w-4 h-4 text-indigo-500" />
Market News
</h3>
<div className="space-y-4">
{news.map((item, i) => (
<div key={i} className="group cursor-pointer">
<div className="text-sm text-gray-300 group-hover:text-white transition-colors line-clamp-2">
{item.title}
</div>
<div className="flex items-center gap-2 mt-1">
<span className="text-xs text-indigo-400">{item.source}</span>
<span className="text-xs text-gray-600">•</span>
<span className="text-xs text-gray-600">
{Math.floor((Date.now() - item.publishedOn) / 3600000)}h ago
</span>
</div>
</div>
))}
</div>
</div>
);
};
// --- Main Page ---
export default function CryptoDashboard() {
const [activeAsset, setActiveAsset] = useState<<Asset>('BTC');
const [livePrice, setLivePrice] = useState(0);
const [priceChange, setPriceChange] = useState(0);
return (
<MarketContext.Provider value={{
activeAsset,
setActiveAsset,
livePrice,
setLivePrice,
priceChange,
setPriceChange
}}>
<div className="min-h-screen bg-[#0B0E11] text-gray-300 font-sans selection:bg-indigo-500/30">
<Head>
<title>CryptoQuant | Advanced Market Analyzer</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<Header />
<main className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Top Row: Chart & Order Book */}
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
<div className="xl:col-span-2 space-y-6">
<MainChart />
<TechnicalsPanel />
</div>
<div className="space-y-6">
<OrderBook />
<FearGreedIndex />
</div>
</div>
{/* Middle Row: Stats & Correlation */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div className="lg:col-span-2">
<CorrelationMatrix />
</div>
<div className="lg:col-span-2">
<NewsFeed />
</div>
</div>
{/* Bottom Row: Advanced Mock Components */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<WhaleAlertPanel />
<LiquidityHeatmap />
</div>
</main>
<footer className="mt-12 border-t border-[#2B2B43] py-8 text-center text-sm text-gray-600">
<p>Built with anycoder</p>
<p className="mt-2">Data provided by Binance Public API. For educational purposes only.</p>
</footer>
</div>
</MarketContext.Provider>
);
}