Skip to content

Instantly share code, notes, and snippets.

@jseverson
Created December 7, 2025 19:06
Show Gist options
  • Select an option

  • Save jseverson/bb92671f7a041281bab1a164e820dc74 to your computer and use it in GitHub Desktop.

Select an option

Save jseverson/bb92671f7a041281bab1a164e820dc74 to your computer and use it in GitHub Desktop.
RLX Jane - Automated Sports Betting Strategies Documentation

Strategy Guides

This directory contains comprehensive documentation for all RLX Jane betting strategies.

Available Strategies

Football

  • Undervalued Yard Leaders - Identifies underdogs with significant yards advantage that are underpriced on Kalshi. Analyzes live games in Q2-Q3, requires β‰₯20% yards advantage.

Hockey

  • Underdogs - Targets extreme underdogs in NHL pre-game markets. Identifies teams priced at ≀$0.39 with potential value from market overreaction.

Soccer

  • Leading Undervalued - Identifies winning soccer teams that are underpriced on prediction markets. Finds teams that are leading but priced <$0.70.

Strategy Structure

Each strategy guide includes:

  • Overview - Core concept and approach
  • Key Criteria - Entry conditions and filters
  • Value Scoring Algorithm - How opportunities are scored
  • Value Tiers - Classification system (GOOD, STRONG, ELITE)
  • Automatic Buy Logic - When and how buys are triggered
  • Discord Notifications - Real-time alerting format
  • Configuration - Environment and Firestore settings
  • Data Flow - End-to-end process
  • Firestore Schema - Data structures used
  • Example Scenarios - Real-world cases
  • Performance Tracking - Metrics and monitoring
  • Best Practices - Usage recommendations
  • Troubleshooting - Common issues and solutions

Common Features

All strategies share the following:

Value Tiers

  • ELITE (πŸ”₯): 90+ value score β†’ 200 shares
  • STRONG (πŸ’Ž): 60-89 value score β†’ 200 shares
  • GOOD (βœ…): 50-59 value score β†’ 100 shares
  • POOR (❌): <50 value score β†’ No buy

Buy Types

  • Simulated (default): Tracked buys with no real money
  • Live: Real purchases on Kalshi (must be explicitly enabled)

Discord Integration

  • Clickable Kalshi market URLs
  • Combined buy + signal notifications
  • Color-coded by tier/status
  • Real-time updates

Firestore Tracking

  • ValueSignal documents with instances array
  • Buy documents with profit tracking
  • Daily performance summaries
  • Strategy-specific metadata

Adding New Strategies

When creating a new strategy:

  1. Name format: {sport}-{strategy-name}.md
  2. Follow the structure template from existing guides
  3. Update this README with a brief description
  4. Ensure consistency with shared buy/notification logic in BaseStrategy

Related Documentation

Football Undervalued Yard Leaders Strategy - Complete Guide

Overview

The "Undervalued Yard Leaders" strategy identifies underdogs with significant yards advantage that are underpriced on Kalshi. The core concept: when an underdog is dominating on yards but the market hasn't adjusted the price accordingly, there's value to capture.

This strategy applies to both NFL and NCAAF (college football).

Key Criteria

Game Phase

  • Q2 and Q3 only - Skips Q1 (too early to judge) and Q4 (too late, variance too high)
  • Live games only - Not pre-game betting

Team Selection

  • Underdog - Team priced < $0.50 on Kalshi
  • Must have clear favorite opponent (β‰₯ $0.50)

Performance Metrics

  • Yards Advantage β‰₯ 20% - (underdog_yards - favorite_yards) / favorite_yards
  • Yards = Rushing yards + Passing yards (total offensive yards)
  • Winnability - Game must still be winnable based on score and time

Value Scoring Algorithm

Formula Components

  1. Yards Advantage (0-100 scale)

    • Base score from yards ratio
    • 20% advantage = 20 points
    • 50% advantage = 50 points
  2. Score Difference Impact

    • Winning/Tied: Bonus points
      • +7 points = +7 score
      • +14 points = +10 score (diminishing returns)
    • Losing: Penalty
      • -7 points = -10 score
      • -14 points = -15 score
  3. Price Impact (inverse relationship)

    • Lower price = higher value
    • $0.10 = +30 points
    • $0.25 = +15 points
    • $0.40 = +5 points
    • $0.50 = 0 points
  4. Winnability Gate

    • If not winnable, score = 0 (hard stop)

