UNPKG

@betalytics/api

Version:

TypeScript SDK for Betalytics API - Sports analytics and betting data

800 lines (656 loc) 23.9 kB
# Betalytics API A TypeScript SDK for accessing the Betalytics API - your comprehensive source for sports analytics and betting data. ## Installation ```bash npm install @betalytics/api # or yarn add @betalytics/api # or pnpm add @betalytics/api ``` ## Quick Start ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient({ baseURL: 'https://api.betalytics.com' }); const nbaPlayerProps = await betalyticsApi.nba.player.getBets({ query: { player: 'LeBron James', bet_grade_from: 7.5 } }); ``` ## Features - **TypeScript Support**: Full TypeScript support with auto-generated types - **Multiple Sports**: Support for NBA, NFL, MLB, NHL, Soccer, and NCAAF - **Organized API**: Clean, organized API by sport and data type - **Flexible Usage**: Use individual sport clients, main client class, or raw functions - **Modern API**: Built with the latest OpenAPI specifications and @hey-api/openapi-ts - **Tree-shakeable**: Import only what you need - **Type-safe**: All requests and responses are fully typed ## API Coverage ### Sports Supported - 🏀 **NBA** (National Basketball Association) - 🏈 **NFL** (National Football League) - **MLB** (Major League Baseball) - 🏒 **NHL** (National Hockey League) - **Soccer** (International leagues) - 🏈 **NCAAF** (College Football) ### Data Types - Game betting recommendations and odds - Player prop betting data - Player and team trends/statistics - Shot heatmap data with coordinates (NHL) - Interactive chart data for visualizations - Goalscorer and goalie props (NHL) - Historical betting data with timestamp filtering - Partner integrations (BetOpenly) ## Usage Examples ### NBA Data ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get NBA game betting data const nbaGames = await betalyticsApi.nba.games.getBets({ query: { limit: 20, game_date_from: '2024-01-01', bookmaker: ['DraftKings', 'FanDuel'], sort: ['home_ml_grade'], order: ['desc'] } }); // Get NBA player props const playerProps = await betalyticsApi.nba.player.getBets({ query: { player: 'LeBron James', market: ['points', 'rebounds', 'assists'], bet_grade_from: 7.5, limit: 10 } }); // Get NBA player trends const playerTrends = await betalyticsApi.nba.player.getTrends({ query: { player_name: 'Stephen Curry', period: ['season', 'last_10_games'], stat_name: ['points', 'threes'] } }); ``` ### NHL Data ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get NHL game betting data const nhlGames = await betalyticsApi.nhl.games.getBets({ query: { game_date: '2024-01-15', league: ['NHL'], sort: ['over_grade'], order: ['desc'] } }); // Get NHL player shot heatmap data const playerShots = await betalyticsApi.nhl.player.getShots({ query: { player_name: 'Connor McDavid', period: 'season', player_team: 'Edmonton Oilers' } }); // Get NHL goalscorer props const goalscorerProps = await betalyticsApi.nhl.goalscorer.getBets({ query: { game_date: '2024-01-15', bet_grade_from: 8.0, sort: ['bet_grade'], order: ['desc'] } }); ``` ### Creating NHL Shot Heatmap Charts The NHL shots endpoints provide rich coordinate and statistical data perfect for creating interactive heatmap visualizations. Here's how to build a chart similar to the one in `chart.astro`: #### Basic Player Shot Heatmap ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get player shot data for charting const playerShotData = await betalyticsApi.nhl.player.getShots({ query: { player_name: 'Connor McDavid', period: 'last_10', player_team: 'Edmonton Oilers', limit: 100 } }); // Extract shot coordinates for visualization const shots = playerShotData.data?.results || []; shots.forEach(player => { // Parse shot coordinate data (JSON strings in the response) const shotCoordinates = JSON.parse(player.shot_coordinates || '[]'); const goalCoordinates = JSON.parse(player.goal_coordinates || '[]'); const individualShots = JSON.parse(player.individual_shots || '[]'); console.log(`${player.player_name} shot data:`, { totalShots: player.total_shots, totalGoals: player.total_goals, shotPercentage: player.shot_percentage, coordinates: shotCoordinates.length, goals: goalCoordinates.length }); }); ``` #### Advanced Team Shot Analysis ```typescript // Get team shot data with comprehensive statistics const teamShotData = await betalyticsApi.nhl.team.getShots({ query: { team: 'Edmonton Oilers', period: 'season_2024', limit: 50 } }); // Process team shot data for visualization const teams = teamShotData.data?.results || []; teams.forEach(team => { // Parse coordinate data for both offensive and defensive stats const offensiveShots = JSON.parse(team.shot_coordinates || '[]'); const offensiveGoals = JSON.parse(team.goal_coordinates || '[]'); const defensiveShots = JSON.parse(team.shot_coordinates_against || '[]'); const defensiveGoals = JSON.parse(team.goal_coordinates_against || '[]'); console.log(`${team.team_name} comprehensive stats:`, { // Offensive stats avgShotsPerGame: team.avg_shots_per_game, avgGoalsPerGame: team.avg_goals_per_game, shotPercentage: team.shot_percentage, // Defensive stats avgShotsAgainstPerGame: team.avg_shots_against_per_game, avgGoalsAgainstPerGame: team.avg_goals_against_per_game, savePercentage: team.save_percentage, // Range breakdown shotsCloseRange: team.shots_close_range, shotsMidRange: team.shots_mid_range, shotsLongRange: team.shots_long_range, // Coordinate data for mapping offensiveCoordinates: offensiveShots.length, defensiveCoordinates: defensiveShots.length }); }); ``` #### Interactive Shot Chart Component Here's how to create a React component similar to the ShotHeatmap in the chart.astro example: ```typescript import React, { useState, useEffect } from 'react'; import { BetalyticsClient } from '@betalytics/api'; interface ShotChartProps { mode: 'player' | 'team'; playerName?: string; teamName?: string; period: 'last_10' | 'last_20' | 'season_2024'; } const ShotChart: React.FC<ShotChartProps> = ({ mode, playerName, teamName, period }) => { const [shotData, setShotData] = useState<any[]>([]); const [loading, setLoading] = useState(false); const betalyticsApi = new BetalyticsClient({ baseURL: 'https://api.betalytics.com' }); useEffect(() => { const fetchData = async () => { setLoading(true); try { if (mode === 'player' && playerName) { const response = await betalyticsApi.nhl.player.getShots({ query: { player_name: playerName, period: period, limit: 100 } }); setShotData(response.data?.results || []); } else if (mode === 'team' && teamName) { const response = await betalyticsApi.nhl.team.getShots({ query: { team: teamName, period: period, limit: 100 } }); setShotData(response.data?.results || []); } } catch (error) { console.error('Error fetching shot data:', error); } finally { setLoading(false); } }; fetchData(); }, [mode, playerName, teamName, period]); if (loading) return <div>Loading shot chart...</div>; return ( <div className="shot-chart"> <h3>NHL {mode === 'player' ? 'Player' : 'Team'} Shot Heatmap</h3> {shotData.map((item, index) => { // Parse coordinate data const shots = JSON.parse(item.shot_coordinates || '[]'); const goals = JSON.parse(item.goal_coordinates || '[]'); return ( <div key={index} className="shot-data"> <h4>{item.player_name || item.team_name}</h4> <div className="stats"> <span>Shots: {item.total_shots}</span> <span>Goals: {item.total_goals}</span> <span>Percentage: {item.shot_percentage?.toFixed(1)}%</span> </div> {/* Render your heatmap visualization here using shots/goals coordinates */} </div> ); })} </div> ); }; export default ShotChart; ``` #### Shot Chart Filter Options ```typescript // Get available filter options for dynamic UI components const playerShotOptions = await betalyticsApi.nhl.player.getShotsOptions(); const teamShotOptions = await betalyticsApi.nhl.team.getShotsOptions(); console.log('Player filters:', { players: playerShotOptions.data?.results.fields_filter_options?.player_name || [], positions: playerShotOptions.data?.results.fields_filter_options?.player_position || [], teams: playerShotOptions.data?.results.fields_filter_options?.player_team || [], periods: playerShotOptions.data?.results.fields_filter_options?.period || [] }); console.log('Team filters:', { teams: teamShotOptions.data?.results.fields_filter_options?.team_name || [], periods: teamShotOptions.data?.results.fields_filter_options?.period || [] }); ``` #### Data Structure for Visualization The shots endpoints return coordinate data as JSON strings that can be parsed for heatmap creation: ```typescript interface ShotCoordinate { x: number; // X coordinate on ice (typically -100 to 100) y: number; // Y coordinate on ice (typically -42.5 to 42.5) count: number; // Number of shots at this location } interface IndividualShot { x: number; y: number; event_type: string; // 'SHOT', 'GOAL', 'MISSED_SHOT' shot_direction: 'for' | 'against'; game_id?: string; opponent_team?: string; } interface ShotCluster { x: number; y: number; zone: string; // 'close_range', 'mid_range', 'long_range' event_type: string; count: number; distance: number; // Distance from goal angle: number; // Angle to goal } // Parse response data for visualization const playerData = shotResponse.data?.results[0]; if (playerData) { const shotCoordinates: ShotCoordinate[] = JSON.parse(playerData.shot_coordinates || '[]'); const goalCoordinates: ShotCoordinate[] = JSON.parse(playerData.goal_coordinates || '[]'); const individualShots: IndividualShot[] = JSON.parse(playerData.individual_shots || '[]'); const shotClusters: ShotCluster[] = JSON.parse(playerData.shot_clusters || '[]'); // Use coordinate data for heatmap rendering } ``` ### MLB Data ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get MLB game betting data const mlbGames = await betalyticsApi.mlb.games.getBets({ query: { game_date_from: '2024-04-01', game_date_to: '2024-04-07', over_grade_from: 8.0, sort: ['game_time'], order: ['asc'] } }); // Get MLB player props const batterProps = await betalyticsApi.mlb.player.getBets({ query: { player: 'Aaron Judge', market: ['home_runs', 'hits', 'rbis'], game_date: '2024-04-15' } }); // Get MLB team trends const teamTrends = await betalyticsApi.mlb.team.getTrends({ query: { team_name: 'New York Yankees', period: ['season', 'last_10_games'], stat_name: ['runs_scored', 'runs_allowed'] } }); ``` ### NFL Data ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get NFL game betting data const nflGames = await betalyticsApi.nfl.games.getBets({ query: { game_date: '2024-01-14', home_ml_grade_from: 8.0, sort: ['game_time'], order: ['asc'] } }); // Get NFL player props const playerProps = await betalyticsApi.nfl.player.getBets({ query: { player: 'Patrick Mahomes', market: ['passing_yards', 'passing_touchdowns'], game_date: '2024-01-14' } }); // Get NFL touchdown props const touchdownProps = await betalyticsApi.nfl.touchdown.getBets({ query: { game_date: '2024-01-14', player_position: ['RB', 'WR', 'TE'], bet_grade_from: 7.5 } }); ``` ### Soccer Data ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get soccer game betting data const soccerGames = await betalyticsApi.soccer.games.getBets({ query: { league: ['Premier League', 'La Liga'], game_date_from: '2024-01-01', home_ml_grade_from: 8.0, sort: ['game_time'], order: ['asc'] } }); // Get available filter options const filterOptions = await betalyticsApi.soccer.games.getBetsOptions(); console.log(filterOptions.data.results.fields_filter_options); ``` ### Partner Integration (BetOpenly) ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get recommended open bets from BetOpenly const openBets = await betalyticsApi.partners.betOpenly.getOpenBets({ query: { onlyRecommended: true, limit: 20 } }); // Check BetOpenly API status const status = await betalyticsApi.partners.betOpenly.getStatus(); ``` ### Historical Data All leagues support historical data queries with ETL timestamp filtering: ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); // Get historical NBA games with ETL timestamp filtering const nbaHistoricalGames = await betalyticsApi.nba.historical.games.getBets({ query: { historical_date_from: '2024-01-01T00:00:00Z', historical_date_to: '2024-12-31T23:59:59Z', home_ml_grade_from: 8.0, limit: 20 } }); // Get historical MLB player props const mlbHistoricalProps = await betalyticsApi.mlb.historical.player.getBets({ query: { player: 'Aaron Judge', historical_date_from: '2024-06-01T00:00:00Z', bet_grade_from: 7.5, limit: 10 } }); // Get historical NFL games const nflHistoricalGames = await betalyticsApi.nfl.historical.games.getBets({ query: { game_date_from: '2024-09-01', historical_date_from: '2024-09-01T00:00:00Z', over_grade_from: 8.0 } }); // Get historical NHL player props const nhlHistoricalProps = await betalyticsApi.nhl.historical.player.getBets({ query: { player_position: 'F', historical_date_from: '2024-10-01T00:00:00Z', proj: 0.3 } }); // Get historical Soccer games const soccerHistoricalGames = await betalyticsApi.soccer.historical.games.getBets({ query: { league: ['Premier League'], historical_date_from: '2024-08-01T00:00:00Z', home_ml_grade_from: 7.0 } }); // Get historical NCAAF games const ncaafHistoricalGames = await betalyticsApi.ncaaf.historical.games.getBets({ query: { game_date_from: '2024-08-01', historical_date_from: '2024-08-01T00:00:00Z' } }); ``` ### Using the Main Client Class ```typescript import BetalyticsClient from '@betalytics/api'; // Initialize the client const betalyticsApi = new BetalyticsClient({ baseURL: 'https://api.betalytics.com', headers: { 'Authorization': 'Bearer your-token-here' } }); // Use any sport const nbaGames = await betalyticsApi.nba.games.getBets({ query: { limit: 10 } }); const nflProps = await betalyticsApi.nfl.player.getBets({ query: { limit: 10 } }); const mlbTrends = await betalyticsApi.mlb.player.getTrends({ query: { limit: 10 } }); const nhlShots = await betalyticsApi.nhl.player.getShots({ query: { limit: 10 } }); // Update configuration betalyticsApi.setConfig({ headers: { 'X-API-Key': 'new-key' } }); ``` ## Configuration ```typescript import { client, BetalyticsClient } from '@betalytics/api'; // Option 1: Configure the global client client.setConfig({ baseURL: 'https://api.betalytics.com', headers: { 'Authorization': 'Bearer your-token-here', 'User-Agent': 'Your App/1.0' } }); // Option 2: Use the main client class const betalytics = new BetalyticsClient({ baseURL: 'https://api.betalytics.com', headers: { 'Authorization': 'Bearer your-token-here' } }); // Get current config const config = client.getConfig(); ``` ## Query Parameters Most endpoints support common query parameters: - **Pagination**: `offset`, `limit` - **Filtering**: `game_date_from`, `game_date_to`, `bookmaker`, `league`, `player`, `team` - **Historical Filtering**: `historical_date_from`, `historical_date_to` (ETL timestamp filtering) - **Sorting**: `sort`, `order` - **Grading**: `bet_grade_from`, `bet_grade_to`, `home_ml_grade_from`, etc. - **Display**: `mode` ('expand' or 'compact') ## Response Types All responses are fully typed. Common response structure: ```typescript { data: { count: number; // Items in current page total_count: number; // Total items available results: Array<T>; // Array of typed results } } ``` ## Error Handling ```typescript import { BetalyticsClient } from '@betalytics/api'; const betalyticsApi = new BetalyticsClient(); try { const response = await betalyticsApi.nba.games.getBets({ query: { limit: 10 } }); if (response.error) { console.error('API Error:', response.error); } else { console.log('Success:', response.data); } } catch (error) { console.error('Network Error:', error); } ``` ## Available APIs ### NBA - `betalyticsApi.nba.games.getBets()` - NBA game betting data - `betalyticsApi.nba.games.getBetsOptions()` - NBA game betting options - `betalyticsApi.nba.player.getBets()` - NBA player props - `betalyticsApi.nba.player.getBetsOptions()` - NBA player prop options - `betalyticsApi.nba.player.getTrends()` - NBA player trends - `betalyticsApi.nba.player.getTrendsOptions()` - NBA player trend options - `betalyticsApi.nba.team.getTrends()` - NBA team trends - `betalyticsApi.nba.team.getTrendsOptions()` - NBA team trend options - `betalyticsApi.nba.historical.games.getBets()` - NBA historical game betting data - `betalyticsApi.nba.historical.games.getBetsOptions()` - NBA historical game betting options - `betalyticsApi.nba.historical.player.getBets()` - NBA historical player props - `betalyticsApi.nba.historical.player.getBetsOptions()` - NBA historical player prop options ### NFL - `betalyticsApi.nfl.games.getBets()` - NFL game betting data - `betalyticsApi.nfl.games.getBetsOptions()` - NFL game betting options - `betalyticsApi.nfl.player.getBets()` - NFL player props - `betalyticsApi.nfl.player.getBetsOptions()` - NFL player prop options - `betalyticsApi.nfl.touchdown.getBets()` - NFL touchdown props - `betalyticsApi.nfl.touchdown.getBetsOptions()` - NFL touchdown prop options - `betalyticsApi.nfl.historical.games.getBets()` - NFL historical game betting data - `betalyticsApi.nfl.historical.games.getBetsOptions()` - NFL historical game betting options - `betalyticsApi.nfl.historical.player.getBets()` - NFL historical player props - `betalyticsApi.nfl.historical.player.getBetsOptions()` - NFL historical player prop options ### MLB - `betalyticsApi.mlb.games.getBets()` - MLB game betting data - `betalyticsApi.mlb.games.getBetsOptions()` - MLB game betting options - `betalyticsApi.mlb.player.getBets()` - MLB player props - `betalyticsApi.mlb.player.getBetsOptions()` - MLB player prop options - `betalyticsApi.mlb.player.getTrends()` - MLB player trends - `betalyticsApi.mlb.player.getTrendsOptions()` - MLB player trend options - `betalyticsApi.mlb.team.getTrends()` - MLB team trends - `betalyticsApi.mlb.team.getTrendsOptions()` - MLB team trend options - `betalyticsApi.mlb.historical.games.getBets()` - MLB historical game betting data - `betalyticsApi.mlb.historical.games.getBetsOptions()` - MLB historical game betting options - `betalyticsApi.mlb.historical.player.getBets()` - MLB historical player props - `betalyticsApi.mlb.historical.player.getBetsOptions()` - MLB historical player prop options ### NHL - `betalyticsApi.nhl.games.getBets()` - NHL game betting data - `betalyticsApi.nhl.games.getBetsOptions()` - NHL game betting options - `betalyticsApi.nhl.player.getBets()` - NHL player props - `betalyticsApi.nhl.player.getBetsOptions()` - NHL player prop options - `betalyticsApi.nhl.player.getTrends()` - NHL player trends - `betalyticsApi.nhl.player.getTrendsOptions()` - NHL player trend options - `betalyticsApi.nhl.player.getShots()` - NHL player shot heatmaps - `betalyticsApi.nhl.player.getShotsOptions()` - NHL player shot options - `betalyticsApi.nhl.team.getTrends()` - NHL team trends - `betalyticsApi.nhl.team.getTrendsOptions()` - NHL team trend options - `betalyticsApi.nhl.team.getShots()` - NHL team shot heatmaps - `betalyticsApi.nhl.team.getShotsOptions()` - NHL team shot options - `betalyticsApi.nhl.goalscorer.getBets()` - NHL goalscorer props - `betalyticsApi.nhl.goalscorer.getBetsOptions()` - NHL goalscorer prop options - `betalyticsApi.nhl.goalie.getBets()` - NHL goalie props - `betalyticsApi.nhl.goalie.getBetsOptions()` - NHL goalie prop options - `betalyticsApi.nhl.historical.games.getBets()` - NHL historical game betting data - `betalyticsApi.nhl.historical.games.getBetsOptions()` - NHL historical game betting options - `betalyticsApi.nhl.historical.player.getBets()` - NHL historical player props - `betalyticsApi.nhl.historical.player.getBetsOptions()` - NHL historical player prop options ### Soccer - `betalyticsApi.soccer.games.getBets()` - Soccer game betting data - `betalyticsApi.soccer.games.getBetsOptions()` - Soccer game betting options - `betalyticsApi.soccer.historical.games.getBets()` - Soccer historical game betting data - `betalyticsApi.soccer.historical.games.getBetsOptions()` - Soccer historical game betting options ### NCAAF - `betalyticsApi.ncaaf.games.getBets()` - NCAAF game betting data - `betalyticsApi.ncaaf.games.getBetsOptions()` - NCAAF game betting options - `betalyticsApi.ncaaf.historical.games.getBets()` - NCAAF historical game betting data - `betalyticsApi.ncaaf.historical.games.getBetsOptions()` - NCAAF historical game betting options ### Partners - `betalyticsApi.partners.betOpenly.getStatus()` - BetOpenly API status - `betalyticsApi.partners.betOpenly.getOpenBets()` - BetOpenly open bets ## TypeScript Support This SDK provides comprehensive TypeScript types for all API calls: ```typescript import type { GetApiNbaV1GamesBetsData, GetApiNbaV1GamesBetsResponse, GetApiNhlV1PlayerBetsData } from '@betalytics/api'; // Type-safe query parameters const queryParams: GetApiNbaV1GamesBetsData['query'] = { limit: 10, game_date_from: '2024-01-01', sort: ['game_time'], order: ['asc'] }; // Type-safe response handling const betalyticsApi = new BetalyticsClient(); const response: GetApiNbaV1GamesBetsResponse = await betalyticsApi.nba.games.getBets({ query: queryParams }); ``` ## Development ### Building the SDK ```bash # Install dependencies npm install # Build the package npm run build # Run tests npm test # Clean build artifacts npm run clean ``` ### Project Structure ``` packages/sdk/ ├── src/ ├── client.gen.ts # Generated client code ├── sdk.gen.ts # Generated SDK methods ├── types.gen.ts # Generated TypeScript types ├── index.ts # Main export file ├── client/ # Client utilities └── core/ # Core functionality ├── index.ts # Entry point ├── package.json # Package configuration └── README.md # This file ``` ## Contributing We welcome contributions! Please feel free to submit issues and pull requests. ## License MIT License - see LICENSE file for details. ## Support For support, please visit our [GitHub Issues](https://github.com/your-org/etl-pipeline/issues) page.