Skip to main content

Overview

The Tracking API manages user bet tracking, performance statistics, and alert data reconstruction. It enables users to track actual bets, view statistics, and automatically grade results.

BetTrackingSystem

Initialize System

from PROPPR.SharedServices.tracking.bet_tracking_system import BetTrackingSystem

tracker = BetTrackingSystem(
    mongo_connection_string=MONGO_CONNECTION_STRING,
    database_name=MONGO_DATABASE,
    bot_type='player'  # 'player' or 'team'
)
mongo_connection_string
string
required
MongoDB connection string
database_name
string
required
Database name
bot_type
string
default:"player"
Bot type: ‘player’ or ‘team’

Track Bets

Track New Bet

result = tracker.track_bet(
    user_id=123456789,
    alert_data={
        'Player': 'Mohamed Salah',
        'Team': 'Liverpool',
        'Market': 'Player Shots On Target',
        'Threshold': 1.5,
        'market_direction': 'over',
        'Odds': 2.10,
        'Match': 'Liverpool vs Man City',
        'Date': '2024-03-10',
        'Time': '16:30',
        'fixture_id': 12345
    },
    actual_stake=10.0,
    unit_size=10.0
)
user_id
integer
required
Telegram user ID
alert_data
object
required
Alert data from alerts collection
actual_stake
float
required
Actual stake amount in currency
unit_size
float
required
User’s unit size for conversion
success
boolean
Whether bet was tracked successfully
bet_id
string
Unique bet tracking ID
message
string
Success/error message

Get Statistics

Get User Stats

stats = tracker.get_user_stats(user_id=123456789)
total_bets
integer
Total number of tracked bets
wins
integer
Number of winning bets
losses
integer
Number of losing bets
refunds
integer
Number of refunded bets
pending
integer
Number of pending bets
half_wins
integer
Number of half-win bets
half_losses
integer
Number of half-loss bets
total_staked_units
float
Total units staked
total_returns_units
float
Total units returned
settled_staked_units
float
Units staked on settled bets only
settled_returns_units
float
Units returned from settled bets only
pending_staked_units
float
Units staked on pending bets
profit_loss_units
float
Profit/loss in units (settled bets only)
roi_percentage
float
Return on investment percentage (settled bets only)
bets
array
Array of all tracked bets

Update Bets

Update Bet Result

success = tracker.update_bet_result(
    user_id=123456789,
    bet_id="bet_12345",
    result_status="won",
    actual_value=2.0,
    manual_override=True
)
user_id
integer
required
User ID
bet_id
string
required
Unique bet tracking ID
result_status
string
required
“won”, “lost”, “refund”, “half_win”, or “half_loss”
actual_value
float
Actual statistic value
manual_override
boolean
default:"false"
Mark bet as manually graded (protected from auto-grading)

Update Stake

success = tracker.update_bet_stake(
    user_id=123456789,
    bet_id="bet_12345",
    new_stake=20.0
)

Update Odds

success = tracker.update_bet_odds(
    user_id=123456789,
    bet_id="bet_12345",
    new_odds=2.30
)

Auto-Settlement

Auto-Settle User Bets

result = tracker.auto_settle_user_bets(
    user_id=123456789,
    api_token=FOTMOB_API_TOKEN
)
user_id
integer
required
User ID to settle bets for
api_token
string
FotMob API token (optional, uses config if not provided)
settled_count
integer
Number of bets settled
settled_bets
array
Array of settled bet details
message
string
Success/error message

Bet Queries

Get Pending Bets

pending = tracker.get_pending_bets(user_id=123456789)
pending_bets
array
Array of pending bet documents

Delete Bet

success = tracker.delete_bet(
    user_id=123456789,
    bet_id="bet_12345"
)

Format Messages

Format Stats Message

message = tracker.format_stats_message(
    stats=stats,
    username="john_doe"
)
Returns formatted Telegram message:
📊 **Betting Statistics** - @john_doe

📈 **Performance**
├ Total Bets: 50
├ Settled: 45
├ Wins: 28 (+ 2 half wins)
├ Losses: 15 (+ 1 half losses)
├ Refunds: 1
├ Pending: 5
└ Win Rate: 64.4% (settled only)

💰 **Financials** (settled only)
├ Staked: 450.00u
├ Returns: 563.20u
├ Profit/Loss: 🜢 +113.20u
└ ROI: 🜢 +25.2%

⏳ **Pending**: 5 bets (50.00u staked)

