-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
664 lines (573 loc) · 21.5 KB
/
Copy pathserver.js
File metadata and controls
664 lines (573 loc) · 21.5 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// server.js
const express = require('express');
const axios = require('axios');
const path = require('path');
require('dotenv').config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
/* Optional hardening; won't crash if packages aren't installed */
let helmet, compression;
try {
helmet = require('helmet');
compression = require('compression');
} catch (e) {
helmet = () => (req, res, next) => next();
compression = () => (req, res, next) => next();
}
app.use(helmet());
app.use(compression());
/* Serve static UI (public/live.html, public/demo.html, etc.) */
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (_req, res) => res.redirect('/live.html'));
app.get('/demo', (_req, res) => res.redirect('/demo.html'));
// ============================================
// DATA STORAGE
// ============================================
let apiMatches = [];
let apiProps = [];
let lastApiUpdate = null;
// ============================================
// PLAYER ACE RATES DATABASE (Updated for 2025)
// ============================================
const ACE_RATES = {
// ATP Top Players - Updated rates
'Novak Djokovic': 0.08,
'Carlos Alcaraz': 0.09,
'Daniil Medvedev': 0.13,
'Jannik Sinner': 0.11,
'Andrey Rublev': 0.10,
'Stefanos Tsitsipas': 0.11,
'Alexander Zverev': 0.14,
'Holger Rune': 0.09,
'Taylor Fritz': 0.13,
'Hubert Hurkacz': 0.18,
'Alex de Minaur': 0.07,
'Tommy Paul': 0.10,
'Ben Shelton': 0.16,
'Grigor Dimitrov': 0.10,
'Karen Khachanov': 0.12,
'Felix Auger-Aliassime': 0.12,
'Lorenzo Musetti': 0.08,
'Sebastian Korda': 0.12,
'Frances Tiafoe': 0.11,
'Casper Ruud': 0.05,
'Sebastian Baez': 0.06,
'Francisco Cerundolo': 0.09,
'Adrian Mannarino': 0.07,
"Christopher O'Connell": 0.12,
'Marton Fucsovics': 0.08,
'Pedro Martinez': 0.06,
// Big Servers
'John Isner': 0.24,
'Reilly Opelka': 0.22,
'Milos Raonic': 0.20,
'Nick Kyrgios': 0.19,
'Matteo Berrettini': 0.16,
'Marin Cilic': 0.15,
'Maxime Cressy': 0.21,
'Sam Querrey': 0.18,
// Clay Court Specialists (Lower rates)
'Rafael Nadal': 0.06,
'Diego Schwartzman': 0.03,
'David Goffin': 0.06,
'Roberto Bautista Agut': 0.05,
'Pablo Carreno Busta': 0.05,
'Albert Ramos-Vinolas': 0.04,
// Default
default: 0.10,
};
// ============================================
// MATHEMATICAL FUNCTIONS
// ============================================
function poissonProbability(lambda, k) {
let probability = Math.exp(-lambda);
for (let i = 1; i <= k; i++) {
probability *= lambda / i;
}
return probability;
}
function calculateOverProbability(line, expectedAces) {
let underProbability = 0;
for (let k = 0; k <= Math.floor(line); k++) {
underProbability += poissonProbability(expectedAces, k);
}
return 1 - underProbability;
}
function getAceRate(playerName) {
const cleanName = (playerName || '').trim();
// exact
if (ACE_RATES[cleanName]) return { rate: ACE_RATES[cleanName], found: true };
// case-insensitive exact
const lower = cleanName.toLowerCase();
for (const [player, rate] of Object.entries(ACE_RATES)) {
if (player.toLowerCase() === lower) return { rate, found: true };
}
// safer last-name exact (not "includes")
const last = lower.split(/\s+/).pop();
for (const [player, rate] of Object.entries(ACE_RATES)) {
const plast = player.toLowerCase().split(/\s+/).pop();
if (plast === last) return { rate, found: true };
}
return { rate: ACE_RATES.default, found: false };
}
// ============================================
// ENHANCED PROP PROCESSING
// ============================================
function processProp(prop) {
// Handle both individual player aces and match total aces
const isMatchTotal = prop.market && prop.market.toLowerCase().includes('total');
let expectedAces, aceRateInfo;
if (isMatchTotal) {
// For match totals, sum both players' expected aces
const player1Rate = getAceRate(prop.player1 || prop.playerName);
const player2Rate = getAceRate(prop.player2 || prop.opponent);
const estimatedSets = prop.bestOf === 5 ? 3.5 : 2.5;
const servicePointsPerPlayer = (estimatedSets * 65) / 2;
const player1Aces = player1Rate.rate * servicePointsPerPlayer;
const player2Aces = player2Rate.rate * servicePointsPerPlayer;
expectedAces = player1Aces + player2Aces;
aceRateInfo = {
rate: (player1Rate.rate + player2Rate.rate) / 2,
found: player1Rate.found && player2Rate.found,
};
} else {
// Individual player aces
aceRateInfo = getAceRate(prop.playerName);
const estimatedSets = prop.bestOf === 5 ? 3.5 : 2.5;
const servicePoints = (estimatedSets * 65) / 2;
expectedAces = aceRateInfo.rate * servicePoints;
}
// Calculate probabilities using Poisson model
const fairOverProb = calculateOverProbability(prop.line, expectedAces);
const fairUnderProb = 1 - fairOverProb;
// Calculate edges if odds are available
let overEdge = 0,
underEdge = 0,
impliedOverProb = 0,
impliedUnderProb = 0;
if (prop.overOdds) {
impliedOverProb = 1 / prop.overOdds;
overEdge = (fairOverProb - impliedOverProb) * 100;
}
if (prop.underOdds) {
impliedUnderProb = 1 / prop.underOdds;
underEdge = (fairUnderProb - impliedUnderProb) * 100;
}
// Determine recommendation
let recommendation = 'NO ODDS';
let bestBet = null;
let confidence = 'Low';
if (prop.overOdds && prop.underOdds) {
if (overEdge >= 8) {
recommendation = 'STRONG BET OVER';
bestBet = 'OVER';
confidence = 'High';
} else if (overEdge >= 5) {
recommendation = 'BET OVER';
bestBet = 'OVER';
confidence = 'Medium';
} else if (underEdge >= 8) {
recommendation = 'STRONG BET UNDER';
bestBet = 'UNDER';
confidence = 'High';
} else if (underEdge >= 5) {
recommendation = 'BET UNDER';
bestBet = 'UNDER';
confidence = 'Medium';
} else {
recommendation = 'PASS';
}
}
return {
...prop,
isMatchTotal,
aceRate: (aceRateInfo.rate * 100).toFixed(1),
hasAceRate: aceRateInfo.found,
expectedAces: expectedAces.toFixed(1),
fairOverProb: (fairOverProb * 100).toFixed(1),
fairUnderProb: (fairUnderProb * 100).toFixed(1),
impliedOverProb: (impliedOverProb * 100).toFixed(1),
impliedUnderProb: (impliedUnderProb * 100).toFixed(1),
overEdge: overEdge.toFixed(1),
underEdge: underEdge.toFixed(1),
recommendation,
bestBet,
confidence,
};
}
// ============================================
// FIXED REAL API INTEGRATION (with ongoing-window guards)
// ============================================
async function fetchRealMatches() {
const API_KEY = process.env.ODDS_API_KEY;
if (!API_KEY || API_KEY === 'demo') {
return { success: false, reason: 'No API key' };
}
try {
console.log('\n🔄 Fetching real tennis matches and props...');
// Step 1: Get available tennis sports
const sportsResponse = await axios.get('https://api.the-odds-api.com/v4/sports', {
params: {
apiKey: API_KEY,
all: false, // Only active sports
},
});
const tennisSports = sportsResponse.data.filter(
(sport) =>
sport.group === 'Tennis' &&
sport.active &&
(sport.key.includes('tennis') || sport.title.toLowerCase().includes('tennis'))
);
console.log(
`Found ${tennisSports.length} active tennis tournaments:`,
tennisSports.map((s) => s.title)
);
if (tennisSports.length === 0) {
return { success: false, reason: 'No active tennis tournaments' };
}
let allMatches = [];
let allProps = [];
// Step 2: For each tennis sport, get events first
for (const sport of tennisSports.slice(0, 3)) {
try {
console.log(`\n📅 Fetching events for ${sport.title}...`);
const eventsResponse = await axios.get(
`https://api.the-odds-api.com/v4/sports/${sport.key}/events`,
{ params: { apiKey: API_KEY } }
);
console.log(`Found ${eventsResponse.data.length} upcoming matches in ${sport.title}`);
// Step 3: For each event, get player props using event-specific endpoint
for (const event of eventsResponse.data.slice(0, 5)) {
try {
const t = Date.parse(event.commence_time);
const now = Date.now();
// Keep a focused window: skip stale (>3 days past) or far-future (>10 days ahead)
if (!Number.isFinite(t)) continue;
if (t < now - 3 * 24 * 60 * 60 * 1000 || t > now + 10 * 24 * 60 * 60 * 1000) {
continue;
}
console.log(`🎾 Fetching props for: ${event.home_team} vs ${event.away_team}`);
// Add match to our list
allMatches.push({
id: event.id,
player1: event.home_team,
player2: event.away_team,
time: new Date(event.commence_time).toISOString(), // ISO for stable sorting
tournament: sport.title || event.sport_title || 'ATP',
sportKey: sport.key,
});
// Get player props for this specific event
const propsResponse = await axios.get(
`https://api.the-odds-api.com/v4/sports/${sport.key}/events/${event.id}/odds`,
{
params: {
apiKey: API_KEY,
regions: 'us', // US bookmakers
markets: 'player_aces', // Request player ace props
oddsFormat: 'decimal',
},
}
);
// Process the props response
if (propsResponse.data && propsResponse.data.bookmakers) {
propsResponse.data.bookmakers.forEach((bookmaker) => {
bookmaker.markets.forEach((market) => {
if (market.key === 'player_aces') {
market.outcomes.forEach((outcome) => {
const isOver = outcome.name && outcome.name.toLowerCase().includes('over');
const isUnder = outcome.name && outcome.name.toLowerCase().includes('under');
// Extract & clean player name
let playerName = outcome.description || outcome.name || 'Unknown Player';
playerName = playerName.replace(/\s*(Over|Under)\s*\d+\.?\d*\s*$/i, '').trim();
// Find existing prop or create new one
let existingProp = allProps.find(
(p) =>
p.matchId === event.id &&
p.playerName === playerName &&
p.line === outcome.point &&
p.bookmaker === bookmaker.title
);
if (!existingProp) {
existingProp = {
matchId: event.id,
player1: event.home_team,
player2: event.away_team,
playerName,
opponent: playerName === event.home_team ? event.away_team : event.home_team,
market: 'player_aces',
line: outcome.point || 0,
overOdds: null,
underOdds: null,
bookmaker: bookmaker.title,
tournament: sport.title || 'ATP',
matchTime: new Date(event.commence_time).toISOString(),
source: 'api',
bestOf: 3, // Most ATP matches are best of 3
};
allProps.push(existingProp);
}
// Set the appropriate odds
if (isOver) {
existingProp.overOdds = outcome.price;
} else if (isUnder) {
existingProp.underOdds = outcome.price;
} else {
existingProp.overOdds = outcome.price; // default to over if unclear
}
});
}
});
});
}
// Small delay to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 100));
} catch (eventError) {
console.log(
`Failed to fetch props for ${event.home_team} vs ${event.away_team}:`,
eventError.response?.status || eventError.message
);
}
}
} catch (sportError) {
console.log(
`Failed to fetch events for ${sport.title}:`,
sportError.response?.status || sportError.message
);
}
// Delay between sports to avoid rate limiting
await new Promise((resolve) => setTimeout(resolve, 200));
}
apiMatches = allMatches;
apiProps = allProps;
lastApiUpdate = new Date();
console.log(`\n✅ Successfully fetched ${allMatches.length} matches and ${allProps.length} props`);
return { success: true, matches: allMatches, props: allProps };
} catch (error) {
console.error('API Error:', error.response?.data || error.message);
return { success: false, reason: error.message };
}
}
// ============================================
// ALTERNATIVE: Try different tennis markets
// ============================================
async function fetchRealMatchesAlternative() {
const API_KEY = process.env.ODDS_API_KEY;
if (!API_KEY || API_KEY === 'demo') {
return { success: false, reason: 'No API key' };
}
try {
console.log('\n🔄 Trying alternative approach with featured markets...');
// Get ATP sports specifically
const sportsResponse = await axios.get('https://api.the-odds-api.com/v4/sports', {
params: { apiKey: API_KEY },
});
const atpSports = sportsResponse.data.filter(
(sport) =>
sport.group === 'Tennis' &&
sport.active &&
(sport.title.toLowerCase().includes('atp') || sport.key.includes('tennis_atp'))
);
console.log('Found ATP tournaments:', atpSports.map((s) => s.title));
if (atpSports.length === 0) {
// Try any tennis sport
const tennisSports = sportsResponse.data.filter((sport) => sport.group === 'Tennis' && sport.active);
console.log('Trying any tennis tournaments:', tennisSports.map((s) => s.title));
if (tennisSports.length === 0) {
return { success: false, reason: 'No active tennis tournaments found' };
}
atpSports.push(...tennisSports.slice(0, 2));
}
let allMatches = [];
// For each sport, get basic odds first (this will work)
for (const sport of atpSports.slice(0, 2)) {
try {
const oddsResponse = await axios.get(`https://api.the-odds-api.com/v4/sports/${sport.key}/odds`, {
params: {
apiKey: API_KEY,
regions: 'us',
markets: 'h2h', // featured market
oddsFormat: 'decimal',
},
});
oddsResponse.data.forEach((match) => {
allMatches.push({
id: match.id,
player1: match.home_team,
player2: match.away_team,
time: new Date(match.commence_time).toISOString(),
tournament: sport.title,
sportKey: sport.key,
});
});
console.log(`✅ Found ${oddsResponse.data.length} matches in ${sport.title}`);
} catch (error) {
console.log(
`❌ Failed to fetch ${sport.title}:`,
error.response?.status,
error.response?.data?.message || error.message
);
}
}
// Generate demo props based on real matches
const demoProps = [];
allMatches.forEach((match) => {
[match.player1, match.player2].forEach((player) => {
const aceRateInfo = getAceRate(player);
const expectedAces = aceRateInfo.rate * 65;
const line = Math.round(expectedAces) + 0.5;
const variance = (Math.random() - 0.5) * 0.1;
const fairProb = calculateOverProbability(line, expectedAces);
const overOdds = Math.round((1 / (fairProb + variance + 0.05)) * 100) / 100;
const underOdds = Math.round((1 / ((1 - fairProb) + variance + 0.05)) * 100) / 100;
demoProps.push({
matchId: match.id,
playerName: player,
opponent: player === match.player1 ? match.player2 : match.player1,
market: 'player_aces',
line,
overOdds,
underOdds,
bookmaker: 'Simulated',
tournament: match.tournament,
source: 'demo_from_real',
bestOf: 3,
});
});
});
apiMatches = allMatches;
apiProps = demoProps;
lastApiUpdate = new Date();
return { success: true, matches: allMatches, props: demoProps };
} catch (error) {
console.error('Alternative API Error:', error.message);
return { success: false, reason: error.message };
}
}
// ============================================
// DEMO DATA GENERATOR
// ============================================
function generateDemoData() {
const demoMatches = [
{ id: 'demo1', player1: 'Carlos Alcaraz', player2: 'Jannik Sinner', tournament: 'ATP MIAMI OPEN' },
{ id: 'demo2', player1: 'John Isner', player2: 'Rafael Nadal', tournament: 'ATP INDIAN WELLS' },
{ id: 'demo3', player1: 'Daniil Medvedev', player2: 'Stefanos Tsitsipas', tournament: 'ATP MONTE CARLO' },
{ id: 'demo4', player1: 'Alexander Zverev', player2: 'Hubert Hurkacz', tournament: 'ATP MADRID' },
];
const bookmakers = ['DraftKings', 'FanDuel', 'BetMGM', 'Caesars', 'PointsBet'];
const demoProps = [];
demoMatches.forEach((match) => {
// Individual player ace props
[match.player1, match.player2].forEach((player) => {
const aceRateInfo = getAceRate(player);
const expectedAces = aceRateInfo.rate * 65;
const line = Math.round(expectedAces) + 0.5;
// Create props for 2-3 bookmakers per player
const numBooks = 2 + Math.floor(Math.random() * 2);
for (let i = 0; i < numBooks; i++) {
const bookmaker = bookmakers[i];
const variance = (Math.random() - 0.5) * 0.1;
const fairProb = calculateOverProbability(line, expectedAces);
const overOdds = Math.round((1 / (fairProb + variance + 0.05)) * 100) / 100;
const underOdds = Math.round((1 / ((1 - fairProb) + variance + 0.05)) * 100) / 100;
demoProps.push({
matchId: match.id,
playerName: player,
opponent: player === match.player1 ? match.player2 : match.player1,
market: 'player_aces',
line,
overOdds,
underOdds,
bookmaker,
tournament: match.tournament,
source: 'demo',
bestOf: 3,
});
}
});
// Match total ace props
const player1Rate = getAceRate(match.player1);
const player2Rate = getAceRate(match.player2);
const totalExpected = (player1Rate.rate + player2Rate.rate) * 65;
const totalLine = Math.round(totalExpected) + 0.5;
// Add match total props
for (let i = 0; i < 2; i++) {
const bookmaker = bookmakers[i];
const variance = (Math.random() - 0.5) * 0.1;
const fairProb = calculateOverProbability(totalLine, totalExpected);
const overOdds = Math.round((1 / (fairProb + variance + 0.05)) * 100) / 100;
const underOdds = Math.round((1 / ((1 - fairProb) + variance + 0.05)) * 100) / 100;
demoProps.push({
matchId: match.id,
player1: match.player1,
player2: match.player2,
playerName: `${match.player1} vs ${match.player2}`,
market: 'total_aces',
line: totalLine,
overOdds,
underOdds,
bookmaker,
tournament: match.tournament,
source: 'demo',
bestOf: 3,
});
}
});
return demoProps.map((prop) => processProp(prop));
}
// ============================================
// API ENDPOINTS
// ============================================
// Get demo props
app.get('/api/demo-props', (_req, res) => {
const demoProps = generateDemoData();
res.json(demoProps);
});
// Get live props from API
app.get('/api/live-props', async (_req, res) => {
const result = await fetchRealMatches();
if (result.success && result.props.length > 0) {
const processedProps = result.props.map((prop) => processProp(prop));
res.json(processedProps);
} else {
// Fallback to demo if no real props available
const demoProps = generateDemoData();
res.json(demoProps);
}
});
// Enhanced status endpoint
app.get('/api/status', async (_req, res) => {
const hasApiKey = process.env.ODDS_API_KEY && process.env.ODDS_API_KEY !== 'demo';
let liveProps = 0;
let tournaments = 0;
if (hasApiKey && apiProps.length === 0) {
// Try to fetch if we haven't yet
const result = await fetchRealMatches();
if (result.success) {
liveProps = result.props.length;
tournaments = new Set(result.props.map((p) => p.tournament)).size;
}
} else {
liveProps = apiProps.length;
tournaments = new Set(apiProps.map((p) => p.tournament)).size;
}
res.json({
hasApiKey,
liveProps,
tournaments,
lastUpdate: lastApiUpdate,
});
});
// ============================================
// START SERVER
// ============================================
app.listen(PORT, () => {
console.log(`\n🎾 AceEdge Pro`);
console.log(`🌐 Running on http://localhost:${PORT}`);
console.log(`📄 UI: /live.html (Live) • /demo.html (Demo)\n`);
if (process.env.ODDS_API_KEY && process.env.ODDS_API_KEY !== 'demo') {
console.log('✅ Live ATP tournament data integration');
} else {
console.log('❌ Live data (Add ODDS_API_KEY to .env for real ATP props)');
}
});