Combined Score

total_score = yards_score + score_impact + price_impact
final_score = max(0, min(100, total_score))

Value Tiers

The strategy uses a simplified 3-tier system:

Tier Range Emoji Shares
ELITE 90+ πŸ”₯ 200
STRONG 60-89 πŸ’Ž 200
GOOD 50-59 βœ… 100
POOR <50 ❌ N/A

Note: Only signals with value score β‰₯ 50 trigger buys (configurable via MIN_VALUE_SCORE).

Winnability Logic

The strategy uses sophisticated winnability detection to avoid impossible comebacks:

Q2 (Early)

  • Down by ≀28 points = Still winnable

Q3 (Mid-game)

  • More than 7 minutes left: Down by ≀21 points
  • Less than 7 minutes left: Down by ≀17 points

Q4 (Critical)

  • 10+ minutes: Down by ≀17 points
  • 5-10 minutes: Down by ≀14 points
  • 3-5 minutes: Down by ≀10 points
  • 1-3 minutes: Down by ≀7 points
  • <1 minute: Down by ≀3 points

Automatic Buy Logic

Buy Triggers

  • Every value signal β‰₯ minimum threshold triggers a buy
  • No separate "min_buy_value" - all qualifying signals are bought
  • Share quantity determined by value tier (GOOD=100, STRONG/ELITE=200)

Buy Types

  • Simulated (default): is_live_buy = false

    • Tracked in Firestore
    • Used for backtesting and strategy validation
    • No real money spent
  • Live: is_live_buy = true

    • Real purchases on Kalshi
    • Must be explicitly enabled per strategy
    • Tracked with market_id for result verification

Discord Notifications

Notification Format

  • Title: Clickable Kalshi market URL
  • Buy Information: Shows shares, price, total, and type (Live/Simulated)
  • Game Status: Quarter and time remaining
  • Yards Advantage: Percentage and absolute numbers
  • Score: Current game score
  • Value Score: Numerical score and tier

Color Coding

  • Green: Buy triggered
  • Magenta: ELITE tier
  • Purple: STRONG tier
  • Green: GOOD tier
  • Red: POOR tier (no buy)

Configuration

Environment Variables

MIN_VALUE_SCORE=35.0          # Minimum score to create signal

Strategy Config (Firestore)

{
  "id": "football-undervalued-yard-leaders",
  "name": "Undervalued Yard Leaders",
  "sport": "football",
  "enabled": true,
  "is_live_buy": false,
  "min_confidence": 0.6,
  "min_expected_value": 0.02
}

Data Flow

  1. Game Analysis

    • Fetch live games from ESPN (NFL/NCAAF)
    • Check game phase (Q2 or Q3)
    • Extract yards data (rushing + passing)
  2. Market Data

    • Fetch team prices from Kalshi
    • Identify underdog (< $0.50)
    • Verify favorite exists (β‰₯ $0.50)
  3. Yards Calculation

    • Calculate yards advantage ratio
    • Verify β‰₯ 20% threshold
    • Check winnability based on score/time
  4. Value Scoring

    • Calculate composite value score
    • Determine value tier
    • Check against minimum threshold
  5. Signal Creation

    • Create ValueSignal with current state
    • Save to Firestore
    • Track instances over time
  6. Auto-Buy Execution

    • Determine share quantity from tier
    • Create Buy record (simulated or live)
    • Mark signal as having triggered buy
  7. Discord Notification

    • Send single combined notification
    • Include buy details inline
    • Provide clickable Kalshi link

Firestore Schema

ValueSignal Document

{
  id: "uuid",
  game_id: "espn-event-id",
  sport: "nfl" | "ncaaf",
  team: "Team Name",
  opponent: "Opponent Name",
  market: "kalshi",
  ticker: "KXNFLGAME-...",
  strategy_id: "football-undervalued-yard-leaders",
  strategy_name: "Undervalued Yard Leaders",
  current_value_score: 75.5,
  current_price: 0.35,
  current_yards_advantage: 0.25,
  current_score_difference: -3,
  is_winnable: true,
  quarter: 2,
  time_remaining: "8:45",
  team_score: 14,
  opponent_score: 17,
  team_yards: 250,
  opponent_yards: 200,
  instances: [...],
  triggered_buy: true,
  buy_id: "buy-uuid"
}

