polymarket-pulse / script.js
D3P0PS's picture
Notification button Nd menu don't do nothing. Categories seems never ending end empty. Whole seems a bit glitchy
4c6591e verified
Raw History Blame Contribute Delete
32 kB
============= Render Functions ====================
const renderMarkets = () => {
const markets = state.filteredMarkets.length > 0 ? state.filteredMarkets : state.markets;
elements.marketsContainer.innerHTML = markets.map(createMarketCard).join('');
feather.replace();
};
==================== Initialization ====================
document.addEventListener('DOMContentLoaded', () => {
// Initialize state
state.markets = generateMockMarkets();
state.filteredMarkets = state.markets;
// Initial renders
renderMarkets();
renderTrendingTags();
renderRecentTrades();
renderAlphaOpportunities();
initVolumeChart();
initEventListeners();
// Set up live updates
startLiveUpdates();
// Periodic trade updates
setInterval(renderRecentTrades, 8000);
// Load saved watchlist
const saved = localStorage.getItem('polymarket-watchlist');
if (saved) {
const ids = JSON.parse(saved);
ids.forEach(id => state.userWatchlist.add(id));
}
// Save watchlist on page leave
window.addEventListener('beforeunload', () => {
localStorage.setItem('polymarket-watchlist', JSON.stringify([...state.userWatchlist]));
});
});
=======
// ==================== Initialization ====================
document.addEventListener('DOMContentLoaded', () => {
// Initialize state with limited markets
state.markets = generateMockMarkets().slice(0, 8);
state.filteredMarkets = [...state.markets];
// Initial renders
renderMarkets();
renderTrendingTags();
renderRecentTrades();
renderAlphaOpportunities();
initVolumeChart();
initEventListeners();
// Set up live updates (less frequent)
startLiveUpdates();
// Periodic trade updates
setInterval(renderRecentTrades, 8000);
// Load saved watchlist
const saved = localStorage.getItem('polymarket-watchlist');
if (saved) {
try {
const ids = JSON.parse(saved);
ids.forEach(id => state.userWatchlist.add(id));
} catch (e) {
console.log('Failed to load watchlist');
}
}
// Save watchlist on page leave
window.addEventListener('beforeunload', () => {
localStorage.setItem('polymarket-watchlist', JSON.stringify([...state.userWatchlist]));
});
// Fix: Ensure categories don't duplicate on rapid clicks
let isFiltering = false;
elements.filterBtns.forEach(btn => {
const originalClick = btn.onclick;
btn.addEventListener('click', (e) => {
if (isFiltering) {
e.preventDefault();
e.stopPropagation();
return;
}
isFiltering = true;
setTimeout(() => isFiltering = false, 300);
});
});
});
==================== Render Functions ====================
const renderMarkets = () => {
const markets = state.filteredMarkets.length > 0 ? state.filteredMarkets : state.markets;
if (markets.length === 0) {
elements.marketsContainer.innerHTML = `
<div class="text-center py-16">
<div class="w-20 h-20 mx-auto mb-6 rounded-full bg-card-bg border border-gray-700 flex items-center justify-center">
<i data-feather="inbox" class="w-10 h-10 text-gray-500"></i>
</div>
<h3 class="text-xl font-semibold text-white mb-2">No markets found</h3>
<p class="text-gray-400">Try selecting a different category or check back later.</p>
</div>
`;
} else {
elements.marketsContainer.innerHTML = markets.map(createMarketCard).join('');
}
feather.replace();
};
Polymarket Pulse - Main JavaScript
// ==================== Configuration ====================
const CONFIG = {
API_BASE: 'https://api.polymarket.com',
POLLING_INTERVAL: 5000, // 5 seconds
MAX_MARKETS: 50,
CATEGORIES: ['politics', 'crypto', 'sports', 'tech', 'entertainment', 'science']
};
// ==================== State Management ====================
const state = {
markets: [],
filteredMarkets: [],
selectedCategory: 'all',
viewMode: 'list', // 'list' or 'grid'
lastUpdate: null,
priceHistory: new Map(),
userWatchlist: new Set(),
liveUpdates: true
};
// ==================== DOM Elements ====================
const elements = {
marketsContainer: document.getElementById('marketsContainer'),
trendingTags: document.getElementById('trendingTags'),
recentTrades: document.getElementById('recentTrades'),
alphaOpportunities: document.getElementById('alphaOpportunities'),
filterBtns: document.querySelectorAll('.filter-btn'),
loadMoreBtn: document.getElementById('loadMoreBtn'),
viewToggle: document.getElementById('viewToggle'),
marketModal: document.getElementById('marketModal'),
modalBackdrop: document.getElementById('modalBackdrop'),
closeModal: document.getElementById('closeModal')
};
// ==================== Mock Data (Simulating API from poly_data1) ====================
const generateMockMarkets = () => [
{
id: 'market-001',
title: 'Will Donald Trump win the 2024 US Presidential Election?',
category: 'politics',
slug: 'trump-2024-election',
yesPrice: 0.52,
noPrice: 0.48,
volume: 24500000,
liquidity: 8900000,
endDate: '2024-11-05T23:59:59Z',
status: 'open',
image: 'http://static.photos/politics/640x360/1',
trending: true,
change24h: +0.08,
trades24h: 15420
},
{
id: 'market-002',
title: 'Will Bitcoin reach $100K before January 1, 2025?',
category: 'crypto',
slug: 'bitcoin-100k-2024',
yesPrice: 0.73,
noPrice: 0.27,
volume: 18900000,
liquidity: 6200000,
endDate: '2024-12-31T23:59:59Z',
status: 'open',
image: 'http://static.photos/technology/640x360/2',
trending: true,
change24h: +0.15,
trades24h: 8930
},
{
id: 'market-003',
title: 'Will Taylor Swift announce a new album in 2024?',
category: 'entertainment',
slug: 'taylor-swift-album-2024',
yesPrice: 0.34,
noPrice: 0.66,
volume: 3200000,
liquidity: 1100000,
endDate: '2024-12-31T23:59:59Z',
status: 'open',
image: 'http://static.photos/entertainment/640x360/3',
trending: false,
change24h: -0.05,
trades24h: 2150
},
{
id: 'market-004',
title: 'Will OpenAI release GPT-5 before Q2 2025?',
category: 'tech',
slug: 'openai-gpt5-q2-2025',
yesPrice: 0.61,
noPrice: 0.39,
volume: 7800000,
liquidity: 2800000,
endDate: '2025-06-30T23:59:59Z',
status: 'open',
image: 'http://static.photos/technology/640x360/4',
trending: true,
change24h: +0.22,
trades24h: 4560
},
{
id: 'market-005',
title: 'Will the Fed cut rates in December 2024?',
category: 'politics',
slug: 'fed-rate-cut-dec-2024',
yesPrice: 0.89,
noPrice: 0.11,
volume: 12400000,
liquidity: 4100000,
endDate: '2024-12-18T18:00:00Z',
status: 'open',
image: 'http://static.photos/finance/640x360/5',
trending: true,
change24h: +0.03,
trades24h: 6780
},
{
id: 'market-006',
title: 'Will Ethereum ETF be approved in 2024?',
category: 'crypto',
slug: 'ethereum-etf-2024',
yesPrice: 0.94,
noPrice: 0.06,
volume: 15600000,
liquidity: 5300000,
endDate: '2024-12-31T23:59:59Z',
status: 'open',
image: 'http://static.photos/technology/640x360/6',
trending: false,
change24h: +0.01,
trades24h: 3240
},
{
id: 'market-007',
title: 'Will the 2024 World Series go to Game 7?',
category: 'sports',
slug: 'world-series-game-7-2024',
yesPrice: 0.28,
noPrice: 0.72,
volume: 2100000,
liquidity: 680000,
endDate: '2024-10-30T23:59:59Z',
status: 'closed',
image: 'http://static.photos/sport/640x360/7',
trending: false,
change24h: -0.12,
trades24h: 1890
},
{
id: 'market-008',
title: 'Will SpaceX Starship reach orbit successfully in 2024?',
category: 'tech',
slug: 'spacex-starship-orbit-2024',
yesPrice: 0.77,
noPrice: 0.23,
volume: 4500000,
liquidity: 1900000,
endDate: '2024-12-31T23:59:59Z',
status: 'open',
image: 'http://static.photos/technology/640x360/8',
trending: true,
change24h: +0.31,
trades24h: 2890
}
];
const trendingTopics = [
{ name: 'US Election', volume: '$45M', growth: '+23%' },
{ name: 'Bitcoin', volume: '$38M', growth: '+15%' },
{ name: 'Fed Rates', volume: '$22M', growth: '+8%' },
{ name: 'AI Models', volume: '$18M', growth: '+42%' },
{ name: 'Taylor Swift', volume: '$12M', growth: '-5%' },
{ name: 'SpaceX', volume: '$9M', growth: '+67%' },
{ name: 'Ethereum', volume: '$28M', growth: '+12%' },
{ name: 'World Cup', volume: '$7M', growth: '+3%' }
];
// ==================== Utility Functions ====================
const formatCurrency = (value) => {
if (value >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
if (value >= 1e6) return `$${(value / 1e6).toFixed(1)}M`;
if (value >= 1e3) return `$${(value / 1e3).toFixed(1)}K`;
return `$${value.toFixed(2)}`;
};
const formatDate = (dateString) => {
const date = new Date(dateString);
const now = new Date();
const diffTime = date - now;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays <= 0) return 'Ended';
if (diffDays <= 1) return '< 1 day';
if (diffDays <= 7) return `${diffDays} days`;
if (diffDays <= 30) return `${Math.floor(diffDays / 7)} weeks`;
return `${Math.floor(diffDays / 30)} months`;
};
const getCategoryEmoji = (category) => {
const emojis = {
politics: '🗳️',
crypto: '₿',
sports: '⚽',
tech: '🚀',
entertainment: '🎭',
science: '🔬'
};
return emojis[category] || '📊';
};
const getCategoryColor = (category) => {
const colors = {
politics: 'from-red-500 to-orange-500',
crypto: 'from-orange-400 to-yellow-400',
sports: 'from-blue-500 to-cyan-500',
tech: 'from-purple-500 to-pink-500',
entertainment: 'from-pink-500 to-rose-500',
science: 'from-green-500 to-emerald-500'
};
return colors[category] || 'from-gray-500 to-gray-600';
};
// ==================== Market Card Component ====================
const createMarketCard = (market) => {
const yesPercent = (market.yesPrice * 100).toFixed(1);
const noPercent = (market.noPrice * 100).toFixed(1);
const isHot = market.trending && market.volume > 10000000;
return `
<div class="market-card relative group p-5 rounded-2xl bg-card-bg border border-gray-800 hover:border-neon-purple/30 transition-all duration-300 cursor-pointer animate-slide-up"
onclick="openMarketDetail('${market.id}')">
<div class="flex gap-4">
<div class="relative shrink-0">
<img src="${market.image}" alt="${market.category}"
class="w-24 h-24 rounded-xl object-cover opacity-80 group-hover:opacity-100 transition-opacity">
${isHot ? `
<div class="absolute -top-2 -right-2 p-1.5 rounded-lg bg-gradient-to-r from-orange-500 to-red-500 animate-pulse-slow">
<i data-feather="flame" class="w-3 h-3 text-white"></i>
</div>
` : ''}
</div>
<div class="flex-1 min-w-0">
<div class="flex items-start justify-between gap-3 mb-2">
<h3 class="font-semibold text-white leading-tight line-clamp-2 group-hover:text-neon-purple transition-colors">
${getCategoryEmoji(market.category)} ${market.title}
</h3>
<button class="shrink-0 p-2 rounded-lg hover:bg-gray-800 transition-all" onclick="event.stopPropagation(); toggleWatchlist('${market.id}')">
<i data-feather="star" class="w-4 h-4 text-gray-400 hover:text-yellow-400 transition-colors" id="star-${market.id}"></i>
</button>
</div>
<div class="flex flex-wrap items-center gap-3 mb-3 text-sm">
<span class="px-2.5 py-1 rounded-lg bg-gradient-to-r ${getCategoryColor(market.category)} text-white text-xs font-medium">
${market.category}
</span>
<span class="text-gray-400 flex items-center gap-1">
<i data-feather="clock" class="w-3 h-3"></i>
${formatDate(market.endDate)}
</span>
<span class="text-gray-400 flex items-center gap-1">
<i data-feather="dollar-sign" class="w-3 h-3"></i>
${formatCurrency(market.volume)}
</span>
</div>
<div class="flex items-center gap-4">
<div class="flex-1">
<div class="flex items-center justify-between text-sm mb-1.5">
<span class="text-green-400 font-medium">Yes ${yesPercent}¢</span>
<span class="text-red-400 font-medium">No ${noPercent}¢</span>
</div>
<div class="h-3 bg-gray-800 rounded-full overflow-hidden">
<div class="h-full bg-gradient-to-r from-green-500 via-green-400 to-red-400 probability-bar"
style="background-size: 100% 100%; background-position: ${yesPercent}% 0; transition: background-position 0.6s ease;">
<div class="h-full w-full bg-dark-bg/30"></div>
</div>
</div>
</div>
<div class="shrink-0 flex flex-col items-end">
<span class="text-xs text-gray-400">24h</span>
<span class="${market.change24h >= 0 ? 'text-green-400' : 'text-red-400'} font-medium flex items-center gap-1">
${market.change24h >= 0 ? '+' : ''}${(market.change24h * 100).toFixed(1)}%
</span>
</div>
</div>
</div>
</div>
</div>
`;
};
// ==================== Render Functions ====================
const renderMarkets = () => {
const markets = state.filteredMarkets.length > 0 ? state.filteredMarkets : state.markets;
elements.marketsContainer.innerHTML = markets.map(createMarketCard).join('');
feather.replace();
};
const renderTrendingTags = () => {
elements.trendingTags.innerHTML = trendingTopics.map(topic => `
<button class="group px-3 py-2 rounded-xl bg-card-bg border border-gray-700 hover:border-neon-purple/50 transition-all duration-300 text-left">
<div class="flex items-center gap-2">
<span class="text-neon-purple font-medium">#${topic.name}</span>
<span class="text-xs text-green-400">${topic.growth}</span>
</div>
<div class="text-xs text-gray-400 mt-0.5">${topic.volume} vol</div>
</button>
`).join('');
};
const generateMockTrades = () => {
const actions = ['bought YES', 'bought NO', 'sold YES', 'sold NO'];
const amounts = [1200, 5000, 890, 3400, 15000, 2300, 6700, 1200];
const names = ['0x7a3f...9e2d', '0x2b8c...4f1a', '0x9d4e...7c3b', '0x1f5a...8d2e', '0x6c9b...3a7f'];
return Array.from({ length: 6 }, (_, i) => ({
name: names[Math.floor(Math.random() * names.length)],
action: actions[Math.floor(Math.random() * actions.length)],
amount: amounts[Math.floor(Math.random() * amounts.length)],
time: Math.floor(Math.random() * 10) + 1
}));
};
const renderRecentTrades = () => {
const trades = generateMockTrades();
elements.recentTrades.innerHTML = trades.map((trade, i) => `
<div class="flex items-center justify-between p-3 rounded-xl bg-dark-bg/50 animate-slide-down" style="animation-delay: ${i * 0.05}s;">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-neon-purple to-neon-blue flex items-center justify-center text-xs font-bold text-white">
${trade.name.slice(2, 4).toUpperCase()}
</div>
<div>
<p class="text-sm text-white">${trade.name}</p>
<p class="text-xs text-gray-400">${trade.action}</p>
</div>
</div>
<div class="text-right">
<p class="text-sm font-mono text-white">$${trade.amount.toLocaleString()}</p>
<p class="text-xs text-gray-500">${trade.time}m ago</p>
</div>
</div>
`).join('');
};
const renderAlphaOpportunities = () => {
const opportunities = [
{ type: 'Arbitrage', description: 'ETH ETF 4% spread detected', profit: '+4.2%', urgency: 'high' },
{ type: 'News Edge', description: 'Fed speech in 2 hours', profit: '+12%', urgency: 'medium' }
];
elements.alphaOpportunities.innerHTML = opportunities.map(opp => `
<div class="p-4 rounded-xl bg-dark-bg/50 border ${opp.urgency === 'high' ? 'border-red-500/30' : 'border-yellow-500/30'} hover:bg-dark-bg transition-all cursor-pointer">
<div class="flex items-start justify-between mb-2">
<span class="px-2 py-0.5 rounded text-xs font-medium ${opp.urgency === 'high' ? 'bg-red-500/20 text-red-400' : 'bg-yellow-500/20 text-yellow-400'}">
${opp.type}
</span>
<span class="text-green-400 font-mono text-sm">${opp.profit}</span>
</div>
<p class="text-sm text-gray-300">${opp.description}</p>
</div>
`).join('');
};
// ==================== Chart Functions ====================
const initVolumeChart = () => {
const ctx = document.getElementById('volumeChart').getContext('2d');
// Gradient fills
const gradientPurple = ctx.createLinearGradient(0, 0, 0, 220);
gradientPurple.addColorStop(0, 'rgba(168, 85, 247, 0.8)');
gradientPurple.addColorStop(1, 'rgba(168, 85, 247, 0.1)');
const gradientBlue = ctx.createLinearGradient(0, 0, 0, 220);
gradientBlue.addColorStop(0, 'rgba(59, 130, 246, 0.8)');
gradientBlue.addColorStop(1, 'rgba(59, 130, 246, 0.1)');
const gradientCyan = ctx.createLinearGradient(0, 0, 0, 220);
gradientCyan.addColorStop(0, 'rgba(6, 182, 212, 0.8)');
gradientCyan.addColorStop(1, 'rgba(6, 182, 212, 0.1)');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Politics', 'Crypto', 'Sports', 'Tech', 'Other'],
datasets: [{
data: [45, 28, 12, 10, 5],
backgroundColor: [
gradientPurple,
gradientBlue,
gradientCyan,
'rgba(251, 191, 36, 0.8)',
'rgba(107, 114, 128, 0.8)'
],
borderWidth: 0,
hoverOffset: 10
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
cutout: '65%',
plugins: {
legend: {
position: 'right',
labels: {
color: '#9ca3af',
font: { size: 11 },
boxWidth: 12,
padding: 15
}
}
}
}
});
};
let priceHistoryChart = null;
const initPriceHistoryChart = () => {
const ctx = document.getElementById('priceHistoryChart');
if (!ctx) return;
const gradientYes = ctx.getContext('2d').createLinearGradient(0, 0, 0, 200);
gradientYes.addColorStop(0, 'rgba(34, 197, 94, 0.3)');
gradientYes.addColorStop(1, 'rgba(34, 197, 94, 0.01)');
const gradientNo = ctx.getContext('2d').createLinearGradient(0, 0, 0, 200);
gradientNo.addColorStop(0, 'rgba(239, 68, 68, 0.3)');
gradientNo.addColorStop(1, 'rgba(239, 68, 68, 0.01)');
// Generate mock price history
const days = 30;
const labels = Array.from({ length: days }, (_, i) => `Day ${i + 1}`);
const yesData = Array.from({ length: days }, () => 0.5 + Math.random() * 0.3);
const noData = yesData.map(y => 1 - y);
priceHistoryChart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [
{
label: 'YES',
data: yesData,
borderColor: '#22c55e',
backgroundColor: gradientYes,
fill: true,
tension: 0.4,
pointRadius: 0
},
{
label: 'NO',
data: noData,
borderColor: '#ef4444',
backgroundColor: gradientNo,
fill: true,
tension: 0.4,
pointRadius: 0
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
interaction: { intersect: false, mode: 'index' },
plugins: {
legend: {
labels: { color: '#9ca3af' }
}
},
scales: {
x: {
grid: { color: '#374151' },
ticks: { color: '#9ca3af', maxTicksLimit: 8 }
},
y: {
grid: { color: '#374151' },
ticks: {
color: '#9ca3af',
callback: v => (v * 100).toFixed(0) + '¢'
},
min: 0,
max: 1
}
}
}
});
};
// ==================== Modal Functions ====================
window.openMarketDetail = (marketId) => {
const market = state.markets.find(m => m.id === marketId);
if (!market) return;
document.getElementById('modalCategory').textContent = market.category;
document.getElementById('modalTitle').textContent = market.title;
document.getElementById('modalYesPrice').textContent = `${(market.yesPrice * 100).toFixed(1)}¢`;
document.getElementById('modalNoPrice').textContent = `${(market.noPrice * 100).toFixed(1)}¢`;
document.getElementById('modalVolume').textContent = formatCurrency(market.volume);
document.getElementById('modalYesBar').style.width = `${market.yesPrice * 100}%`;
document.getElementById('modalNoBar').style.width = `${market.noPrice * 100}%`;
document.getElementById('currentPrice').textContent = `${(market.yesPrice * 100).toFixed(1)}¢`;
// Generate mock order book
const generateOrders = (side, basePrice, count) => {
return Array.from({ length: count }, (_, i) => {
const price = side === 'bid'
? basePrice - (i * 0.01)
: basePrice + (i * 0.01);
const size = Math.floor(Math.random() * 5000) + 500;
return { price: price.toFixed(3), size, total: 0 };
}).map((o, i, arr) => ({
...o,
total: arr.slice(0, i + 1).reduce((s, x) => s + x.size, 0)
})).reverse();
};
const bids = generateOrders('bid', market.yesPrice, 8);
const asks = generateOrders('ask', market.yesPrice, 8);
document.getElementById('orderBookBids').innerHTML = bids.map(b => `
<div class="grid grid-cols-3 text-center text-xs py-1.5 hover:bg-green-500/10 cursor-pointer transition-colors">
<span class="text-green-400 font-mono">${(b.price * 100).toFixed(1)}¢</span>
<span class="text-gray-300 font-mono">${b.size.toLocaleString()}</span>
<span class="text-gray-400 font-mono">${b.total.toLocaleString()}</span>
</div>
`).reverse().join('');
document.getElementById('orderBookAsks').innerHTML = asks.map(a => `
<div class="grid grid-cols-3 text-center text-xs py-1.5 hover:bg-red-500/10 cursor-pointer transition-colors">
<span class="text-red-400 font-mono">${(a.price * 100).toFixed(1)}¢</span>
<span class="text-gray-300 font-mono">${a.size.toLocaleString()}</span>
<span class="text-gray-400 font-mono">${a.total.toLocaleString()}</span>
</div>
`).join('');
// Mock recent trades for modal
document.getElementById('modalRecentTrades').innerHTML = generateMockTrades()
.slice(0, 5).map(t => `
<div class="flex items-center justify-between py-2 border-b border-gray-800 last:border-0">
<span class="text-sm text-gray-400">${t.name}</span>
<span class="text-sm ${t.action.includes('bought YES') || t.action.includes('sold NO') ? 'text-green-400' : 'text-red-400'}">
${t.action}
</span>
<span class="text-sm font-mono text-white">$${t.amount.toLocaleString()}</span>
</div>
`).join('');
elements.marketModal.classList.remove('hidden');
document.body.style.overflow = 'hidden';
// Initialize chart after modal opens
setTimeout(() => {
if (priceHistoryChart) {
priceHistoryChart.destroy();
}
initPriceHistoryChart();
}, 100);
};
const closeModal = () => {
elements.marketModal.classList.add('hidden');
document.body.style.overflow = '';
if (priceHistoryChart) {
priceHistoryChart.destroy();
priceHistoryChart = null;
}
};
// ==================== Watchlist ====================
window.toggleWatchlist = (marketId) => {
const star = document.getElementById(`star-${marketId}`);
if (state.userWatchlist.has(marketId)) {
state.userWatchlist.delete(marketId);
star.classList.remove('text-yellow-400', 'fill-yellow-400');
star.classList.add('text-gray-400');
} else {
state.userWatchlist.add(marketId);
star.classList.remove('text-gray-400');
star.classList.add('text-yellow-400', 'fill-yellow-400');
}
};
// ==================== Event Handlers ====================
const initEventListeners = () => {
// Filter buttons
elements.filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
elements.filterBtns.forEach(b => {
b.classList.remove('active', 'bg-neon-purple/20', 'text-neon-purple', 'border-neon-purple/30');
b.classList.add('text-gray-400', 'border-gray-700');
});
btn.classList.add('active', 'bg-neon-purple/20', 'text-neon-purple', 'border-neon-purple/30');
btn.classList.remove('text-gray-400', 'border-gray-700');
const filter = btn.dataset.filter;
state.selectedCategory = filter;
if (filter === 'all') {
state.filteredMarkets = state.markets;
} else {
state.filteredMarkets = state.markets.filter(m => m.category === filter);
}
renderMarkets();
});
});
// View toggle
elements.viewToggle.addEventListener('click', () => {
state.viewMode = state.viewMode === 'list' ? 'grid' : 'list';
elements.marketsContainer.classList.toggle('grid', state.viewMode === 'grid');
elements.marketsContainer.classList.toggle('grid-cols-1', state.viewMode === 'grid');
elements.marketsContainer.classList.toggle('md:grid-cols-2', state.viewMode === 'grid');
const icon = elements.viewToggle.querySelector('i');
icon.setAttribute('data-feather', state.viewMode === 'list' ? 'grid' : 'list');
feather.replace();
});
// Modal close
elements.closeModal.addEventListener('click', closeModal);
elements.modalBackdrop.addEventListener('click', closeModal);
document.addEventListener('keydown', e => e.key === 'Escape' && closeModal());
// Load more
elements.loadMoreBtn.addEventListener('click', () => {
const moreMarkets = generateMockMarkets().map(m => ({
...m,
id: m.id + '-extra-' + Math.random().toString(36).substr(2, 5),
title: m.title.replace('?', ' (Extended)?')
}));
state.markets.push(...moreMarkets);
if (state.selectedCategory === 'all') {
state.filteredMarkets = state.markets;
} else {
state.filteredMarkets = state.markets.filter(m => m.category === state.selectedCategory);
}
renderMarkets();
});
};
// ==================== Live Updates ====================
const startLiveUpdates = () => {
setInterval(() => {
if (!state.liveUpdates) return;
// Simulate price movements
state.markets.forEach(market => {
const movement = (Math.random() - 0.5) * 0.02;
market.yesPrice = Math.max(0.01, Math.min(0.99, market.yesPrice + movement));
market.noPrice = 1 - market.yesPrice;
});
// Update visible cards
document.querySelectorAll('.market-card').forEach((card, i) => {
const market = state.filteredMarkets[i] || state.markets[i];
if (!market) return;
const yesPercent = (market.yesPrice * 100).toFixed(1);
const bar = card.querySelector('.probability-bar');
if (bar) {
bar.style.backgroundPosition = `${yesPercent}% 0`;
}
});
// Update recent trades
if (Math.random() > 0.7) {
renderRecentTrades();
}
// Update stats animation
document.getElementById('totalVolume').classList.add('animate-pulse');
setTimeout(() => document.getElementById('totalVolume').classList.remove('animate-pulse'), 500);
}, CONFIG.POLLING_INTERVAL);
};
// ==================== Initialization ====================
document.addEventListener('DOMContentLoaded', () => {
// Initialize state
state.markets = generateMockMarkets();
state.filteredMarkets = state.markets;
// Initial renders
renderMarkets();
renderTrendingTags();
renderRecentTrades();
renderAlphaOpportunities();
initVolumeChart();
initEventListeners();
// Set up live updates
startLiveUpdates();
// Periodic trade updates
setInterval(renderRecentTrades, 8000);
// Load saved watchlist
const saved = localStorage.getItem('polymarket-watchlist');
if (saved) {
const ids = JSON.parse(saved);
ids.forEach(id => state.userWatchlist.add(id));
}
// Save watchlist on page leave
window.addEventListener('beforeunload', () => {
localStorage.setItem('polymarket-watchlist', JSON.stringify([...state.userWatchlist]));
});
});