📝 **Recent Bets**
✅ Mohamed Salah Shots On Target @2.10 (1.00u)
❌ Erling Haaland Goals @1.90 (1.00u)
...

AlertReconstructionService

Initialize Service

from PROPPR.SharedServices.tracking.alert_reconstruction_service import AlertReconstructionService

reconstructor = AlertReconstructionService(
    sportmonks_api_token=SPORTMONKS_API_TOKEN,
    player_alerts_collection=player_alerts_collection,
    team_alerts_collection=team_alerts_collection
)
sportmonks_api_token
string
SportMonks API token (optional - SportMonks is deprecated)
player_alerts_collection
Collection
required
MongoDB collection for player alerts
team_alerts_collection
Collection
required
MongoDB collection for team alerts

Reconstruct Alerts

Reconstruct from Alert ID

alert = reconstructor.reconstruct_from_alert_id(
    alert_id="12345|67890|Player Goals|last5|Bet365",
    bot_type='player'
)
alert_id
string
required
Composite alert ID
bot_type
string
default:"player"
‘player’ or ‘team’
Alert ID Format:
  • Player: player_id|fixture_id|market|scope|bookmaker|direction|threshold
  • Team: team_id|fixture_id|market|scope|bookmaker

Reconstruct from Message

alert = reconstructor.reconstruct_from_message_text(
    message_text=telegram_message,
    bot_type='player'
)
Extracts data from formatted Telegram alert messages.

Search Database

alert = reconstructor.search_alert_in_db(
    fixture_id=12345,
    player_id=67890,
    market="Player Goals",
    bot_type='player'
)

Search by Names

alert = reconstructor.search_alert_by_names(
    fixture_name="Liverpool vs Man City",
    player_name="Mohamed Salah",
    market="Player Shots On Target",
    bot_type='player'
)

Full Reconstruction

Reconstruct Alert

alert = reconstructor.reconstruct_alert(
    alert_id="12345|67890|Player Goals|last5|Bet365",
    message_text=telegram_message,
    bot_type='player'
)
Cascading Fallback Methods:
  1. Parse alert_id and search database by IDs
  2. Extract from message text and search by names
  3. Use SportMonks API to reconstruct (if available)
  4. Return None if all methods fail

Bet Document Structure

bet_doc = {
    "bet_id": "bet_12345",
    "alert_id": "alert_67890",
    "tracked_at": datetime.now(timezone.utc),
    "player_name": "Mohamed Salah",
    "player_id": 12345,
    "team": "Liverpool",
    "team_id": 55,
    "market": "Player Shots On Target",
    "match": "Liverpool vs Man City",
    "date": "2024-03-10",
    "time": "16:30",
    "threshold": 1.5,
    "market_direction": "over",
    "bookmaker": "Bet365",
    "odds": 2.10,
    "actual_stake": 10.0,
    "unit_size": 10.0,
    "units_staked": 1.0,
    "status": "pending",
    "manual_override": False,
    "returns": 0.0,
    "profit_loss": 0.0,
    "fixture_id": 67890,
    "result_tracking": {
        "api_type_id": 86,
        "api_location": "player",
        "stat_type": "shots_on_target",
        "expected_threshold": 1.5,
        "market_direction": "over",
        "result_status": "pending",
        "actual_value": None
    }
}

Example Usage

Complete Tracking Flow

# Initialize tracker
tracker = BetTrackingSystem(
    mongo_connection_string=MONGO_CONNECTION_STRING,
    database_name=MONGO_DATABASE,
    bot_type='player'
)

# Track bet
result = tracker.track_bet(
    user_id=123456789,
    alert_data=alert_data,
    actual_stake=10.0,
    unit_size=10.0
)

if result['success']:
    print(f"Bet tracked: {result['bet_id']}")

# Get stats
stats = tracker.get_user_stats(user_id=123456789)
print(f"ROI: {stats['roi_percentage']:.1f}%")

# Auto-settle finished bets
settle_result = tracker.auto_settle_user_bets(user_id=123456789)
print(f"Settled {settle_result['settled_count']} bets")

# Update manually if needed
tracker.update_bet_result(
    user_id=123456789,
    bet_id=result['bet_id'],
    result_status='won',
    actual_value=2.0,
    manual_override=True
)

References

  • Source: SharedServices/tracking/bet_tracking_system.py
  • Source: SharedServices/tracking/alert_reconstruction_service.py
  • Related: Grading API
  • Related: Bet Model

Build docs developers (and LLMs) love