Buy Document

{
  id: "uuid",
  value_signal_id: "signal-uuid",
  game_id: "espn-event-id",
  market: "kalshi",
  ticker: "KXNFLGAME-...",
  market_id: "KXNFLGAME-...",
  shares: 200,
  price_per_share: 0.35,
  total_cost: 70.00,
  is_live_buy: false,
  team: "Team Name",
  opponent: "Opponent Name",
  sport: "nfl",
  strategy_id: "football-undervalued-yard-leaders",
  strategy_name: "Undervalued Yard Leaders",
  value_score: 75.5,
  yards_advantage: 0.25,
  score_difference: -3,
  current_market_value: 70.00,
  is_correct: null,
  final_value: null,
  profit: null,
  created_at: "2025-11-26T...",
  closed_at: null
}

Example Scenarios

Scenario 1: Strong Comeback Candidate (ELITE)

  • Situation: Underdog down 3 in Q2, 8:45 remaining
  • Yards: Underdog 250, Favorite 200 (25% advantage)
  • Price: $0.30
  • Value Score: 85
  • Tier: ELITE
  • Action: Buy 200 shares @ $0.30 = $60.00

Scenario 2: Marginal Opportunity (GOOD)

  • Situation: Underdog tied in Q3, 6:30 remaining
  • Yards: Underdog 180, Favorite 150 (20% advantage)
  • Price: $0.42
  • Value Score: 52
  • Tier: GOOD
  • Action: Buy 100 shares @ $0.42 = $42.00

Scenario 3: Not Winnable (Skipped)

  • Situation: Underdog down 21 in Q3, 2:15 remaining
  • Yards: Underdog 300, Favorite 200 (50% advantage)
  • Price: $0.15
  • Value Score: 0 (not winnable)
  • Action: Skip (no signal created)

Performance Tracking

Metrics Available

  • Win rate by tier (GOOD, STRONG, ELITE)
  • ROI by tier
  • Average value score of wins vs losses
  • Yards advantage correlation with wins
  • Quarter distribution of signals
  • Price range analysis

Daily Summaries

  • Automated at 5am PST
  • Shows previous day's buys
  • Win/loss breakdown
  • Total profit/loss
  • ROI calculation

Best Practices

  1. Start Simulated

    • Always test with is_live_buy = false first
    • Validate strategy performance over time
    • Build confidence before going live
  2. Monitor Yards Data

    • ESPN API can occasionally have stale data
    • Verify yards make sense for game situation
    • Check for data quality issues
  3. Respect Game Phases

    • Q1 too volatile, Q4 too risky
    • Q2/Q3 sweet spot for value capture
    • Don't override these constraints
  4. Watch Winnability

    • Algorithm is conservative by design
    • Large deficits + low time = auto-skip
    • Trust the winnability logic
  5. Track Performance

    • Review daily summaries
    • Analyze which tiers perform best
    • Adjust MIN_VALUE_SCORE if needed

Troubleshooting

No Signals Created

  • Check if games are in Q2/Q3
  • Verify ESPN yards data is available
  • Confirm clear underdog exists (< $0.50)
  • Check yards advantage β‰₯ 20%

Buys Not Triggering

  • Verify value score β‰₯ MIN_VALUE_SCORE
  • Check if signal already triggered buy
  • Confirm buy service is initialized

Discord Not Sending

  • Verify DISCORD_WEBHOOK_URL is set
  • Check network connectivity
  • Review Discord rate limits

Future Enhancements

  • Live market tracking: Update current_market_value in real-time
  • Advanced yards metrics: Separate rushing vs passing analysis
  • Time-of-possession factor: Additional context for yards dominance
  • Defensive stats: Incorporate turnovers, sacks, etc.
  • Weather integration: Adjust for conditions affecting passing

Hockey Underdogs Strategy - Complete Guide

Overview

The "Hockey Underdogs" strategy targets extreme underdogs in NHL pre-game markets. Simple premise: when the market prices a team at ≀$0.39, there's potential value to capture from market overreaction.

Strategy Details

