import { deVigTwoWay, solveImpliedLambda } from './math.js'; /** * Configurable presets matching betting modes. * Default: "sniper" (1.50 - 1.85, 1-2 legs max, strict CLEAN legs only). */ export const PRESETS = { sniper: { id: 'sniper', name: 'Single Best Sniper (1.50–1.85, 1 CLEAN pick)', minOdds: 1.50, maxOdds: 1.85, maxLegs: 1, minFairProb: 0.52, maxVigPct: 7.0, strictMode: true, allowCaution: false, minSlipAdjProb: 0.54, includeAlternative: false, singlePreferenceGap: 0.015, retailHaircut: 0.02, }, balanced: { id: 'balanced', name: 'Balanced Cushion (2.00–2.60)', minOdds: 2.00, maxOdds: 2.60, maxLegs: 3, minFairProb: 0.62, maxVigPct: 7.5, strictMode: false, allowCaution: true, minSlipAdjProb: 0.36, includeAlternative: true, singlePreferenceGap: 0.01, retailHaircut: 0.025, }, classic3x: { id: 'classic3x', name: 'Classic 3x (3.05–3.45)', minOdds: 3.05, maxOdds: 3.45, maxLegs: 3, minFairProb: 0.60, maxVigPct: 7.5, strictMode: false, allowCaution: true, minSlipAdjProb: 0.25, includeAlternative: true, singlePreferenceGap: 0.01, retailHaircut: 0.025, }, }; const MAX_POSITIVE_BONUS = 0.02; // Strictly capped at +2.0 pp to eliminate confirmation bias const SOFT_PENALTY_VETO_THRESHOLD = 0.045; // >= 4.5 pp cumulative penalty triggers VETO function computeTeamDerived(team) { const gp = team.gp || 0; const gfPerGame = gp > 0 && team.gf !== null ? team.gf / gp : team.venueGfPerGame; const gaPerGame = gp > 0 && team.ga !== null ? team.ga / gp : team.venueGaPerGame; const rawHasXg = gp >= 5 && team.gf !== null && team.xg !== null; const rawHasXga = gp >= 5 && team.ga !== null && team.xga !== null; const rawXgPg = rawHasXg ? team.xg / gp : null; const rawXgaPg = rawHasXga ? team.xga / gp : null; // Guard against cross-competition data mixing (e.g. 12-game domestic GF paired with 4-game UCL xG) const xgMismatch = rawHasXg && gp >= 6 && gfPerGame !== null && rawXgPg > 0 && gfPerGame - rawXgPg >= 1.0 && team.gf / team.xg >= 1.8; const xgaMismatch = rawHasXga && gp >= 6 && gaPerGame !== null && rawXgaPg > 0 && gaPerGame - rawXgaPg >= 1.0 && team.ga / team.xga >= 1.8; const hasXg = rawHasXg && !xgMismatch; const hasXga = rawHasXga && !xgaMismatch; const xgPerGame = hasXg ? rawXgPg : null; const xgaPerGame = hasXga ? rawXgaPg : null; const attDiff = hasXg ? team.gf - team.xg : null; const defLuck = hasXga ? team.ga - team.xga : null; const startingDefOut = (team.confirmedOut.startingCB || 0) + (team.confirmedOut.otherDef || 0); return { gp, gfPerGame, gaPerGame, xgPerGame, xgaPerGame, attDiff, defLuck, startingDefOut, xgMismatch, xgaMismatch, }; } function summarizeKeyDriver(match, isOver, line, impliedLambda, combinedXgPg, combinedXgaPg, bonuses) { const parts = [`Implied total ${impliedLambda.toFixed(2)} goals`]; if (combinedXgPg !== null) { parts.push(`combined xG ${combinedXgPg.toFixed(2)}/g`); } if (combinedXgaPg !== null) { parts.push(`xGA ${combinedXgaPg.toFixed(2)}/g`); } if (bonuses.length > 0) { parts.push(bonuses[0].reason); } else if (match.notes) { parts.push(match.notes.slice(0, 110)); } return parts.join(' · '); } function summarizeFailureRisk(hardVetoes, softFlags, isOver, line) { if (hardVetoes.length > 0) return hardVetoes[0].reason; if (softFlags.length > 0) return softFlags[0].reason; return isOver ? `Early red card or low-tempo game stalling under ${line} goals.` : `Early penalty or late transition burst pushing total past ${line} goals.`; } /** * Evaluate a single (match, lineKey, side) candidate deterministically. */ export function evaluateLeg(match, lineKey, side, configInput = {}) { const config = { ...PRESETS.sniper, ...configInput }; const line = Number(lineKey); const lineData = match.totals[lineKey]; if (!lineData) return null; const dv = deVigTwoWay(lineData.over, lineData.under); if (!dv) return null; const isOver = side === 'over'; const odds = isOver ? dv.overOdds : dv.underOdds; if (!odds) return null; const explicitSportyOdds = isOver ? lineData.sportybetOver : lineData.sportybetUnder; const floorOdds = explicitSportyOdds ? explicitSportyOdds : +(Math.max(1.02, 1 + (odds - 1) * (1 - config.retailHaircut))).toFixed(2); const fairProb = isOver ? dv.fairOver : dv.fairUnder; const simProb = isOver ? lineData.simOverProb : lineData.simUnderProb; const impliedLambda = +solveImpliedLambda(line, dv.fairOver).toFixed(2); const openOdds = isOver ? lineData.openOver : lineData.openUnder; const driftAgainst = openOdds ? +(odds - openOdds).toFixed(3) : 0; const driftWith = openOdds ? +(openOdds - odds).toFixed(3) : 0; const h = computeTeamDerived(match.home); const a = computeTeamDerived(match.away); const combinedXgPg = h.xgPerGame !== null && a.xgPerGame !== null ? h.xgPerGame + a.xgPerGame : null; const combinedXgaPg = h.xgaPerGame !== null && a.xgaPerGame !== null ? h.xgaPerGame + a.xgaPerGame : null; const hardVetoes = []; const softFlags = []; const bonuses = []; const addVeto = (code, reason) => hardVetoes.push({ code, reason }); const addSoft = (code, penaltyPp, reason) => softFlags.push({ code, penaltyPp, reason }); const addBonus = (code, bonusPp, reason) => bonuses.push({ code, bonusPp, reason }); // ========================================================================= // 1. UNIVERSAL HARD VETOES // ========================================================================= if (!match.hasVerifiedTeamNews) { addVeto('NO_VERIFIED_TEAM_NEWS', 'No verified pre-match injury or team-news sheet.'); } if (match.isReserveOrYouth) { addVeto('RESERVE_OR_YOUTH', 'Reserve or youth team fixture (high lineup volatility).'); } if (dv.vigPct > config.maxVigPct) { addVeto( 'EXCESSIVE_VIG', `Bookmaker margin is ${dv.vigPct.toFixed(1)}% (exceeds ${config.maxVigPct.toFixed(1)}% cap).` ); } if (fairProb < config.minFairProb) { addVeto( 'BELOW_FAIR_PROB_FLOOR', `De-vigged fair probability is ${(fairProb * 100).toFixed(1)}% (below ${(config.minFairProb * 100).toFixed(0)}% floor).` ); } if (driftAgainst >= 0.08) { addVeto( 'SHARP_DRIFT_AGAINST', `Sharp market drifted +${driftAgainst.toFixed(2)} against this side (${openOdds.toFixed(2)} -> ${odds.toFixed(2)}).` ); } // ========================================================================= // 2. DIRECTION-SPECIFIC SYMMETRIC HARD VETOES & SOFT PENALTIES // ========================================================================= if (isOver) { const maxAttBubble = Math.max( h.attDiff !== null ? h.attDiff : -99, a.attDiff !== null ? a.attDiff : -99 ); const bubbleThreshold = line >= 2.5 ? 5.0 : 6.5; if (maxAttBubble >= bubbleThreshold) { const culprit = (h.attDiff !== null && h.attDiff >= bubbleThreshold ? `${match.home.name} (+${h.attDiff.toFixed(1)})` : '') || `${match.away.name} (+${a.attDiff.toFixed(1)})`; addVeto( 'ATT_XG_BUBBLE', `Attacking finishing bubble >= +${bubbleThreshold.toFixed(1)} goals above xG (${culprit}).` ); } else if (maxAttBubble >= 3.5 && line >= 2.5) { addSoft( 'MILD_ATT_XG_BUBBLE', 2.0, `Elevated finishing overperformance (+${maxAttBubble.toFixed(1)} goals vs xG).` ); } const homeNewTight = match.home.managerGamesInCharge <= 3 && match.home.newManagerTightenedDefense; const awayNewTight = match.away.managerGamesInCharge <= 3 && match.away.newManagerTightenedDefense; if (homeNewTight || awayNewTight) { const teamName = homeNewTight ? match.home.name : match.away.name; addVeto( 'NEW_MGR_TIGHTENED_DEFENSE', `${teamName} hired a new manager within last 3 games who tightened defensive structure.` ); } const topOut = (match.home.confirmedOut.topScorer || 0) + (match.away.confirmedOut.topScorer || 0); const topDoubt = (match.home.doubts5050.topScorer || 0) + (match.away.doubts5050.topScorer || 0); if (line >= 2.5 && topOut >= 1) { addVeto('TOP_SCORER_OUT', 'Confirmed absence of a primary top scorer on an Over 2.5+ line.'); } else if (line >= 2.5 && topDoubt >= 1) { if (config.strictMode) { addVeto('TOP_SCORER_5050_DOUBT', 'Primary striker is a 50/50 fitness doubt on an Over 2.5+ line.'); } else { addSoft('TOP_SCORER_5050_DOUBT', 3.0, 'Primary striker is a 50/50 fitness doubt (verify at T-60).'); } } else if (topOut >= 1 && line <= 1.5) { addSoft('TOP_SCORER_OUT_O15', 2.0, 'Primary top scorer ruled out.'); } const w = match.weather; if (line >= 2.5 && (w.precipType === 'snow' || (w.precipType === 'rain' && w.windKmh >= 25))) { addVeto('SEVERE_WEATHER_OVER', `Adverse pitch weather (${w.precipType}, ${w.tempC}°C, ${w.windKmh} km/h wind).`); } else if (w.tempC <= 2 || w.windKmh >= 22 || w.precipType === 'rain' || w.precipType === 'snow') { addSoft('WEATHER_DRAG_OVER', 1.5, `Scoring drag from weather (${w.tempC}°C, ${w.precipType}, ${w.windKmh} km/h).`); } if (line >= 2.5 && combinedXgPg !== null && combinedXgaPg !== null && combinedXgPg < 2.35 && combinedXgaPg < 2.35) { addVeto( 'LOW_UNDERLYING_XG', `Combined underlying xG (${combinedXgPg.toFixed(2)}/g) and xGA (${combinedXgaPg.toFixed(2)}/g) are too low for Over ${line}.` ); } if (match.isPostIntlBreak) { addSoft('POST_INTL_BREAK_RUST', 2.0, 'First match after international break (elevated attacking rust risk).'); } if (match.home.managerGamesInCharge <= 2 || match.away.managerGamesInCharge <= 2) { if (!homeNewTight && !awayNewTight) { addSoft('NEW_MGR_UNCERTAINTY', 2.0, 'Manager has <= 2 games in charge (tactical unpredictability).'); } } const otherAttOut = (match.home.confirmedOut.otherAtt || 0) + (match.away.confirmedOut.otherAtt || 0); const otherAttDoubt = (match.home.doubts5050.otherAtt || 0) + (match.away.doubts5050.otherAtt || 0); if (line >= 2.5 && (otherAttOut >= 2 || otherAttDoubt >= 2)) { addSoft('ATTACKING_DEPTH_LOSS', 2.0, 'Multiple secondary attackers injured or doubtful.'); } if ( line >= 2.5 && ((h.gfPerGame !== null && h.gfPerGame < 0.85) || (a.gfPerGame !== null && a.gfPerGame < 0.85)) ) { addSoft('ONE_SIDED_ATTACK_O25', 2.0, 'One side averages under 0.85 goals/game (Over 2.5 relies heavily on one team).'); } if (combinedXgaPg !== null && combinedXgaPg >= 3.10 && maxAttBubble < 3.0) { addBonus('LEAKY_UNDERLYING_DEFENSES', 0.5, `High combined xGA (${combinedXgaPg.toFixed(2)}/g) without finishing bubble.`); } if (match.home.confirmedOut.startingCB >= 1 || match.away.confirmedOut.startingCB >= 1) { addBonus('DEFENDER_OUT_FOR_OVER', 0.5, 'Confirmed starting center-back absence supports goal volume.'); } } else { // --- UNDER HARD VETOES --- const minMl = Math.min( match.moneyline.home || 99, match.moneyline.away || 99 ); const o25Odds = match.totals['2.5']?.over || null; if (minMl < 1.45 && o25Odds !== null && o25Odds < 1.50) { addVeto( 'HEAVY_FAVORITE_BLOWOUT', `Heavy favorite (ML ${minMl.toFixed(2)}) with short Over 2.5 (${o25Odds.toFixed(2)}) carries 4-0/4-1 blowout risk.` ); } if (combinedXgaPg !== null && combinedXgaPg >= 3.10) { addVeto( 'HIGH_COMBINED_XGA', `Combined season xGA is ${combinedXgaPg.toFixed(2)}/game (>= 3.10 porous-defense cutoff).` ); } if ( (h.gp >= 6 && h.gaPerGame !== null && h.gaPerGame >= 2.00) || (a.gp >= 6 && a.gaPerGame !== null && a.gaPerGame >= 2.00) ) { const leaky = h.gp >= 6 && h.gaPerGame >= 2.00 ? `${match.home.name} (${h.gaPerGame.toFixed(2)} GA/g)` : `${match.away.name} (${a.gaPerGame.toFixed(2)} GA/g)`; addVeto('POROUS_DEFENSE_GA', `${leaky} concedes >= 2.00 goals per game.`); } const bothMissingCB = match.home.confirmedOut.startingCB >= 1 && match.away.confirmedOut.startingCB >= 1; const eitherMissing2Def = h.startingDefOut >= 2 || a.startingDefOut >= 2; const gkOut = match.home.confirmedOut.gk >= 1 || match.away.confirmedOut.gk >= 1; if (bothMissingCB) { addVeto('BOTH_STARTING_CBS_OUT', 'Both teams are missing a confirmed starting center-back.'); } else if (eitherMissing2Def) { const depleted = h.startingDefOut >= 2 ? match.home.name : match.away.name; addVeto('DEFENSIVE_UNIT_DEPLETED', `${depleted} is missing 2+ starting defenders.`); } else if (gkOut) { addVeto('STARTING_GK_OUT', 'First-choice goalkeeper is ruled out on an Under line.'); } const homeLuckyWithOut = h.defLuck !== null && h.defLuck <= -5.0 && h.startingDefOut >= 1; const awayLuckyWithOut = a.defLuck !== null && a.defLuck <= -5.0 && a.startingDefOut >= 1; const combDefLuck = h.defLuck !== null && a.defLuck !== null ? h.defLuck + a.defLuck : null; if (homeLuckyWithOut || awayLuckyWithOut) { const culprit = homeLuckyWithOut ? `${match.home.name} (${h.defLuck.toFixed(1)} GA vs xGA + defender out)` : `${match.away.name} (${a.defLuck.toFixed(1)} GA vs xGA + defender out)`; addVeto('DEF_XGA_LUCK_PLUS_INJURY', `Defensive luck bubble colliding with defensive absence: ${culprit}.`); } else if (combDefLuck !== null && combDefLuck <= -7.5) { addVeto( 'COMBINED_DEF_XGA_LUCK', `Combined defenses are running ${combDefLuck.toFixed(1)} goals lucky vs xGA (high snap-back risk).` ); } else { const worstDefLuck = Math.min( h.defLuck !== null ? h.defLuck : 0, a.defLuck !== null ? a.defLuck : 0 ); if (worstDefLuck <= -4.5) { addSoft( 'MILD_DEF_XGA_LUCK', 2.5, `One defense is outperforming xGA by ${worstDefLuck.toFixed(1)} goals (regression watch).` ); } } const homeRebound = h.attDiff !== null && (h.attDiff <= -8.0 || (h.attDiff <= -6.0 && (a.xgaPerGame === null || a.xgaPerGame >= 1.15 || match.away.confirmedOut.startingCB >= 1))); const awayRebound = a.attDiff !== null && (a.attDiff <= -8.0 || (a.attDiff <= -6.0 && (h.xgaPerGame === null || h.xgaPerGame >= 1.15 || match.home.confirmedOut.startingCB >= 1))); if (homeRebound || awayRebound) { const culprit = homeRebound ? `${match.home.name} (${h.attDiff.toFixed(1)} GF vs xG)` : `${match.away.name} (${a.attDiff.toFixed(1)} GF vs xG)`; addVeto('ATT_REBOUND_RISK', `${culprit} is heavily under-scoring xG and due for upward finishing regression.`); } const maxXgCap = line <= 2.5 ? 2.75 : 3.25; if (combinedXgPg !== null && combinedXgPg >= maxXgCap) { addVeto( 'HIGH_COMBINED_XG', `Combined attacking creation (${combinedXgPg.toFixed(2)} xG/g) exceeds safe Under ${line} ceiling (${maxXgCap}).` ); } const totalCbOut = match.home.confirmedOut.startingCB + match.away.confirmedOut.startingCB; if (totalCbOut === 1 && !bothMissingCB && !eitherMissing2Def) { addSoft('SINGLE_CB_OUT', 2.0, 'One starting center-back confirmed out.'); } const defDoubts = match.home.doubts5050.startingCB + match.away.doubts5050.startingCB + match.home.doubts5050.gk + match.away.doubts5050.gk; if (defDoubts >= 1) { addSoft('DEFENSIVE_DOUBT', 1.5, 'Starting center-back or goalkeeper listed as 50/50 doubt.'); } if (match.home.managerGamesInCharge <= 2 || match.away.managerGamesInCharge <= 2) { addSoft('NEW_MGR_DEBUT_UNDER', 2.5, 'New manager debut (<= 2 games) adds tactical script volatility.'); } const attOut = match.home.confirmedOut.topScorer + match.away.confirmedOut.topScorer; if (attOut >= 1) { addBonus('TOP_SCORER_OUT_FOR_UNDER', 1.0, 'Confirmed absence of a primary goalscorer suppresses ceiling.'); } const w = match.weather; if ((w.tempC <= 3 || w.precipType !== 'none') && w.windKmh >= 15) { addBonus('ADVERSE_WEATHER_UNDER', 0.5, `Cold/windy conditions (${w.tempC}°C, ${w.windKmh} km/h) suppress tempo.`); } } // Universal soft flags & sharp steam if (driftAgainst >= 0.04 && driftAgainst < 0.08) { addSoft('MODERATE_DRIFT_AGAINST', 2.0, `Odds drifted +${driftAgainst.toFixed(2)} against this pick.`); } if (driftWith >= 0.04) { addBonus('SHARP_STEAM_WITH', 1.0, `Sharp market steamed -${driftWith.toFixed(2)} in favor of this pick.`); } if (simProb !== null && simProb < fairProb - 0.04) { addSoft( 'SIM_DISAGREES_NEGATIVE', 1.5, `Third-party simulation (${(simProb * 100).toFixed(1)}%) sits >4 pp below market fair (${(fairProb * 100).toFixed(1)}%).` ); } // ========================================================================= // 3. ASYMMETRIC FINAL SCORING & STATUS // ========================================================================= const totalPenaltyPp = softFlags.reduce((acc, f) => acc + f.penaltyPp, 0); const rawBonusPp = bonuses.reduce((acc, b) => acc + b.bonusPp, 0); const cappedBonusPp = Math.min(rawBonusPp, MAX_POSITIVE_BONUS * 100); const adjProb = Math.max( 0.05, Math.min(0.95, fairProb - totalPenaltyPp / 100 + cappedBonusPp / 100) ); if (hardVetoes.length === 0) { if (totalPenaltyPp >= SOFT_PENALTY_VETO_THRESHOLD * 100) { addVeto( 'CUMULATIVE_RISK_PENALTY', `Cumulative risk penalties (-${totalPenaltyPp.toFixed(1)} pp) exceed 4.5 pp safety limit.` ); } else if (config.strictMode && softFlags.length >= 2) { addVeto( 'MULTIPLE_RISK_FLAGS', `${softFlags.length} concurrent risk flags disqualify leg in strict mode.` ); } else if (adjProb < config.minFairProb) { addVeto( 'ADJ_PROB_BELOW_FLOOR', `Risk-adjusted probability (${(adjProb * 100).toFixed(1)}%) dropped below ${(config.minFairProb * 100).toFixed(0)}% floor.` ); } } let status = 'CLEAN'; if (hardVetoes.length > 0) { status = 'VETOED'; } else if (softFlags.length > 0) { status = 'CAUTION'; } let actualOutcome = null; if (match.actualScore && typeof match.actualScore.home === 'number' && typeof match.actualScore.away === 'number') { const totalGoals = match.actualScore.home + match.actualScore.away; const won = isOver ? totalGoals > line : totalGoals < line; actualOutcome = { score: `${match.actualScore.home}-${match.actualScore.away}`, totalGoals, won, }; } return { matchId: match.id, espnEventId: match.espnEventId || null, espnLeague: match.espnLeague || null, kickoffIso: match.kickoffIso || null, matchLabel: match.label, kickoffEAT: match.kickoffEAT, league: match.league, tier: match.tier, line, lineKey, side, pickLabel: `${isOver ? 'Over' : 'Under'} ${lineKey}`, odds: +odds.toFixed(2), floorOdds, explicitSportyOdds: Boolean(explicitSportyOdds), vigPct: +dv.vigPct.toFixed(1), estimatedVig: dv.estimatedVig, fairProb: +fairProb.toFixed(4), simProb, impliedLambda, adjProb: +adjProb.toFixed(4), totalPenaltyPp: +totalPenaltyPp.toFixed(1), cappedBonusPp: +cappedBonusPp.toFixed(1), status, hardVetoes, softFlags, bonuses, keyDriver: summarizeKeyDriver(match, isOver, line, impliedLambda, combinedXgPg, combinedXgaPg, bonuses), failureRisk: summarizeFailureRisk(hardVetoes, softFlags, isOver, line), hasVerifiedXg: Boolean(combinedXgPg !== null || combinedXgaPg !== null), xgSampleMismatch: Boolean(h.xgMismatch || a.xgMismatch || h.xgaMismatch || a.xgaMismatch), metrics: { combinedXgPg: combinedXgPg !== null ? +combinedXgPg.toFixed(2) : null, combinedXgaPg: combinedXgaPg !== null ? +combinedXgaPg.toFixed(2) : null, homeAttDiff: h.attDiff !== null ? +h.attDiff.toFixed(1) : null, awayAttDiff: a.attDiff !== null ? +a.attDiff.toFixed(1) : null, homeDefLuck: h.defLuck !== null ? +h.defLuck.toFixed(1) : null, awayDefLuck: a.defLuck !== null ? +a.defLuck.toFixed(1) : null, }, actualOutcome, _matchRef: match, }; } /** * Evaluate every available half-goal Over/Under leg across all matches in a slate. */ export function evaluateSlate(slate, configInput = {}) { const config = { ...PRESETS.sniper, ...configInput }; const allLegs = []; for (const match of slate.matches) { for (const lineKey of Object.keys(match.totals)) { for (const side of ['over', 'under']) { const res = evaluateLeg(match, lineKey, side, config); if (res) allLegs.push(res); } } } const rankOrder = { CLEAN: 0, CAUTION: 1, VETOED: 2 }; allLegs.sort((a, b) => { if (rankOrder[a.status] !== rankOrder[b.status]) { return rankOrder[a.status] - rankOrder[b.status]; } if (b.adjProb !== a.adjProb) return b.adjProb - a.adjProb; return a.vigPct - b.vigPct; }); return { config, allLegs, cleanLegs: allLegs.filter((l) => l.status === 'CLEAN'), cautionLegs: allLegs.filter((l) => l.status === 'CAUTION'), vetoedLegs: allLegs.filter((l) => l.status === 'VETOED'), }; }