-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
339 lines (288 loc) · 10.9 KB
/
script.js
File metadata and controls
339 lines (288 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Configuration
const CONFIG = {
POLYMARKET_API: 'https://gamma-api.polymarket.com',
GOOGLE_SHEETS_SCRIPT_URL: 'https://script.google.com/macros/s/AKfycbyqISjEK6GCLjyZEH1i4__lI0JbJSl7BWHWdekfP1Xk0666rkx7cHE2NhfyO_LBLLPCPg/exec',
CACHE_DURATION: 5 * 60 * 1000, // 5 minutes
};
// State management
let accountsData = {
winrate: [],
roi: []
};
let currentPage = 'winrate';
let currentSort = 'winrate';
// Initialize
document.addEventListener('DOMContentLoaded', () => {
initializeEventListeners();
loadCachedData();
updateLastSync();
});
function initializeEventListeners() {
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const page = e.currentTarget.dataset.page;
switchPage(page);
});
});
// Buttons
document.getElementById('fetchBtn').addEventListener('click', fetchAndDisplayAccounts);
document.getElementById('exportBtn').addEventListener('click', exportToGoogleSheets);
// Sort selector
document.getElementById('sortBy').addEventListener('change', (e) => {
currentSort = e.target.value;
renderAccounts();
});
}
function switchPage(page) {
currentPage = page;
// Update tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.page === page);
});
// Update page content
document.querySelectorAll('.page-content').forEach(content => {
content.classList.toggle('active', content.id === `${page}-page`);
});
}
async function fetchAndDisplayAccounts() {
showLoading(true);
try {
// Fetch top accounts by win rate
const winrateAccounts = await fetchTopAccountsByWinRate();
accountsData.winrate = winrateAccounts;
// Fetch top accounts by ROI
const roiAccounts = await fetchTopAccountsByROI();
accountsData.roi = roiAccounts;
// Cache the data
cacheData();
// Render accounts
renderAccounts();
// Update stats
updateHeaderStats();
updateLastSync();
} catch (error) {
console.error('Error fetching accounts:', error);
alert('Error fetching account data. Please check console for details.');
} finally {
showLoading(false);
}
}
async function fetchTopAccountsByWinRate() {
// Note: This is a mock implementation since the actual Polymarket API endpoint
// may require authentication or have different structure
// Replace with actual API calls based on Polymarket's documentation
try {
// Example: Fetch leaderboard data
// const response = await fetch(`${CONFIG.POLYMARKET_API}/leaderboard?sortBy=winrate&limit=50`);
// const data = await response.json();
// For demonstration, generating mock data
return generateMockAccounts('winrate');
} catch (error) {
console.error('Error fetching win rate accounts:', error);
return generateMockAccounts('winrate');
}
}
async function fetchTopAccountsByROI() {
try {
// Example: Fetch leaderboard data
// const response = await fetch(`${CONFIG.POLYMARKET_API}/leaderboard?sortBy=roi&limit=50`);
// const data = await response.json();
// For demonstration, generating mock data
return generateMockAccounts('roi');
} catch (error) {
console.error('Error fetching ROI accounts:', error);
return generateMockAccounts('roi');
}
}
function generateMockAccounts(type) {
// Mock data generator - replace with actual API calls
const accounts = [];
const count = 20;
for (let i = 0; i < count; i++) {
const username = `trader_${Math.random().toString(36).substring(2, 10)}`;
const winRate = type === 'winrate'
? 95 - (i * 2) - Math.random() * 3
: 60 + Math.random() * 30;
const initialDeposit = 1000 + Math.random() * 9000;
const currentBalance = initialDeposit * (type === 'roi'
? (5 + i * 0.5 + Math.random() * 2)
: (1.5 + Math.random() * 2));
const roi = ((currentBalance - initialDeposit) / initialDeposit) * 100;
const weeklyPnL = (Math.random() - 0.3) * 5000;
accounts.push({
username,
rank: i + 1,
winRate: parseFloat(winRate.toFixed(2)),
roi: parseFloat(roi.toFixed(2)),
initialDeposit: parseFloat(initialDeposit.toFixed(2)),
currentBalance: parseFloat(currentBalance.toFixed(2)),
totalVolume: parseFloat((currentBalance * (2 + Math.random() * 8)).toFixed(2)),
totalTrades: Math.floor(50 + Math.random() * 450),
weeklyPnL: parseFloat(weeklyPnL.toFixed(2)),
profileUrl: `https://polymarket.com/profile/${username}`
});
}
return accounts;
}
function renderAccounts() {
const winrateGrid = document.getElementById('winrateGrid');
const roiGrid = document.getElementById('roiGrid');
// Sort accounts based on current sort option
const sortedWinrate = sortAccounts([...accountsData.winrate], currentSort);
const sortedROI = sortAccounts([...accountsData.roi], currentSort);
winrateGrid.innerHTML = sortedWinrate.map(account => createAccountCard(account)).join('');
roiGrid.innerHTML = sortedROI.map(account => createAccountCard(account)).join('');
// Add click listeners
document.querySelectorAll('.account-card').forEach(card => {
card.addEventListener('click', (e) => {
const url = e.currentTarget.dataset.url;
window.open(url, '_blank');
});
});
}
function sortAccounts(accounts, sortBy) {
return accounts.sort((a, b) => {
switch(sortBy) {
case 'winrate':
return b.winRate - a.winRate;
case 'roi':
return b.roi - a.roi;
case 'pnl':
return b.weeklyPnL - a.weeklyPnL;
case 'volume':
return b.totalVolume - a.totalVolume;
default:
return 0;
}
});
}
function createAccountCard(account) {
const isProfitable = account.weeklyPnL >= 0;
const pnlClass = isProfitable ? 'profit' : 'loss';
const pnlColor = isProfitable ? 'positive' : 'negative';
const arrow = isProfitable ? '↑' : '↓';
return `
<div class="account-card" data-url="${account.profileUrl}">
<div class="account-header">
<div>
<div class="account-name">${account.username}</div>
<div class="account-rank">#${account.rank}</div>
</div>
</div>
<div class="account-stats">
<div class="stat">
<div class="stat-name">Win Rate</div>
<div class="stat-value-large positive">${account.winRate}%</div>
</div>
<div class="stat">
<div class="stat-name">ROI</div>
<div class="stat-value-large ${account.roi >= 0 ? 'positive' : 'negative'}">
${account.roi >= 0 ? '+' : ''}${account.roi.toFixed(1)}%
</div>
</div>
<div class="stat">
<div class="stat-name">Volume</div>
<div class="stat-value neutral">$${formatNumber(account.totalVolume)}</div>
</div>
<div class="stat">
<div class="stat-name">Trades</div>
<div class="stat-value neutral">${account.totalTrades}</div>
</div>
</div>
<div class="pnl-indicator ${pnlClass}">
<div class="pnl-arrow">${arrow}</div>
<div>
<div class="pnl-label">WEEKLY P&L</div>
</div>
<div class="pnl-value ${pnlColor}">
${account.weeklyPnL >= 0 ? '+' : ''}$${formatNumber(Math.abs(account.weeklyPnL))}
</div>
</div>
</div>
`;
}
function formatNumber(num) {
if (num >= 1000000) {
return (num / 1000000).toFixed(2) + 'M';
} else if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K';
}
return num.toFixed(2);
}
function updateHeaderStats() {
const totalAccounts = accountsData.winrate.length + accountsData.roi.length;
document.getElementById('accountCount').textContent = totalAccounts;
}
function updateLastSync() {
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: false
});
document.getElementById('lastSync').textContent = timeString;
}
function showLoading(show) {
document.getElementById('loadingOverlay').classList.toggle('active', show);
}
// Google Sheets Integration
async function exportToGoogleSheets() {
if (!CONFIG.GOOGLE_SHEETS_SCRIPT_URL) {
alert('Please configure your Google Apps Script URL in the CONFIG object');
return;
}
showLoading(true);
try {
const allAccounts = [
...accountsData.winrate.map(acc => ({ ...acc, category: 'High Win Rate' })),
...accountsData.roi.map(acc => ({ ...acc, category: 'High ROI' }))
];
const response = await fetch(CONFIG.GOOGLE_SHEETS_SCRIPT_URL, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'writeAccounts',
data: allAccounts
})
});
alert('Data exported to Google Sheets successfully!');
} catch (error) {
console.error('Error exporting to Google Sheets:', error);
alert('Error exporting to Google Sheets. Check console for details.');
} finally {
showLoading(false);
}
}
// Cache Management
function cacheData() {
const cacheObj = {
timestamp: Date.now(),
data: accountsData
};
localStorage.setItem('polymarket_accounts_cache', JSON.stringify(cacheObj));
}
function loadCachedData() {
const cached = localStorage.getItem('polymarket_accounts_cache');
if (!cached) return;
try {
const cacheObj = JSON.parse(cached);
const age = Date.now() - cacheObj.timestamp;
if (age < CONFIG.CACHE_DURATION) {
accountsData = cacheObj.data;
renderAccounts();
updateHeaderStats();
}
} catch (error) {
console.error('Error loading cached data:', error);
}
}
// Auto-refresh every 5 minutes
setInterval(() => {
if (document.visibilityState === 'visible') {
fetchAndDisplayAccounts();
}
}, CONFIG.CACHE_DURATION);