Name: Hockey Underdogs Sport: NHL Type: Pre-game only (isPreGame=true, isLiveGame=false) Max Price: $0.39 (only considers teams at or below this threshold)

Philosophy

Why Target Extreme Underdogs?

  1. Market Inefficiency: Markets can overreact to recent performance, injuries, or perceived team strength
  2. Binary Outcomes: Hockey games have three outcomes (win/loss/tie), creating pricing inefficiencies
  3. Variance: Hockey is high-variance - underdogs win more often than their price suggests
  4. Value Detection: When market dramatically undervalues a team, there's profit opportunity

The $0.39 Threshold

  • Teams priced above $0.39 are "expected underdogs" - no special value
  • Teams at $0.39 or below are "extreme underdogs" - market has written them off
  • This threshold captures the ~10-15% of games where markets overreact

Algorithm

Signal Criteria

A value signal is created when:

  1. Game is pre-game - Has not started yet
  2. Team price ≀ $0.39 - Extreme underdog threshold
  3. Value score β‰₯ MIN_VALUE_SCORE_HOCKEY - Default: 50.0

Update Logic

Once a signal exists for a game/team:

  • Ignore if price increases or decreases < 10%
  • Update only if price drops β‰₯ 10% (significant market move)
  • This prevents noise and focuses on meaningful price changes

Value Score Formula (0-100 scale)

Price-Based Scoring (lower price = higher value):

Price Range Base Score Logic
$0.01 99 Nearly written off
$0.01-$0.05 95-99 Extreme underdog
$0.05-$0.10 90-95 Very strong value
$0.10-$0.20 75-90 Strong value
$0.20-$0.30 60-75 Good value
$0.30-$0.39 50-60 Decent value
>$0.39 0 No signal

Price Drop Bonus (if updating existing signal):

Price Drop Bonus Points Description
β‰₯ 30% +15 Dramatic market shift
β‰₯ 20% +10 Major undervaluing
β‰₯ 10% +5 Significant drop
β‰₯ 5% +2 Minor adjustment
< 5% 0 Ignored (no update)

Value Score Tiers

Tier Score Range Emoji Auto-Buy?
ELITE 90-100 πŸ”₯ Yes (if β‰₯80)
STRONG 75-89 πŸ’Ž Yes (if β‰₯80)
GOOD 65-74 βœ… No
DECENT 55-64 πŸ“Š No
WEAK 50-54 ⚠️ No
POOR 0-49 ❌ No (below min)

Example Calculations

Example 1: Elite Signal

Game: Chicago Blackhawks @ Colorado Avalanche Price: $0.08 Previous: None (first detection)

price_score = 92.5  # $0.08 in the $0.05-$0.10 range
price_drop_bonus = 0  # First detection

total = 92.5 (ELITE πŸ”₯)

Result: Auto-buy triggered! Market has nearly written off the Blackhawks.

Example 2: Strong Signal with Update

Game: Arizona Coyotes @ Vegas Golden Knights Initial Price: $0.25 (value score: 67.5) New Price: $0.18 (28% drop!)

price_score = 78.0  # $0.18 in the $0.10-$0.20 range
price_drop_bonus = 10  # 28% drop (β‰₯20%)

total = 78.0 + 10 = 88.0 (STRONG πŸ’Ž)

Result: Signal updated! Auto-buy triggered due to dramatic price drop.

Example 3: Ignored Update

Game: Seattle Kraken @ Edmonton Oilers Previous Price: $0.35 New Price: $0.33 (5.7% drop)

price_drop_pct = 5.7% < 10%

Result: Update ignored - price change not significant enough.

Example 4: Rejected - Above Threshold

Game: Buffalo Sabres @ Toronto Maple Leafs Price: $0.42

Result: Rejected - Price above $0.39 threshold. Not an extreme underdog.

Configuration

Environment Variables (.env)

# Hockey Value Thresholds
MIN_VALUE_SCORE_HOCKEY=50.0    # Minimum to log signal
MIN_BUY_VALUE_HOCKEY=80.0      # Minimum to auto-buy

# Shared Settings
BUY_SHARES=100                 # Shares per auto-buy
DISCORD_WEBHOOK_URL=https://...

Tuning Recommendations

Conservative (only elite signals)

MIN_VALUE_SCORE_HOCKEY=75.0
MIN_BUY_VALUE_HOCKEY=90.0

