### Set Up Development Environment Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/contributing.md Set up a Python virtual environment, install development dependencies, and install pre-commit hooks. For Windows users, a setup script is available. ```bash # Create virtual environment python -m venv .venv # Activate (Windows) .venv\Scripts\activate # Activate (macOS/Linux) source .venv/bin/activate # Install dev dependencies pip install -e ".[dev]" # Install pre-commit hooks pre-commit install ``` ```powershell .\setup_dev.ps1 ``` -------------------------------- ### Install StakeAPI Source: https://github.com/chipadevteam/stakeapi/blob/main/README.md Install the StakeAPI package using pip. This is the first step to using the library. ```bash pip install stakeapi ``` -------------------------------- ### Install StakeAPI from Source Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Clone the repository and install StakeAPI in editable mode for the latest development version. ```bash git clone https://github.com/chipadevteam/StakeAPI.git cd StakeAPI pip install -e . ``` -------------------------------- ### Install StakeAPI with Documentation Dependencies Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Install StakeAPI in editable mode with dependencies required for building documentation. ```bash pip install -e ".[docs]" ``` -------------------------------- ### Quick Start: Get User Balance Source: https://github.com/chipadevteam/stakeapi/blob/main/README.md Initialize the StakeAPI client with your access token and retrieve the user's available and vault balances. Ensure you have an active asyncio event loop. ```python import asyncio from stakeapi import StakeAPI async def main(): # Initialize with access token from stake.com async with StakeAPI(access_token="your_access_token") as client: # Get account balance balance = await client.get_user_balance() print(f"Available balance: {balance['available']}") print(f"Vault balance: {balance['vault']}") asyncio.run(main()) ``` -------------------------------- ### Install Dependencies Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Install project dependencies, including development packages. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Verify StakeAPI Installation Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md A simple Python script to import StakeAPI and print its version to verify the installation. ```python import stakeapi print(f"StakeAPI version: {stakeapi.__version__}") ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Install pre-commit hooks to ensure code quality and style consistency before committing. ```bash pre-commit install ``` -------------------------------- ### Build a Casino Dashboard Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/casino-games.md This example shows how to create a comprehensive casino dashboard by fetching all games and then calculating statistics for categories, providers, and RTP. It requires the `asyncio` and `stakeapi` libraries. ```python import asyncio from stakeapi import StakeAPI async def casino_dashboard(): async with StakeAPI(access_token="your_token") as client: games = await client.get_casino_games() # Category breakdown categories = {} for game in games: categories[game.category] = categories.get(game.category, 0) + 1 print("šŸŽ° CASINO DASHBOARD") print("=" * 50) print(f"\nTotal Games: {len(games)}") print("\nšŸ“‚ Games by Category:") for cat, count in sorted(categories.items(), key=lambda x: x[1], reverse=True): bar = "ā–ˆ" * (count // 5) print(f" {cat:20s} {count:4d} {bar}") # Provider leaderboard providers = {} for game in games: providers[game.provider] = providers.get(game.provider, 0) + 1 print("\nšŸ¢ Top 10 Providers:") for provider, count in sorted(providers.items(), key=lambda x: x[1], reverse=True)[:10]: print(f" {provider:25s} {count:4d} games") # RTP statistics rtps = [g.rtp for g in games if g.rtp] if rtps: print(f"\nšŸ“ˆ RTP Statistics:") print(f" Average: {sum(rtps)/len(rtps):.2f}%") print(f" Highest: {max(rtps):.2f}%") print(f" Lowest: {min(rtps):.2f}%") asyncio.run(casino_dashboard()) ``` -------------------------------- ### Build StakeAPI Docs Locally Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/README.md Navigate to the docs directory and install dependencies using Bundler, then serve the Jekyll site locally. Access the documentation at the specified localhost address. ```bash cd docs bundle install bundle exec jekyll serve ``` -------------------------------- ### Model Serialization Examples Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Demonstrates how to serialize Pydantic models to a dictionary or JSON string, and how to create models from dictionaries. ```python # To dictionary user_dict = user.model_dump() # To JSON string user_json = user.model_dump_json() # From dictionary user = User.from_dict(data) # or user = User(**data) ``` -------------------------------- ### Game Factory Method Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Creates a Game model instance from a dictionary. This example shows how to populate core game details. ```python game = Game.from_dict({ "id": "sweet-bonanza", "name": "Sweet Bonanza", "category": "slots", "provider": "Pragmatic Play", "rtp": 96.48, "volatility": "high" }) ``` -------------------------------- ### Quick Example: StakeAPI Usage Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/index.md Demonstrates basic usage of the StakeAPI client to fetch user balance, casino games, and sports events. Requires an access token and an asyncio event loop. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: # Get your balance balance = await client.get_user_balance() print(f"Available: {balance['available']}") print(f"Vault: {balance['vault']}") # Browse casino games games = await client.get_casino_games(category="slots") for game in games[:5]: print(f"{game.name} by {game.provider} — RTP: {game.rtp}%") # Check sports events events = await client.get_sports_events(sport="football") for event in events[:3]: print(f"{event.home_team} vs {event.away_team}") asyncio.run(main()) ``` -------------------------------- ### StakeAPI Project Structure Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/contributing.md Overview of the StakeAPI project directory structure, including the main package, tests, documentation, and examples. ```tree StakeAPI/ ā”œā”€ā”€ stakeapi/ # Main package │ ā”œā”€ā”€ __init__.py # Package exports │ ā”œā”€ā”€ _version.py # Version info │ ā”œā”€ā”€ auth.py # Authentication │ ā”œā”€ā”€ client.py # Main client │ ā”œā”€ā”€ endpoints.py # API endpoints │ ā”œā”€ā”€ exceptions.py # Custom exceptions │ ā”œā”€ā”€ models.py # Pydantic models │ └── utils.py # Utility functions ā”œā”€ā”€ tests/ # Test suite │ ā”œā”€ā”€ conftest.py # Test fixtures │ ā”œā”€ā”€ test_client.py # Client tests │ ā”œā”€ā”€ test_models.py # Model tests │ └── test_utils.py # Utility tests ā”œā”€ā”€ docs/ # Documentation (GitHub Pages) ā”œā”€ā”€ examples/ # Example scripts ā”œā”€ā”€ pyproject.toml # Project configuration └── Makefile # Dev commands ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/contributing.md Examples of commit messages following the conventional commits specification. ```git feat: add WebSocket support fix: handle token expiration correctly docs: update authentication guide test: add tests for rate limiter refactor: simplify GraphQL request handling ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/troubleshooting.md When using a virtual environment, make sure it is activated before installing packages or running your script. This ensures that dependencies are managed correctly. ```bash # Windows .venv\Scripts\activate # macOS/Linux source .venv/bin/activate ``` -------------------------------- ### Write and Execute Custom GraphQL Query Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/graphql-queries.md Construct and execute a custom GraphQL query with variables. This example fetches user details and a limited number of bets. ```python custom_query = """ query MyCustomQuery($limit: Int!) { user { id name balances { available { amount currency } } bets(first: $limit) { edges { node { id amount payout outcome createdAt game { name } } } } } } """ data = await client._graphql_request( query=custom_query, variables={"limit": 10}, operation_name="MyCustomQuery" ) ``` -------------------------------- ### Example .gitignore for Sensitive Files Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md A sample .gitignore file to prevent sensitive files like .env from being committed to version control. This is crucial for maintaining security. ```gitignore # .gitignore .env *.env config.py secrets.py ``` -------------------------------- ### Upgrade StakeAPI using pip Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/migration.md Use pip to upgrade to the latest version, a specific version, or check the current installed version. ```bash pip install --upgrade stakeapi ``` ```bash pip install stakeapi==0.2.0 ``` ```python python -c "import stakeapi; print(stakeapi.__version__)" ``` -------------------------------- ### Implement a Custom Token Bucket Rate Limiter Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/rate-limiting.md Create a custom rate limiter using the token bucket algorithm for more granular control over request rates. This example uses asyncio for concurrency. ```python import asyncio import time class RateLimiter: """Simple token bucket rate limiter.""" def __init__(self, requests_per_second: int = 10): self.rate = requests_per_second self.tokens = requests_per_second self.last_refill = time.monotonic() self._lock = asyncio.Lock() async def acquire(self): async with self._lock: now = time.monotonic() elapsed = now - self.last_refill self.tokens = min(self.rate, self.tokens + elapsed * self.rate) self.last_refill = now if self.tokens < 1: wait_time = (1 - self.tokens) / self.rate await asyncio.sleep(wait_time) self.tokens = 0 else: self.tokens -= 1 # Usage limiter = RateLimiter(requests_per_second=5) async with StakeAPI(access_token="token") as client: for i in range(100): await limiter.acquire() balance = await client.get_user_balance() print(f"Request {i + 1}: OK") ``` -------------------------------- ### Get User Profile Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/user-account.md Fetches and prints basic user profile information like username, email, verification status, preferred currency, country, and account creation date. Requires an access token. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: user = await client.get_user_profile() print(f"šŸ‘¤ Username: {user.username}") print(f"šŸ“§ Email: {user.email or 'Not set'}") print(f"āœ… Verified: {user.verified}") print(f"šŸ’µ Currency: {user.currency}") print(f"šŸŒ Country: {user.country or 'Not set'}") print(f"šŸ“… Member since: {user.created_at}") asyncio.run(main()) ``` -------------------------------- ### Handle Token Expiration Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/faq.md Implement token expiration handling for long-running scripts. This example shows how to catch AuthenticationError and prompt for a new token. ```python from stakeapi.exceptions import AuthenticationError try: balance = await client.get_user_balance() except AuthenticationError: print("Token expired — refresh it from stake.com") ``` -------------------------------- ### Perform Multiple Concurrent StakeAPI Requests Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/quickstart.md This example demonstrates how to leverage `asyncio.gather` to execute multiple StakeAPI requests concurrently, significantly improving performance for I/O-bound operations. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: # Run 3 requests at the same time! balance, games, events = await asyncio.gather( client.get_user_balance(), client.get_casino_games(), client.get_sports_events(), ) print(f"Balance: {balance}") print(f"Games: {len(games)}") print(f"Events: {len(events)}") asyncio.run(main()) ``` -------------------------------- ### Get User Profile with StakeAPI Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/examples.md Retrieves and prints basic user profile information such as username, verification status, default currency, and creation date. An access token is required. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: user = await client.get_user_profile() print(f"Username: {user.username}") print(f"Verified: {user.verified}") print(f"Currency: {user.currency}") print(f"Member since: {user.created_at}") asyncio.run(main()) ``` -------------------------------- ### Get Casino Games with Filtering Source: https://context7.com/chipadevteam/stakeapi/llms.txt Fetch all available casino games or filter them by category. Demonstrates in-memory filtering by provider, RTP, and minimum bet. Inspects individual game details. ```python import asyncio from decimal import Decimal from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_access_token") as client: # All games all_games = await client.get_casino_games() # Filtered by category slots = await client.get_casino_games(category="slots") print(f"Total slot games: {len(slots)}") # Filter by provider in-memory pragmatic = [g for g in all_games if "pragmatic" in g.provider.lower()] print(f"Pragmatic Play games: {len(pragmatic)}") # Filter high-RTP games high_rtp = [g for g in all_games if g.rtp and g.rtp > 96.0] print(f"High RTP games (>96%): {len(high_rtp)}") # Filter by low minimum bet low_stakes = [g for g in all_games if g.min_bet <= Decimal("0.10")] print(f"Low min-bet games: {len(low_stakes)}") # Inspect a specific game game = slots[0] print(f"\nGame: {game.name}") print(f" Provider: {game.provider}") print(f" Min bet: {game.min_bet} / Max bet: {game.max_bet}") print(f" RTP: {game.rtp}% Volatility: {game.volatility}") asyncio.run(main()) ``` -------------------------------- ### Get All Casino Games Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Retrieve a list of all available casino games. No specific setup is required beyond having an authenticated client. ```python games = await client.get_casino_games() ``` -------------------------------- ### Get Sports Events with Filtering Source: https://context7.com/chipadevteam/stakeapi/llms.txt Fetch upcoming and live sports events, optionally filtering by sport. Displays event details including teams, league, start time, status, and odds. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_access_token") as client: events = await client.get_sports_events(sport="football") print(f"Found {len(events)} football events") live_events = [e for e in events if e.live] print(f"Live now: {len(live_events)}") for event in events[:3]: print(f"\n{event.home_team} vs {event.away_team}") print(f" League: {event.league}") print(f" Starts: {event.start_time.strftime('%Y-%m-%d %H:%M UTC')}") print(f" Status: {event.status}") if event.odds: home_odd = event.odds.get("home", "N/A") away_odd = event.odds.get("away", "N/A") draw_odd = event.odds.get("draw", "N/A") print(f" Odds — Home: {home_odd} Draw: {draw_odd} Away: {away_odd}") asyncio.run(main()) ``` -------------------------------- ### Fetch Sports Data Using GraphQL Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/sports-betting.md Retrieves detailed sports event data, including competitors, league information, start times, markets, and odds, using the GraphQL API. Requires an access token and the `GraphQLQueries` class. This example filters events by sport slug and limits the results. ```python from stakeapi.endpoints import GraphQLQueries async with StakeAPI(access_token="your_token") as client: data = await client._graphql_request( query=GraphQLQueries.SPORTS_EVENTS, variables={ "first": 50, "sportSlug": "football" }, operation_name="SportsEvents" ) for edge in data.get("sportsEvents", {}).get("edges", []): event = edge["node"] competitors = [c["name"] for c in event.get("competitors", [])] print(f"{ ' vs '.join(competitors)}") print(f" League: {event['league']['name']}") print(f" Start: {event['startTime']}") # Show markets and odds for market in event.get("markets", []): print(f" Market: {market['name']}") for outcome in market.get("outcomes", []): print(f" {outcome['name']}: {outcome['odds']}") ``` -------------------------------- ### Make Your First StakeAPI Call Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/quickstart.md This script demonstrates how to initialize the StakeAPI client, fetch user balance, browse casino games, and check sports events. Replace 'your_access_token_here' with your actual token. ```python import asyncio from stakeapi import StakeAPI async def main(): # Replace with your actual access token async with StakeAPI(access_token="your_access_token_here") as client: # 1. Get your balance balance = await client.get_user_balance() print("šŸ’° Your Balance:") for currency, amount in balance["available"].items(): if amount > 0: print(f" {currency.upper()}: {amount}") # 2. Browse casino games games = await client.get_casino_games(category="slots") print(f"\nšŸŽ° Found {len(games)} slot games!") for game in games[:5]: print(f" - {game.name} by {game.provider}") # 3. Check sports events events = await client.get_sports_events(sport="football") print(f"\n⚽ Found {len(events)} football events!") for event in events[:3]: print(f" - {event.home_team} vs {event.away_team}") asyncio.run(main()) ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Create a Python virtual environment for the project. ```bash python -m venv venv ``` -------------------------------- ### Get All Sports Events Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Retrieve a list of all upcoming sports events. This call does not require any parameters. ```python events = await client.get_sports_events() ``` -------------------------------- ### Initialize StakeAPI Client Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Instantiate the StakeAPI client with optional authentication and configuration parameters. ```python client = StakeAPI( access_token="your_token" ) ``` ```python client = StakeAPI( access_token="your_token", session_cookie="your_session", timeout=60, rate_limit=5, ) ``` -------------------------------- ### Get Auth Headers Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/auth-manager.md Retrieve authentication headers, including the X-Access-Token if an access token is set. ```python auth = AuthManager(access_token="token123") headers = await auth.get_auth_headers() # {"X-Access-Token": "token123"} ``` -------------------------------- ### Run Linting and Formatting Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Apply code formatting with Black, sort imports with isort, and check for linting errors with flake8. ```bash black . && isort . && flake8 ``` -------------------------------- ### Get Casino Games by Category Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Filter and retrieve casino games belonging to a specific category, such as 'slots'. ```python slots = await client.get_casino_games(category="slots") ``` -------------------------------- ### Migrate Client Initialization from Pre-release to v0.1.0 Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/migration.md Adjust how the client is initialized, changing the class name and the authentication parameter. ```python # Old client = Client(api_key="your_key") # New (v0.1.0+) client = StakeAPI(access_token="your_token") ``` -------------------------------- ### Initialize StakeAPI with .env Credentials Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md Load credentials from a .env file using python-dotenv and initialize the StakeAPI client. This approach centralizes configuration and secrets. ```python import os from dotenv import load_dotenv from stakeapi import StakeAPI load_dotenv() token = os.getenv("STAKE_ACCESS_TOKEN") session = os.getenv("STAKE_SESSION_COOKIE") async with StakeAPI(access_token=token, session_cookie=session) as client: balance = await client.get_user_balance() ``` -------------------------------- ### Get Sports Events by Sport Type Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Filter and retrieve sports events for a specific sport, like 'football'. ```python football = await client.get_sports_events(sport="football") ``` -------------------------------- ### Import StakeAPI Client Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Import the main StakeAPI client class from the library. ```python from stakeapi import StakeAPI ``` -------------------------------- ### Get Specific Game Details Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Fetch detailed information for a single casino game using its unique identifier. ```python game = await client.get_game_details("game_123") print(f"{game.name} — RTP: {game.rtp}%") ``` -------------------------------- ### Fetch and Display Full Account Summary Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/user-account.md Asynchronously fetches user profile and balance data in parallel and prints a formatted summary to the console. Requires the StakeAPI client and asyncio. ```python async def full_account_summary(): async with StakeAPI(access_token="your_token") as client: # Fetch both in parallel import asyncio user, balance = await asyncio.gather( client.get_user_profile(), client.get_user_balance() ) print(f"ā•”{'═' * 48}ā•—") print(f"ā•‘ ACCOUNT SUMMARY ā•‘") print(f"ā• {'═' * 48}ā•£") print(f"ā•‘ User: {user.username:40s} ā•‘") print(f"ā•‘ Verified: {'āœ… Yes' if user.verified else 'āŒ No':38s} ā•‘") print(f"ā•‘ Currency: {user.currency:38s} ā•‘") print(f"ā• {'═' * 48}ā•£") available = {k: v for k, v in balance["available"].items() if v > 0} vault = {k: v for k, v in balance["vault"].items() if v > 0} print(f"ā•‘ Available Balances: {len(available):27d} ā•‘") for cur, amt in available.items(): print(f"ā•‘ {cur.upper():6s} {amt:>38.8f} ā•‘") print(f"ā•‘ Vault Balances: {len(vault):31d} ā•‘") for cur, amt in vault.items(): print(f"ā•‘ {cur.upper():6s} {amt:>38.8f} ā•‘") print(f"ā•š{'═' * 48}ā•") asyncio.run(full_account_summary()) ``` -------------------------------- ### Initialize StakeAPI Client Correctly Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/troubleshooting.md When initializing the StakeAPI client, pass the access token directly. Do not include the header name 'x-access-token' in the token string. ```python # āœ… Correct client = StakeAPI(access_token="your_actual_token_value") # āŒ Wrong — don't include the header name client = StakeAPI(access_token="x-access-token: token_value") ``` -------------------------------- ### Get Specific Game Details Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/casino-games.md Fetches detailed information for a single game using its ID. Requires an access token. ```python async with StakeAPI(access_token="your_token") as client: game = await client.get_game_details("game_id_here") print(f"Name: {game.name}") print(f"Provider: {game.provider}") print(f"Category: {game.category}") print(f"Description: {game.description}") print(f"Min Bet: ${game.min_bet}") print(f"Max Bet: ${game.max_bet}") print(f"RTP: {game.rtp}%") print(f"Volatility: {game.volatility}") print(f"Features: {', '.join(game.features)}") ``` -------------------------------- ### StakeAPI Client Initialization Source: https://context7.com/chipadevteam/stakeapi/llms.txt Initializes the StakeAPI client with authentication and configuration options. It should be used as an async context manager. ```APIDOC ## StakeAPI Client Initialization The `StakeAPI` class is the main entry point. It accepts an `access_token` (extracted from browser DevTools as the `x-access-token` header), an optional `session_cookie`, a `cf_clearance` Cloudflare cookie, and tuning parameters for timeout and rate limiting. Use it as an async context manager to ensure the underlying `aiohttp` session is properly opened and closed. ```python import asyncio import os from stakeapi import StakeAPI from stakeapi.exceptions import AuthenticationError, RateLimitError, StakeAPIError async def main(): async with StakeAPI( access_token=os.getenv("STAKE_ACCESS_TOKEN"), cf_clearance=os.getenv("STAKE_CF_CLEARANCE"), # Required to bypass Cloudflare user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...", timeout=30, rate_limit=10, # max requests per second ) as client: try: balance = await client.get_user_balance() print(balance) except AuthenticationError: print("Invalid or expired access token.") except RateLimitError: print("Rate limit hit — slow down requests.") except StakeAPIError as e: print(f"API error: {e}") asyncio.run(main()) ``` ``` -------------------------------- ### Create and Activate venv (Windows) Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Steps to create and activate a Python virtual environment using venv on Windows. ```bash # Create virtual environment python -m venv .venv # Activate (Windows) .venv\Scripts\activate ``` -------------------------------- ### Get User Profile Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Fetch the current authenticated user's profile information, including username and verification status. ```python user = await client.get_user_profile() print(f"Username: {user.username}") print(f"Verified: {user.verified}") ``` -------------------------------- ### SportEvent Model Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Represents a sports event or match, including sport, league, teams, start time, status, and odds. ```APIDOC ## SportEvent Model Represents a sports event/match. ```python class SportEvent(BaseModel): id: str sport: str league: str home_team: str away_team: str start_time: datetime status: str odds: Dict[str, float] = {} live: bool = False ``` ### Fields | Field | Type | Default | Description | |:------|:-----|:--------|:------------| | `id` | `str` | — | Unique event ID | | `sport` | `str` | — | Sport type | | `league` | `str` | — | League/competition name | | `home_team` | `str` | — | Home team name | | `away_team` | `str` | — | Away team name | | `start_time` | `datetime` | — | Scheduled start time | | `status` | `str` | — | Event status | | `odds` | `Dict[str, float]` | `{}` | Market odds dictionary | | `live` | `bool` | `False` | Whether event is currently live | ### Odds Format ```python event.odds = { "home": 1.85, "draw": 3.50, "away": 4.20 } ``` ``` -------------------------------- ### Initialize StakeAPI Client Source: https://context7.com/chipadevteam/stakeapi/llms.txt Initialize the StakeAPI client as an async context manager. Requires an access token and optionally Cloudflare cookies. Configure timeout and rate limiting as needed. ```python import asyncio import os from stakeapi import StakeAPI from stakeapi.exceptions import AuthenticationError, RateLimitError, StakeAPIError async def main(): async with StakeAPI( access_token=os.getenv("STAKE_ACCESS_TOKEN"), cf_clearance=os.getenv("STAKE_CF_CLEARANCE"), # Required to bypass Cloudflare user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...", timeout=30, rate_limit=10, # max requests per second ) as client: try: balance = await client.get_user_balance() print(balance) except AuthenticationError: print("Invalid or expired access token.") except RateLimitError: print("Rate limit hit — slow down requests.") except StakeAPIError as e: print(f"API error: {e}") asyncio.run(main()) ``` -------------------------------- ### Extract Access Token from cURL Source: https://github.com/chipadevteam/stakeapi/blob/main/README.md Example of an access token header extracted from a cURL command. This token is required for authenticating with the StakeAPI. ```bash -H "x-access-token: your_token_here" ``` -------------------------------- ### Import StakeAPI Utilities Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/utilities.md Import necessary utility functions from the stakeapi.utils module. ```python from stakeapi.utils import ( validate_api_key, safe_decimal, parse_datetime, format_currency, calculate_win_rate, validate_bet_amount, sanitize_game_name, ) ``` -------------------------------- ### Create and Activate venv (macOS/Linux) Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Steps to create and activate a Python virtual environment using venv on macOS or Linux. ```bash # Create virtual environment python -m venv .venv # Activate (macOS/Linux) source .venv/bin/activate ``` -------------------------------- ### SportEvent Odds Format Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Example of how to format the odds for a sports event. The 'odds' field is a dictionary mapping outcome names to their respective decimal odds. ```python event.odds = { "home": 1.85, "draw": 3.50, "away": 4.20 } ``` -------------------------------- ### Clone the StakeAPI Repository Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/contributing.md Clone the StakeAPI repository and navigate into the project directory. ```bash git clone https://github.com/chipadevteam/StakeAPI.git cd StakeAPI ``` -------------------------------- ### Get User Balance Source: https://context7.com/chipadevteam/stakeapi/llms.txt Retrieve the authenticated user's available and vault balances for all currencies. Handles potential authentication or rate limit errors. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_access_token") as client: balance = await client.get_user_balance() print("Available balances:") for currency, amount in balance["available"].items(): if amount > 0: print(f" {currency.upper()}: {amount}") print("Vault balances:") for currency, amount in balance["vault"].items(): if amount > 0: print(f" {currency.upper()}: {amount}") # Expected output: # Available balances: # BTC: 0.00152 # USD: 45.30 # Vault balances: # BTC: 0.01 asyncio.run(main()) ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Create a new conda environment named 'stakeapi' with Python 3.11 and activate it. ```bash conda create -n stakeapi python=3.11 conda activate stakeapi ``` -------------------------------- ### SportEvent Model Definition Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Defines the structure for a sports event, including sport, league, teams, start time, and status. Odds are stored as a dictionary. ```python class SportEvent(BaseModel): id: str sport: str league: str home_team: str away_team: str start_time: datetime status: str odds: Dict[str, float] = {} live: bool = False ``` -------------------------------- ### Build a Sports Dashboard with StakeAPI Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/sports-betting.md Aggregates sports data to create a dashboard showing total events, events by sport, live vs upcoming counts, and top leagues. Requires an access token. ```python import asyncio from collections import Counter from stakeapi import StakeAPI async def sports_dashboard(): async with StakeAPI(access_token="your_token") as client: events = await client.get_sports_events() print("šŸˆ SPORTS DASHBOARD") print("=" * 60) print(f"Total Events: {len(events)}") # Events by sport sports = Counter(e.sport for e in events) print("\nšŸ“Š Events by Sport:") for sport, count in sports.most_common(): bar = "ā–ˆ" * (count // 2) print(f" {sport:20s} {count:4d} {bar}") # Live vs upcoming live = sum(1 for e in events if e.live) upcoming = len(events) - live print(f"\nšŸ”“ Live: {live}") print(f"ā³ Upcoming: {upcoming}") # Top leagues leagues = Counter(e.league for e in events) print("\nšŸ† Top 10 Leagues:") for league, count in leagues.most_common(10): print(f" {league:30s} {count:4d} events") asyncio.run(sports_dashboard()) ``` -------------------------------- ### Model Validation Example Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/models.md Illustrates Pydantic's automatic data type validation. Providing incorrect types for model fields will raise a validation error. ```python # This will raise a validation error game = Game(id=123, name=456) # id and name must be strings ``` -------------------------------- ### Check User Balance with StakeAPI Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/resources/examples.md Demonstrates how to fetch and display a user's available balance for different currencies. Requires an access token. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: balance = await client.get_user_balance() print("Available:") for currency, amount in balance["available"].items(): if amount > 0: print(f" {currency.upper()}: {amount}") asyncio.run(main()) ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Activate the Python virtual environment. Use the appropriate command for your operating system. ```bash venv\Scripts\activate ``` ```bash source venv/bin/activate ``` -------------------------------- ### Get All Casino Games Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/casino-games.md Fetches all available casino games from Stake.com. Requires an access token. Prints the total count and details of the first 10 games. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: games = await client.get_casino_games() print(f"Total games available: {len(games)}") for game in games[:10]: print(f"šŸŽ° {game.name}") print(f" Provider: {game.provider}") print(f" Category: {game.category}") print(f" Min Bet: {game.min_bet} | Max Bet: {game.max_bet}") if game.rtp: print(f" RTP: {game.rtp}%") print() asyncio.run(main()) ``` -------------------------------- ### Get User Balance Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Retrieve the user's account balance across all currencies using a GraphQL query. The response includes 'available' and 'vault' balances. ```python balance = await client.get_user_balance() for currency, amount in balance["available"].items(): if amount > 0: print(f"{currency.upper()}: {amount}") ``` -------------------------------- ### Initialize StakeAPI with Access Token Only Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md Instantiate the StakeAPI client using only an access token. This is the simplest authentication method and sufficient for most API interactions. ```python async with StakeAPI(access_token="your_token") as client: # Make API calls pass ``` -------------------------------- ### Get User Profile Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/user-account.md Retrieves the current user's profile information, including username, email, verification status, currency, country, and account creation date. ```APIDOC ## Get User Profile ### Description Retrieves the current user's profile information. ### Method GET (Implicit via SDK method) ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: user = await client.get_user_profile() print(f"šŸ‘¤ Username: {user.username}") print(f"šŸ“§ Email: {user.email or 'Not set'}") print(f"āœ… Verified: {user.verified}") print(f"šŸ’µ Currency: {user.currency}") print(f"šŸŒ Country: {user.country or 'Not set'}") print(f"šŸ“… Member since: {user.created_at}") asyncio.run(main()) ``` ### Response #### Success Response (200) - **id** (str) - Unique user ID - **username** (str) - Display name - **email** (Optional[str]) - Email address - **verified** (bool) - Email verification status - **created_at** (datetime) - Account creation date - **country** (Optional[str]) - User's country - **currency** (str) - Preferred currency #### Response Example ```json { "id": "user_id_123", "username": "example_user", "email": "user@example.com", "verified": true, "created_at": "2023-01-01T10:00:00Z", "country": "US", "currency": "USD" } ``` ``` -------------------------------- ### Initialize StakeAPI with Access Token and Session Cookie Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md Initialize the StakeAPI client with both an access token and a session cookie for enhanced compatibility. This method provides the most robust authentication. ```python async with StakeAPI( access_token="your_token", session_cookie="your_session_cookie" ) as client: # Make API calls pass ``` -------------------------------- ### Add StakeAPI with Poetry Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/installation.md Use Poetry to add StakeAPI as a dependency to your project. ```bash poetry add stakeapi ``` -------------------------------- ### Fetch Sports Events Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/graphql-queries.md Retrieve sports events using `GraphQLQueries.SPORTS_EVENTS`. Parameters include `first` for the number of events and `sportSlug` for filtering by sport. This example fetches football events. ```python data = await client._graphql_request( query=GraphQLQueries.SPORTS_EVENTS, variables={ "first": 30, "sportSlug": "football" }, operation_name="SportsEvents" ) for edge in data["sportsEvents"]["edges"]: event = edge["node"] print(f"{event['name']}") for market in event.get("markets", []): for outcome in market.get("outcomes", []): print(f" {outcome['name']}: {outcome['odds']}") ``` -------------------------------- ### Handle Token Expiration with StakeAPI Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md Catch AuthenticationError when a token expires or is invalidated during an API call. This example shows how to gracefully handle such errors by printing a message and optionally re-authenticating. ```python from stakeapi import StakeAPI from stakeapi.exceptions import AuthenticationError async with StakeAPI(access_token="your_token") as client: try: balance = await client.get_user_balance() except AuthenticationError: print("Token expired! Please get a new token from stake.com") # Optionally: re-authenticate or notify user ``` -------------------------------- ### Create Feature Branch Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Create a new branch for developing a feature. Replace 'your-feature-name' with a descriptive name. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Get Specific Game Details by ID Source: https://context7.com/chipadevteam/stakeapi/llms.txt Retrieve comprehensive details for a single casino game using its unique ID. Handles potential API errors or if the game is not found. ```python import asyncio from stakeapi import StakeAPI from stakeapi.exceptions import StakeAPIError async def main(): async with StakeAPI(access_token="your_access_token") as client: try: game = await client.get_game_details(game_id="gates-of-olympus") print(f"Name: {game.name}") print(f"Provider: {game.provider}") print(f"Category: {game.category}") print(f"RTP: {game.rtp}%") print(f"Min bet: {game.min_bet} Max bet: {game.max_bet}") print(f"Features: {', '.join(game.features)}") except StakeAPIError as e: print(f"Game not found or API error: {e}") asyncio.run(main()) ``` -------------------------------- ### Clone Repository Source: https://github.com/chipadevteam/stakeapi/blob/main/CONTRIBUTING.md Clone the StakeAPI repository to your local machine. ```bash git clone https://github.com/chipadevteam/StakeAPI.git ``` -------------------------------- ### Get User Profile Source: https://context7.com/chipadevteam/stakeapi/llms.txt Fetch the current user's profile information using the REST API. Returns a validated `User` Pydantic model. Catches authentication errors. ```python import asyncio from stakeapi import StakeAPI from stakeapi.exceptions import AuthenticationError async def main(): async with StakeAPI(access_token="your_access_token") as client: try: user = await client.get_user_profile() print(f"Username: {user.username}") print(f"ID: {user.id}") print(f"Verified: {user.verified}") print(f"Country: {user.country}") print(f"Default currency: {user.currency}") print(f"Member since: {user.created_at.strftime('%Y-%m-%d')}") except AuthenticationError: print("Authentication failed.") asyncio.run(main()) ``` -------------------------------- ### StakeAPI Constructor Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/api-reference/client.md Initializes the StakeAPI client. You can authenticate using an access token or a session cookie. Optional parameters allow for custom base URLs, request timeouts, and rate limiting. ```APIDOC ## Constructor ```python StakeAPI( access_token: Optional[str] = None, session_cookie: Optional[str] = None, base_url: str = "https://stake.com", timeout: int = 30, rate_limit: int = 10, ) ``` ### Parameters | Parameter | Type | Default | Description | |:----------|:-----|:--------|:------------| | `access_token` | `Optional[str]` | `None` | Your Stake.com access token (`x-access-token` header) | | `session_cookie` | `Optional[str]` | `None` | Session cookie for authentication | | `base_url` | `str` | `"https://stake.com"` | Base URL for the API | | `timeout` | `int` | `30` | Request timeout in seconds | | `rate_limit` | `int` | `10` | Maximum requests per second | ### Example ```python # Basic usage client = StakeAPI(access_token="your_token") # Full configuration client = StakeAPI( access_token="your_token", session_cookie="your_session", timeout=60, rate_limit=5, ) ``` ``` -------------------------------- ### Combine WebSocket with REST API for Live Updates Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/websockets.md Fetch initial user balance using the REST API and then switch to WebSocket for real-time balance updates. Requires a StakeAPI client. ```python async def live_balance_tracker(): """Combine REST for initial state and WebSocket for live updates.""" async with StakeAPI(access_token="your_token") as client: # Get initial balance via REST balance = await client.get_user_balance() print("Initial balance:", balance) # Then switch to WebSocket for live updates ws_client = StakeWebSocket(access_token="your_token") await ws_client.subscribe("user:balances") await ws_client.connect() ``` -------------------------------- ### Fetch Paginated Casino Games Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/graphql-queries.md Retrieve a paginated list of casino games using `GraphQLQueries.CASINO_GAMES`. Specify `first` for the number of items and `categorySlug` to filter by category. This example fetches slots. ```python data = await client._graphql_request( query=GraphQLQueries.CASINO_GAMES, variables={ "first": 50, "categorySlug": "slots" }, operation_name="CasinoGames" ) games = data["casinoGames"]["edges"] for edge in games: game = edge["node"] print(f"{game['name']} by {game['provider']['name']}") # Check for more pages page_info = data["casinoGames"]["pageInfo"] if page_info["hasNextPage"]: print(f"More games available after cursor: {page_info['endCursor']}") ``` -------------------------------- ### Load Stake Credentials from .env File Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/getting-started/authentication.md Configure Stake API authentication by storing your access token and session cookie in a .env file. Ensure this file is added to your .gitignore to prevent accidental commits. ```env STAKE_ACCESS_TOKEN=your_access_token_here STAKE_SESSION_COOKIE=your_session_cookie_here ``` -------------------------------- ### SportEvent Model Definition Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/sports-betting.md Defines the structure of a sports event object, including details like ID, sport, league, teams, start time, status, odds, and live status. ```python class SportEvent(BaseModel): id: str # Unique identifier sport: str # Sport type league: str # League/competition name home_team: str # Home team name away_team: str # Away team name start_time: datetime # Event start time status: str # Event status odds: Dict[str, float] # Market odds live: bool # Whether currently live ``` -------------------------------- ### Configure StakeAPI Client Rate Limit Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/rate-limiting.md Set the rate limit when initializing the StakeAPI client. Defaults to 10 requests per second. ```python from stakeapi import StakeAPI # Default: 10 requests per second client = StakeAPI(access_token="token", rate_limit=10) # Conservative: 5 requests per second client = StakeAPI(access_token="token", rate_limit=5) # Aggressive: 20 requests per second (use with caution!) client = StakeAPI(access_token="token", rate_limit=20) ``` -------------------------------- ### Fetch User Balances with Built-in Query Source: https://github.com/chipadevteam/stakeapi/blob/main/docs/guides/graphql-queries.md Utilize the pre-built `GraphQLQueries.USER_BALANCES` for fetching user balance information. This requires an active `StakeAPI` client. ```python from stakeapi.endpoints import GraphQLQueries async with StakeAPI(access_token="your_token") as client: data = await client._graphql_request( query=GraphQLQueries.USER_BALANCES, operation_name="UserBalances" ) for balance in data["user"]["balances"]["available"]: print(f"{balance['currency']}: {balance['amount']}") ```