Moderate (current default)

MIN_VALUE_SCORE_HOCKEY=50.0
MIN_BUY_VALUE_HOCKEY=80.0

Aggressive (more signals, lower quality)

MIN_VALUE_SCORE_HOCKEY=40.0
MIN_BUY_VALUE_HOCKEY=70.0

Cloud Function

Schedule

Runs every 6 hours to check upcoming games

Process

  1. Fetch upcoming NHL games from ESPN (pre-game status only)
  2. Get NHL markets from Kalshi
  3. Match games to markets by team names
  4. For each team in each game:
    • Check if price ≀ $0.39
    • Check if signal already exists
    • If exists: check for β‰₯10% price drop
    • Calculate value score (with price drop bonus if applicable)
    • Create/update signal if score β‰₯ MIN_VALUE_SCORE_HOCKEY
    • Trigger auto-buy if score β‰₯ MIN_BUY_VALUE_HOCKEY
    • Send Discord notification

Discord Notifications

New Signal

πŸ’ 1 Hockey Underdog Found!

πŸ”₯ Hockey Underdog: Chicago Blackhawks vs Colorado Avalanche

Chicago Blackhawks priced at extreme underdog value: $0.08

πŸ• Underdog Team          πŸ†š Opponent              πŸ’ Matchup
Chicago Blackhawks ($0.08) Colorado Avalanche      CHI @ COL

⏰ Status                  🎯 Ticker                ⭐ Value Score
Pre-game                   KXNHL-...                92.5 (ELITE)

Sport: NHL | Strategy: Hockey Underdogs

Updated Signal (Price Drop)

πŸ”” Hockey Underdog Updated (Instance #2)

πŸ“‰ PRICE DROP
Was $0.25 β†’ Now $0.18 (-28.0%)

πŸ’Ž Hockey Underdog: Arizona Coyotes vs Vegas Golden Knights

Arizona Coyotes priced at extreme underdog value: $0.18

...

⭐ Value Score
88.0 (STRONG)

Auto-Buy Triggered

πŸ”” Hockey Underdog Updated (Instance #1)

πŸ€– AUTO-BUY TRIGGERED
βœ… Simulated purchase executed

πŸ”₯ Hockey Underdog: Chicago Blackhawks vs Colorado Avalanche
...

Files Created

Strategy

  • backend/src/strategies/hockey/hockey_underdogs.py - Main strategy
  • backend/src/strategies/hockey/__init__.py - Module exports

Utilities

  • backend/src/utils/hockey_value_scorer.py - Value scoring logic

Cloud Functions

  • backend/cloud_functions/main.py - Added analyze_nhl_underdogs()

Configuration

  • backend/.env - Added MIN_VALUE_SCORE_HOCKEY, MIN_BUY_VALUE_HOCKEY

Deployment

Deploy Cloud Function

cd backend/cloud_functions
firebase deploy --only functions:analyze_nhl_underdogs

Monitor

# View function logs
firebase functions:log --only analyze_nhl_underdogs

# Check Firestore
# Collection: valueSignals
# Filter: sport == "nhl"

Strategy Advantages

  1. Clear Threshold: $0.39 is an objective, easy-to-understand cutoff
  2. Pre-game Focus: No live game pressure or rapid changes
  3. Noise Reduction: 10% minimum price drop filter prevents overtrading
  4. Price-Driven: Pure value play based on market pricing
  5. Binary Logic: Simple "underdog or not" decision

Strategy Risks

  1. Extreme Underdogs Lose Often: By definition, these teams are unlikely to win
  2. Small Sample Size: Only ~10-15% of games have such extreme underdogs
  3. Injury Impact: Late scratches can justify low prices
  4. Back-to-Back Games: Tired teams may be correctly priced low
  5. Goalie Changes: Backup goalies can dramatically shift odds

Statistical Context

Expected Value Analysis

Theoretical Breakeven:

  • At $0.39, a team needs to win >39% of the time to be profitable
  • If true win rate is 45%, expected value is positive
  • Market inefficiency exists when win rate > price

Historical Context (general NHL data):

  • Extreme underdogs (<$0.40) win ~25-35% of games
  • Need careful selection to find the 40%+ win rate opportunities
  • Value exists in specific situations: divisional games, home underdogs, revenge games

When Strategy Works Best

  1. Divisional Matchups: Teams know each other, upsets more common
  2. Home Underdogs: Home ice advantage undervalued
  3. After Blowout Loss: Market overreacts to recent performance
  4. Backup Goalie: Market overvalues starting goalie importance
  5. End of Road Trip: Tired favorites, fresh underdogs

Future Enhancements

  1. Historical Analysis: Track actual win rates at different price points
  2. Situational Factors: Back-to-backs, home/away, divisional games
  3. Goalie Tracking: Adjust for starting goalies
  4. Team Form: Recent performance trends
  5. Head-to-Head: Historical matchup data
  6. Line Movement: Track how price has changed over time
  7. Injury News: Integrate injury reports

Performance Tracking

Key Metrics to Monitor

from src.services.buy_service import BuyService
from src.services.firebase_service import FirebaseService

firebase = FirebaseService()
buy_service = BuyService(firebase)

# Get all NHL underdog buys
query = firebase.db.collection('buys').where('sport', '==', 'nhl')
buys = [Buy.from_dict(doc.to_dict()) for doc in query.get()]

# Calculate metrics by price range
price_ranges = {
    '$0.01-$0.10': [],
    '$0.10-$0.20': [],
    '$0.20-$0.30': [],
    '$0.30-$0.39': [],
}

for buy in buys:
    if buy.price_per_share <= 0.10:
        price_ranges['$0.01-$0.10'].append(buy)
    elif buy.price_per_share <= 0.20:
        price_ranges['$0.10-$0.20'].append(buy)
    # ... etc

# Analyze win rate by price range
for range_name, range_buys in price_ranges.items():
    wins = sum(1 for b in range_buys if b.is_correct)
    total = len(range_buys)
    if total > 0:
        win_rate = wins / total * 100
        print(f"{range_name}: {win_rate:.1f}% ({wins}/{total})")

Troubleshooting

No Signals Found

Possible causes:

  1. No upcoming NHL games (off-season, rest days)
  2. No teams priced ≀ $0.39 (competitive games)
  3. MIN_VALUE_SCORE_HOCKEY threshold too high

Solutions:

  • Check ESPN API for upcoming games
  • Verify Kalshi has NHL markets
  • Lower threshold to 40-45 for testing

Signals Not Updating

Issue: Price dropped but signal didn't update

Causes:

  • Price drop < 10% (working as designed)
  • Different game/team than existing signal
  • Signal already has auto-buy triggered

Solution: Review update logic in strategy code

Too Many Signals

Issue: Getting signals for marginal underdogs

Solution: Raise MIN_VALUE_SCORE_HOCKEY to 60-70

Best Practices

  1. Track by Price Range: Monitor win rates in different price buckets
  2. Set Position Limits: Don't over-expose to extreme underdogs
  3. Review Updates: Check why signals are being updated
  4. Adjust Thresholds: Based on historical performance
  5. Consider Context: Playoff games behave differently

Hockey Underdogs strategy is production-ready! πŸ’πŸ•

Leading Undervalued Soccer Strategy - Complete Guide

Overview

The "Leading Undervalued" strategy identifies winning soccer teams that are underpriced on prediction markets. Simple concept: if a team is leading but costs less than $0.70, there's value to capture.

Strategy Details

Name: Leading Undervalued Sport: Soccer Type: Live game only (isLiveGame=true, isPreGame=false) Max Price: $0.70 (never buys above this)

Algorithm

Signal Criteria

A value signal is created when ALL of the following are true:

  1. Game is live - Must be in progress
  2. Team is leading - Any goal lead (1, 2, 3+ goals)
  3. Price < $0.70 - Team must be undervalued
  4. Value score β‰₯ MIN_VALUE_SCORE_SOCCER - Default: 40.0

Value Score Formula (0-100 scale)

The value score combines three factors:

1. Goal Lead (Exponential Impact)

  • 1 goal ahead = 25 points
  • 2 goals ahead = 45 points
  • 3 goals ahead = 60 points
  • 4+ goals ahead = 70 points

Why exponential? Each additional goal makes a comeback exponentially less likely.

2. Price (Inverse Impact)

Lower price = higher value

  • $0.10 = +35 points
  • $0.30 = +25 points
  • $0.50 = +15 points
  • $0.69 = +1 point
  • $0.70+ = Signal rejected

Formula: (0.70 - price) * 50

3. Time Remaining (Inverse Impact)

Less time = higher value

  • 0-10 minutes = +30 points
  • 10-20 minutes = +20 points
  • 20-30 minutes = +12 points
  • 30-45 minutes = +5 points
  • 45+ minutes = +0 points

Why? Less time means less opportunity for opponent to come back.

Value Score Tiers

Tier Score Range Emoji Auto-Buy?
ELITE 85-100 πŸ”₯ Yes (if β‰₯75)
STRONG 70-84 πŸ’Ž Yes (if β‰₯75)
GOOD 55-69 βœ… No
DECENT 40-54 πŸ“Š No
WEAK 25-39 ⚠️ No (below min)
POOR 0-24 ❌ No (below min)

Example Calculations

Example 1: Elite Signal

Game: Manchester City 2 - 0 Liverpool Time: 85' (5 minutes remaining) Price: $0.45

goal_score = 45      # 2 goals ahead
price_impact = 12.5  # (0.70 - 0.45) * 50
time_score = 30      # <10 minutes remaining

total = 45 + 12.5 + 30 = 87.5 (ELITE πŸ”₯)

Result: Auto-buy triggered!

Example 2: Strong Signal

Game: Barcelona 1 - 0 Real Madrid Time: 80' (10 minutes remaining) Price: $0.55

goal_score = 25     # 1 goal ahead
price_impact = 7.5  # (0.70 - 0.55) * 50
time_score = 20     # 10-20 minutes remaining

total = 25 + 7.5 + 20 = 52.5 (DECENT πŸ“Š)

Result: Signal logged, no auto-buy

Example 3: Rejected - Price Too High

Game: PSG 3 - 0 Lyon Time: 70' (20 minutes remaining) Price: $0.75

Result: Rejected - Price β‰₯ $0.70

Example 4: Rejected - Too Early

Game: Bayern 1 - 0 Dortmund Time: 20' (70 minutes remaining) Price: $0.40

goal_score = 25     # 1 goal ahead
price_impact = 15   # (0.70 - 0.40) * 50
time_score = 0      # 45+ minutes remaining

total = 25 + 15 + 0 = 40 (DECENT πŸ“Š)

Result: Signal logged (barely meets minimum), but low value due to time

ESPN Soccer League Codes

The strategy monitors these soccer leagues:

# England
'eng.1': 'Premier League'
'eng.2': 'EFL Championship'
'eng.fa': 'FA Cup'
'eng.league_cup': 'EFL Cup'

# Spain
'esp.1': 'La Liga'
'esp.2': 'La Liga 2'

# Italy
'ita.1': 'Serie A'
'ita.2': 'Serie B'

# Germany
'ger.1': 'Bundesliga'
'ger.2': 'Bundesliga 2'

# France
'fra.1': 'Ligue 1'
'fra.2': 'Ligue 2'

# USA
'usa.1': 'MLS'
'usa.nwsl': 'NWSL'

# International
'uefa.champions': 'UEFA Champions League'
'uefa.europa': 'UEFA Europa League'
'uefa.conf': 'UEFA Conference League'

Configuration

Environment Variables (.env)

# Soccer Value Thresholds
MIN_VALUE_SCORE_SOCCER=40.0    # Minimum to log signal
MIN_BUY_VALUE_SOCCER=75.0      # Minimum to auto-buy

# Shared Settings
BUY_SHARES=100                 # Shares per auto-buy
DISCORD_WEBHOOK_URL=https://...

Tuning Recommendations

Conservative (fewer signals, higher quality)

MIN_VALUE_SCORE_SOCCER=50.0
MIN_BUY_VALUE_SOCCER=80.0

Aggressive (more signals, lower quality)

MIN_VALUE_SCORE_SOCCER=30.0
MIN_BUY_VALUE_SOCCER=65.0

Cloud Function

Schedule

Runs every 5 minutes to catch all live games

Process

  1. Fetch live games from ESPN (all leagues)
  2. Get soccer markets from Kalshi
  3. Match games to markets by team names
  4. For each game with a leader:
    • Check if price < $0.70
    • Calculate value score
    • Create/update signal if score β‰₯ MIN_VALUE_SCORE_SOCCER
    • Trigger auto-buy if score β‰₯ MIN_BUY_VALUE_SOCCER
    • Send Discord notification

Discord Notifications

Soccer Value Signal

⚽ 1 Soccer Buying Opportunity Found!

πŸ’Ž Soccer Value Signal: Barcelona vs Real Madrid

Barcelona leading by 2 goal(s) but priced at $0.45

⚽ Leading Team       πŸ₯… Goal Lead        πŸ“Š Score
Barcelona ($0.45)    +2                  Barcelona 2
                                         Real Madrid 0

⏱️ Time Status       🎯 Ticker           ⭐ Value Score
Period 2 - 75'       KXSOCCER-...        87.5 (ELITE)

Sport: SOCCER | Strategy: Leading Undervalued

Auto-Buy Triggered

πŸ”” Soccer Value Signal Updated (Instance #2)

πŸ€– AUTO-BUY TRIGGERED
βœ… Simulated purchase executed

πŸ”₯ Soccer Value Signal: Barcelona vs Real Madrid
...

Discovery Tool

Use the league discovery tool to find new soccer league codes:

cd backend
python scripts/discover_soccer_leagues.py

This tool:

  1. Fetches soccer markets from Kalshi
  2. Extracts team names
  3. Tries known league codes on ESPN
  4. Matches teams to find active leagues
  5. Outputs Python dict of discovered codes

Files Created

Strategy

  • backend/src/strategies/soccer/leading_undervalued.py - Main strategy
  • backend/src/strategies/soccer/__init__.py - Module exports

Services

  • backend/src/api/espn/soccer_service.py - ESPN soccer API client
  • backend/src/utils/soccer_value_scorer.py - Value scoring logic

Scripts

  • backend/scripts/discover_soccer_leagues.py - League discovery tool

Cloud Functions

  • backend/cloud_functions/main.py - Added analyze_live_soccer_games()

Configuration

  • backend/.env - Added MIN_VALUE_SCORE_SOCCER, MIN_BUY_VALUE_SOCCER

Deployment

Deploy Cloud Function

cd backend/cloud_functions
firebase deploy --only functions:analyze_live_soccer_games

Monitor

# View function logs
firebase functions:log --only analyze_live_soccer_games

# Check Firestore
# Collection: valueSignals
# Filter: sport == "soccer"

Troubleshooting

No Signals Found

Possible causes:

  1. No live soccer games right now
  2. All leading teams priced β‰₯ $0.70
  3. MIN_VALUE_SCORE_SOCCER threshold too high
  4. No Kalshi soccer markets available

Solutions:

  • Lower MIN_VALUE_SCORE_SOCCER to 25-30
  • Check ESPN API for live games manually
  • Verify Kalshi has soccer markets

Team Name Matching Fails

Issue: Can't match Kalshi markets to ESPN games

Solution: The current matching is simplified. For production:

  1. Use the discovery tool to map exact team names
  2. Create a team name normalization function
  3. Handle different naming conventions (e.g., "Man City" vs "Manchester City")

Wrong Team Gets Signal

Issue: Home/away designation mismatch

Solution: Verify Kalshi market structure:

  • Some markets are "Will Team A win?"
  • Others are "Home team to win?"
  • Adjust market_data mapping accordingly

Strategy Advantages

  1. Simple Logic: Easy to understand and trust
  2. Time Decay: Value increases as clock runs down
  3. Conservative: Only buys obvious value (price < $0.70)
  4. Goal Exponential: Properly values multi-goal leads
  5. Real-Time: Runs every 5 minutes to catch opportunities

Strategy Risks

  1. Late Goals: Soccer can change quickly
  2. Stoppage Time: Not accounted for in time calculations
  3. Red Cards: Can dramatically shift game dynamics
  4. Team Name Matching: May miss some games
  5. Limited Data: No possession, shots, or other stats

Future Enhancements

  1. Add Advanced Stats: Possession %, shots on goal, xG
  2. Red Card Detection: Adjust value when team has advantage
  3. Better Team Matching: Use fuzzy matching or database
  4. Historical Win %: Factor in team strength
  5. League Weighting: Different thresholds per league
  6. Multi-Goal Markets: Not just moneyline

Soccer strategy is live and ready for deployment! ⚽

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment