### Set Up Development Environment Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Set up a Python virtual environment, activate it, install development dependencies, and install pre-commit hooks. For Windows users, a setup script is also 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 from Source Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Install the latest development version of StakeAPI by cloning the repository and installing from source. ```bash git clone https://github.com/chipadevteam/StakeAPI.git cd StakeAPI pip install -e . ``` -------------------------------- ### Quick Install StakeAPI Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Use this command for the simplest installation of StakeAPI and its core dependencies. ```bash pip install stakeapi ``` -------------------------------- ### Install StakeAPI Source: https://chipadevteam.github.io/StakeAPI/resources/faq Use pip to install the library in your Python environment. ```bash pip install stakeapi ``` -------------------------------- ### Install StakeAPI with Documentation Dependencies Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Install StakeAPI along with dependencies required for building and managing documentation. ```bash pip install -e ".[docs]" ``` -------------------------------- ### Install and Activate Environment Source: https://chipadevteam.github.io/StakeAPI/resources/troubleshooting Commands for installing the package and activating virtual environments on different operating systems. ```bash pip install stakeapi ``` ```bash # Windows .venv\Scripts\activate # macOS/Linux source .venv/bin/activate ``` -------------------------------- ### Install StakeAPI with Development Dependencies Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Install StakeAPI with additional tools for contributors and developers, including testing and linting frameworks. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Verify StakeAPI Installation Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Check if StakeAPI is installed correctly by importing it and printing its version. ```python import stakeapi print(f"StakeAPI version: {stakeapi.__version__}") ``` -------------------------------- ### Dynamic Path Parameters Example Source: https://chipadevteam.github.io/StakeAPI/api-reference/endpoints Demonstrates how to format endpoints with dynamic path parameters. ```APIDOC ## Dynamic Path Parameters ### Description Some endpoints have path parameters that need to be formatted. ### Example: Game Details ```python endpoint = Endpoints.CASINO_GAME_DETAILS.format(game_id="sweet-bonanza") # Result: /api/v1/casino/games/sweet-bonanza ``` ### Example: Bet Details ```python endpoint = Endpoints.BET_DETAILS.format(bet_id="bet_123") # Result: /api/v1/bets/bet_123 ``` ``` -------------------------------- ### Python: Combine WebSocket with REST API Source: https://chipadevteam.github.io/StakeAPI/guides/websockets Example demonstrating how to use StakeAPI's REST client to fetch initial user balance and then switch to the StakeWebSocket client for continuous, live updates. ```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() ``` -------------------------------- ### Balance Response Format Example Source: https://chipadevteam.github.io/StakeAPI/guides/user-account Illustrates the dictionary structure returned by the `get_user_balance()` method, detailing 'available' and 'vault' balances for various cryptocurrencies. ```json { "available": { "btc": 0.00150000, "eth": 0.05000000, "ltc": 1.50000000, "doge": 500.00000000, "usd": 100.00, "eur": 0.00, # ... more currencies }, "vault": { "btc": 0.01000000, "eth": 0.00000000, # ... more currencies } } ``` -------------------------------- ### Upgrade StakeAPI via pip Source: https://chipadevteam.github.io/StakeAPI/resources/migration Commands to update the library or verify the installed version. ```bash # Upgrade to latest pip install --upgrade stakeapi # Upgrade to specific version pip install stakeapi==0.2.0 # Check current version python -c "import stakeapi; print(stakeapi.__version__)" ``` -------------------------------- ### Get User Profile with StakeAPI Source: https://chipadevteam.github.io/StakeAPI/resources/examples Fetches and displays basic user profile information including username, verification status, and account currency. ```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 User Profile Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Fetch the current 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}") ``` -------------------------------- ### Set Sport Event Odds Source: https://chipadevteam.github.io/StakeAPI/api-reference/models Example of how to populate the `odds` dictionary for a SportEvent. The keys represent the market (e.g., 'home', 'draw', 'away') and values are the corresponding odds. ```python event.odds = { "home": 1.85, "draw": 3.50, "away": 4.20 } ``` -------------------------------- ### Get User Profile Information Source: https://chipadevteam.github.io/StakeAPI/guides/user-account Retrieves and prints details of the authenticated user, including 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()) ``` -------------------------------- ### Implement Response Caching Source: https://chipadevteam.github.io/StakeAPI/guides/performance Cache API responses to avoid redundant fetches for data that changes infrequently. This example demonstrates caching with different Time-To-Live (TTL) values for games and user balance. ```python import time from functools import lru_cache class CachedStakeAPI: def __init__(self, client): self.client = client self._cache = {} self._cache_ttl = {} async def get_cached(self, key, fetcher, ttl=60): """Get cached result or fetch fresh data.""" now = time.time() if key in self._cache and now < self._cache_ttl.get(key, 0): return self._cache[key] result = await fetcher() self._cache[key] = result self._cache_ttl[key] = now + ttl return result async def get_games_cached(self, category=None): """Casino games change infrequently β€” cache for 5 minutes.""" key = f"games:{category}" return await self.get_cached( key, lambda: self.client.get_casino_games(category=category), ttl=300 ) async def get_balance_cached(self): """Balance changes often β€” cache for 10 seconds.""" return await self.get_cached( "balance", self.client.get_user_balance, ttl=10 ) ``` -------------------------------- ### Get All Upcoming Sports Events Source: https://chipadevteam.github.io/StakeAPI/guides/sports-betting Fetches all upcoming sports events and prints details for the first 10. Requires an access token and the `stakeapi` library. Handles event details including teams, sport, league, start time, status, and odds. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: # Get all upcoming events events = await client.get_sports_events() print(f"Total events: {len(events)}") for event in events[:10]: print(f"\n⚽ {event.home_team} vs {event.away_team}") print(f" Sport: {event.sport}") print(f" League: {event.league}") print(f" Start: {event.start_time}") print(f" Status: {event.status}") print(f" Live: {'πŸ”΄ LIVE' if event.live else '⏳ Upcoming'}") if event.odds: print(f" Odds:") for market, odds in event.odds.items(): print(f" {market}: {odds}") asyncio.run(main()) ``` -------------------------------- ### Initialize Client for v0.1.0 Source: https://chipadevteam.github.io/StakeAPI/resources/migration The client class and authentication parameter name were updated. ```python # Old client = Client(api_key="your_key") # New (v0.1.0+) client = StakeAPI(access_token="your_token") ``` -------------------------------- ### Initialize StakeAPI and Fetch Data Source: https://chipadevteam.github.io/StakeAPI/getting-started/quickstart Demonstrates basic usage of the StakeAPI client to retrieve user balance, casino games, and sports events. ```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()) ``` -------------------------------- ### Conventional Commit Message Examples Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Examples of commit messages following the conventional commits specification for different types of changes. ```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 ``` -------------------------------- ### Manage Asynchronous Patterns Source: https://chipadevteam.github.io/StakeAPI/getting-started/quickstart Illustrates correct context management and manual session handling versus common pitfalls. ```python # βœ… CORRECT β€” Using async context manager async with StakeAPI(access_token=token) as client: result = await client.get_user_balance() # βœ… CORRECT β€” Manual session management client = StakeAPI(access_token=token) await client._create_session() try: result = await client.get_user_balance() finally: await client.close() # ❌ WRONG β€” Forgetting to await async with StakeAPI(access_token=token) as client: result = client.get_user_balance() # This returns a coroutine, not the result! ``` -------------------------------- ### Get Session Cookies Source: https://chipadevteam.github.io/StakeAPI/api-reference/auth-manager Retrieve the session cookie if it has been set. ```python def get_cookies(self) -> Dict[str, str] ``` -------------------------------- ### Create and Activate conda Virtual Environment Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Set up a virtual environment named 'stakeapi' with Python 3.11 using conda. ```bash conda create -n stakeapi python=3.11 conda activate stakeapi pip install stakeapi ``` -------------------------------- ### Fetch User Profile and Balance in Python Source: https://chipadevteam.github.io/StakeAPI/guides/user-account This snippet demonstrates how to fetch both user profile and balance data concurrently using asyncio.gather. Ensure you have your access token ready. ```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()) ``` -------------------------------- ### Get Bet History Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieves the user's bet history with an optional limit. ```APIDOC ## GET /api/v1/bets ### Description Get the user’s bet history. ### Method GET ### Endpoint /api/v1/bets ### Query Parameters - **limit** (int) - Optional - Maximum number of bets to return. Defaults to 50. ### Response #### Success Response (200) - **bets** (List[Bet]) - List of bet objects ### Response Example ```json [ { "id": "123", "amount": 10.50, "status": "won" } ] ``` ### Request Example ```python bets = await client.get_bet_history(limit=20) for bet in bets: print(f"{bet.id}: {bet.amount} β†’ {bet.status}") ``` ``` -------------------------------- ### Get Sports Events by Sport Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieve a list of sports events filtered by a specific sport, such as 'football'. ```python football = await client.get_sports_events(sport="football") ``` -------------------------------- ### Get Casino Games by Category Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieve a list of casino games filtered by a specific category, such as 'slots'. ```python slots = await client.get_casino_games(category="slots") ``` -------------------------------- ### Create and Activate venv Virtual Environment Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Set up a virtual environment using Python's built-in venv module to manage project dependencies. ```bash # Create virtual environment python -m venv .venv # Activate (Windows) .venv\Scripts\activate # Activate (macOS/Linux) source .venv/bin/activate # Install StakeAPI pip install stakeapi ``` -------------------------------- ### Initialize StakeAPI Client Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Instantiate the StakeAPI client with basic or full configuration options, including access token, session cookie, base URL, timeout, and rate limiting. ```python client = StakeAPI(access_token="your_token") ``` ```python client = StakeAPI( access_token="your_token", session_cookie="your_session", timeout=60, rate_limit=5, ) ``` -------------------------------- ### Get Specific Game Details Source: https://chipadevteam.github.io/StakeAPI/guides/casino-games Retrieves comprehensive metadata for a single game using its unique identifier. ```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)}") ``` -------------------------------- ### Initialize and Use StakeAPI Source: https://chipadevteam.github.io/StakeAPI Demonstrates basic usage including authentication, balance retrieval, and fetching casino or sports data. Requires a valid Stake.com access token. ```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()) ``` -------------------------------- ### Get Authentication Headers Source: https://chipadevteam.github.io/StakeAPI/api-reference/auth-manager Retrieve HTTP headers for authentication, including the X-Access-Token if set. This method is asynchronous. ```python auth = AuthManager(access_token="token123") headers = await auth.get_auth_headers() # {"X-Access-Token": "token123"} ``` -------------------------------- ### Create Game Instance from Dictionary Source: https://chipadevteam.github.io/StakeAPI/api-reference/models Shows how to create a Game model instance using the `from_dict` factory method. This is useful for deserializing game data received from the API. ```python game = Game.from_dict({ "id": "sweet-bonanza", "name": "Sweet Bonanza", "category": "slots", "provider": "Pragmatic Play", "rtp": 96.48, "volatility": "high" }) ``` -------------------------------- ### Get All Casino Games Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieve a list of all available casino games. This method can optionally filter games by category. ```python games = await client.get_casino_games() ``` -------------------------------- ### Import StakeAPI Client Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Import the main StakeAPI client class to begin interacting with the Stake.com API. ```python from stakeapi import StakeAPI ``` -------------------------------- ### Initialize Multiple Accounts Source: https://chipadevteam.github.io/StakeAPI/resources/faq Manage multiple Stake.com accounts by instantiating separate client objects with unique access tokens. ```python client1 = StakeAPI(access_token="token_account_1") client2 = StakeAPI(access_token="token_account_2") ``` -------------------------------- ### Get All Sports Events Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieve a list of all available sports events. This method can optionally filter events by sport type. ```python events = await client.get_sports_events() ``` -------------------------------- ### Get Specific Game Details Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Fetch detailed information for a particular casino game using its unique game ID. ```python game = await client.get_game_details("game_123") print(f"{game.name} β€” RTP: {game.rtp}%") ``` -------------------------------- ### Load API Credentials from .env and Initialize Client Source: https://chipadevteam.github.io/StakeAPI/getting-started/authentication Load API credentials from a .env file using python-dotenv and initialize the StakeAPI client with both access token and session cookie. ```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() ``` -------------------------------- ### Create User Instance from Dictionary Source: https://chipadevteam.github.io/StakeAPI/api-reference/models Demonstrates the factory method `from_dict` to create a User model instance from a dictionary. Note that `created_at` requires a valid datetime string. ```python user = User.from_dict({"id": "123", "username": "player1", "created_at": "2024-01-01"}) ``` -------------------------------- ### Handle RateLimitError with Exponential Backoff Source: https://chipadevteam.github.io/StakeAPI/guides/rate-limiting Implement a retry mechanism with exponential backoff when a RateLimitError is encountered. This example uses asyncio for asynchronous operations. ```python from stakeapi.exceptions import RateLimitError import asyncio async def fetch_with_backoff(client, max_retries=5): for attempt in range(max_retries): try: return await client.get_user_balance() except RateLimitError: wait = 2 ** attempt # 1, 2, 4, 8, 16 seconds print(f"Rate limited! Waiting {wait}s (attempt {attempt + 1}/{max_retries})") await asyncio.sleep(wait) raise Exception("Exceeded maximum retries") ``` -------------------------------- ### Execute Async Code Source: https://chipadevteam.github.io/StakeAPI/resources/troubleshooting Use asyncio.run() to execute asynchronous functions from a synchronous entry point. ```python import asyncio async def main(): async with StakeAPI(access_token="token") as client: balance = await client.get_user_balance() # βœ… Correct asyncio.run(main()) # ❌ Wrong β€” don't call async functions directly # main() # This returns a coroutine, not the result ``` -------------------------------- ### Initialize StakeAPI Client Source: https://chipadevteam.github.io/StakeAPI/resources/troubleshooting Pass the access token directly to the constructor without including the header name prefix. ```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 User Balance Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieve the user's account balance across all currencies using GraphQL. 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 and Session Cookie Source: https://chipadevteam.github.io/StakeAPI/getting-started/authentication For maximum compatibility and robustness, initialize the StakeAPI client with both your access token and session cookie. ```python async with StakeAPI( access_token="your_token", session_cookie="your_session_cookie" ) as client: # Make API calls pass ``` -------------------------------- ### Get User Bet History Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Retrieves a list of the user's past bets. Specify a limit to control the number of bets returned. Requires an active session. ```python async def get_bet_history(self, limit: int = 50) -> List[Bet] ``` ```python bets = await client.get_bet_history(limit=20) for bet in bets: print(f"{bet.id}: {bet.amount} β†’ {bet.status}") ``` -------------------------------- ### Importing StakeAPI Utilities Source: https://chipadevteam.github.io/StakeAPI/api-reference/utilities Import the 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, ) ``` -------------------------------- ### Configure Environment Variables Source: https://chipadevteam.github.io/StakeAPI/getting-started/quickstart Uses python-dotenv to securely load the access token from a .env file. ```python import asyncio import os from dotenv import load_dotenv from stakeapi import StakeAPI load_dotenv() # Load from .env file async def main(): token = os.getenv("STAKE_ACCESS_TOKEN") if not token: print("Set STAKE_ACCESS_TOKEN environment variable!") return async with StakeAPI(access_token=token) as client: balance = await client.get_user_balance() print(balance) asyncio.run(main()) ``` -------------------------------- ### SportEvent Model Definition Source: https://chipadevteam.github.io/StakeAPI/api-reference/models Defines the Pydantic model for a sports event. Includes event ID, sport, league, teams, start time, status, and betting odds. ```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 ``` -------------------------------- ### StakeAPI Constructor Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Initializes the StakeAPI client with optional authentication credentials, base URL, timeout, and rate limiting configurations. ```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, ) ``` ``` -------------------------------- ### StakeAPI Project Structure Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Overview of the StakeAPI project directory structure, highlighting key directories and files. ```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 ``` -------------------------------- ### Initialize StakeAPI with Access Token Only Source: https://chipadevteam.github.io/StakeAPI/getting-started/authentication The simplest way to authenticate with StakeAPI is by providing only the access token. This is sufficient for most common use cases. ```python async with StakeAPI(access_token="your_token") as client: # Make API calls pass ``` -------------------------------- ### Filter Sports Events by Sport Type Source: https://chipadevteam.github.io/StakeAPI/guides/sports-betting Retrieves sports events filtered by specific sport types like football, basketball, and tennis. Ensure you have a valid access token and the `stakeapi` library installed. The available sport slugs are listed in the documentation. ```python async with StakeAPI(access_token="your_token") as client: # Football/Soccer football = await client.get_sports_events(sport="football") print(f"Football events: {len(football)}") # Basketball basketball = await client.get_sports_events(sport="basketball") print(f"Basketball events: {len(basketball)}") # Tennis tennis = await client.get_sports_events(sport="tennis") print(f"Tennis events: {len(tennis)}") ``` -------------------------------- ### Utilities Overview Source: https://chipadevteam.github.io/StakeAPI/api-reference/utilities The `stakeapi.utils` module offers essential helper functions for common tasks when interacting with the Stake.com API. These utilities ensure data integrity and simplify operations. ```APIDOC ## Overview The `stakeapi.utils` module provides utility functions for common operations like validation, formatting, and type conversion. **Import:** ```python from stakeapi.utils import ( validate_api_key, safe_decimal, parse_datetime, format_currency, calculate_win_rate, validate_bet_amount, sanitize_game_name, ) ``` ``` -------------------------------- ### Add StakeAPI using Poetry Source: https://chipadevteam.github.io/StakeAPI/getting-started/installation Add StakeAPI as a dependency to your project managed by Poetry. ```bash poetry add stakeapi ``` -------------------------------- ### Clone StakeAPI Repository Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Clone the StakeAPI repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/chipadevteam/StakeAPI.git cd StakeAPI ``` -------------------------------- ### Establish Basic WebSocket Connection Source: https://chipadevteam.github.io/StakeAPI/guides/websockets Connect to the Stake.com WebSocket API, authenticate with an access token, and subscribe to balance updates. This is the foundational snippet for all WebSocket interactions. ```python import asyncio import websockets import json async def connect_to_stake(): uri = "wss://stake.com/_api/websocket" headers = { "x-access-token": "your_token_here", "Origin": "https://stake.com", } async with websockets.connect(uri, extra_headers=headers) as ws: print("βœ… Connected to Stake.com WebSocket") # Subscribe to balance updates subscribe_msg = { "type": "subscribe", "channel": "user:balances" } await ws.send(json.dumps(subscribe_msg)) # Listen for messages async for message in ws: data = json.loads(message) print(f"πŸ“© Received: {data}") asyncio.run(connect_to_stake()) ``` -------------------------------- ### Implement a Custom Token Bucket Rate Limiter Source: https://chipadevteam.github.io/StakeAPI/guides/rate-limiting A simple token bucket rate limiter implementation using asyncio. This class manages token refills and enforces limits. ```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") ``` -------------------------------- ### Execute Custom GraphQL Query Source: https://chipadevteam.github.io/StakeAPI/resources/examples Demonstrates how to perform raw GraphQL queries using the internal _graphql_request method. ```python import asyncio from stakeapi import StakeAPI async def main(): async with StakeAPI(access_token="your_token") as client: query = """ query { user { id name balances { available { amount currency } } } } """ data = await client._graphql_request(query=query) print(data) asyncio.run(main()) ``` -------------------------------- ### Format and Lint Code Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Format code using Black, sort imports with isort, lint with flake8, and perform type checking with mypy. ```bash # Format code black stakeapi/ tests/ isort stakeapi/ tests/ # Lint flake8 stakeapi/ tests/ # Type check mypy stakeapi/ ``` -------------------------------- ### Execute Python Script Source: https://chipadevteam.github.io/StakeAPI/getting-started/quickstart Command to run the initial script from the terminal. ```bash python my_first_script.py ``` -------------------------------- ### Configure StakeAPI Client Rate Limit Source: https://chipadevteam.github.io/StakeAPI/guides/rate-limiting Set the desired requests per second when initializing the StakeAPI client. Default is 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) ``` -------------------------------- ### Execute Synchronously Source: https://chipadevteam.github.io/StakeAPI/resources/faq Wrap asynchronous StakeAPI calls using asyncio.run() for synchronous execution environments. ```python import asyncio from stakeapi import StakeAPI async def get_balance(): async with StakeAPI(access_token="token") as client: return await client.get_user_balance() balance = asyncio.run(get_balance()) ``` -------------------------------- ### Implement Error Handling Source: https://chipadevteam.github.io/StakeAPI/getting-started/quickstart Demonstrates catching specific API exceptions like authentication failures and rate limits. ```python import asyncio from stakeapi import StakeAPI from stakeapi.exceptions import ( StakeAPIError, AuthenticationError, RateLimitError, ) async def main(): async with StakeAPI(access_token="your_token") as client: try: balance = await client.get_user_balance() print(balance) except AuthenticationError: print("Invalid or expired token. Get a new one from stake.com") except RateLimitError: print("Too many requests. Wait a moment and try again.") except StakeAPIError as e: print(f"API error: {e}") asyncio.run(main()) ``` -------------------------------- ### Monitor Balance with Alerts Source: https://chipadevteam.github.io/StakeAPI/resources/examples Continuously polls the user balance and prints changes to the console. Uses a configurable check interval. ```python import asyncio from datetime import datetime from stakeapi import StakeAPI async def monitor(token: str, check_interval: int = 30): prev = {} while True: try: async with StakeAPI(access_token=token) as client: balance = await client.get_user_balance() now = datetime.now().strftime("%H:%M:%S") for cur, amt in balance["available"].items(): if amt <= 0: continue old = prev.get(cur, amt) diff = amt - old if diff > 0: print(f"[{now}] πŸ“ˆ {cur.upper()}: +{diff:.8f}") elif diff < 0: print(f"[{now}] πŸ“‰ {cur.upper()}: {diff:.8f}") prev = {k: v for k, v in balance["available"].items() if v > 0} except Exception as e: print(f"Error: {e}") await asyncio.sleep(check_interval) asyncio.run(monitor("your_token")) ``` -------------------------------- ### Implement Comprehensive Error Handling Source: https://chipadevteam.github.io/StakeAPI/api-reference/exceptions A recommended pattern for handling multiple exception types with specific recovery logic. ```python from stakeapi.exceptions import * try: result = await client.get_user_balance() except AuthenticationError: # Token issues β€” cannot retry handle_auth_failure() except RateLimitError: # Retry after delay await asyncio.sleep(5) except NetworkError: # Connection issues β€” retry with backoff await asyncio.sleep(2) except ValidationError as e: # Bad input β€” fix and retry log_validation_error(e) except StakeAPIError as e: # Catch-all for other API errors log_error(e) ``` -------------------------------- ### Build a Sports Analytics Dashboard Source: https://chipadevteam.github.io/StakeAPI/guides/sports-betting Aggregates event data to display counts by sport, live status, and top leagues. ```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()) ``` -------------------------------- ### Utilities Source: https://chipadevteam.github.io/StakeAPI/api-reference Includes helper functions and validators for StakeAPI. ```APIDOC ## Utilities ### Description Includes helper functions and validators for StakeAPI. These utilities can assist in data validation and other common tasks. ``` -------------------------------- ### Run Tests with Pytest Source: https://chipadevteam.github.io/StakeAPI/resources/contributing Execute tests using pytest. Options include running all tests, running tests with coverage, or running tests for a specific file. ```bash # Run all tests pytest # With coverage pytest --cov=stakeapi # Run specific test file pytest tests/test_client.py ``` -------------------------------- ### Basic Error Handling with StakeAPI Source: https://chipadevteam.github.io/StakeAPI/guides/error-handling Demonstrates a standard try-except block to catch specific API exceptions during client operations. ```python from stakeapi import StakeAPI from stakeapi.exceptions import ( StakeAPIError, AuthenticationError, RateLimitError, ValidationError, NetworkError, GameNotFoundError, InsufficientFundsError, ) async with StakeAPI(access_token="your_token") as client: try: balance = await client.get_user_balance() print(balance) except AuthenticationError: print("Your access token is invalid or expired.") print("Get a new token from stake.com") except RateLimitError: print("Too many requests. Slow down!") except NetworkError: print("Network error. Check your internet connection.") except StakeAPIError as e: print(f"API error: {e}") ``` -------------------------------- ### Format Endpoint for Bet Details Source: https://chipadevteam.github.io/StakeAPI/api-reference/endpoints Demonstrates how to format the BET_DETAILS endpoint string with a dynamic bet ID using Python's string formatting. ```python # Bet details endpoint = Endpoints.BET_DETAILS.format(bet_id="bet_123") # Result: /api/v1/bets/bet_123 ``` -------------------------------- ### Manage API Tokens with Environment Variables Source: https://chipadevteam.github.io/StakeAPI/guides/security Use environment variables to avoid hardcoding sensitive credentials in source code. ```python import os # βœ… GOOD β€” from environment token = os.getenv("STAKE_ACCESS_TOKEN") # ❌ BAD β€” hardcoded token = "2775b505cccaee723e5c705..." ``` -------------------------------- ### Exception Handling Patterns Source: https://chipadevteam.github.io/StakeAPI/api-reference/exceptions Overview of the StakeAPI exception hierarchy and how to implement robust error handling in your code. ```APIDOC ## Exception Hierarchy - **StakeAPIError**: Base exception for all library errors. - **AuthenticationError**: Raised on HTTP 401 (invalid/expired token). - **RateLimitError**: Raised on HTTP 429 (rate limit exceeded). - **ValidationError**: Raised when input data is invalid. - **NetworkError**: Raised on connection failures. - **GameNotFoundError**: Raised when a requested game does not exist. - **InsufficientFundsError**: Raised when account balance is too low for a transaction. ### Recommended Pattern ```python from stakeapi.exceptions import * try: result = await client.get_user_balance() except AuthenticationError: handle_auth_failure() except RateLimitError: await asyncio.sleep(5) except NetworkError: await asyncio.sleep(2) except ValidationError as e: log_validation_error(e) except StakeAPIError as e: log_error(e) ``` ``` -------------------------------- ### Use Access Token from Environment Variable Source: https://chipadevteam.github.io/StakeAPI/getting-started/authentication Retrieve the Stake.com API access token from the environment variable and use it to initialize the StakeAPI client. This method is recommended for security. ```python import os from stakeapi import StakeAPI token = os.getenv("STAKE_ACCESS_TOKEN") async with StakeAPI(access_token=token) as client: balance = await client.get_user_balance() ``` -------------------------------- ### Subscribe to Balance Updates Source: https://chipadevteam.github.io/StakeAPI/guides/websockets Listen for real-time notifications whenever your account balance changes. Ensure you are already connected to the WebSocket. ```python async def watch_balance(ws): await ws.send(json.dumps({ "type": "subscribe", "channel": "user:balances" })) async for message in ws: data = json.loads(message) if data.get("channel") == "user:balances": print(f"πŸ’° Balance update: {data['payload']}") ``` -------------------------------- ### Check User Balance with StakeAPI Source: https://chipadevteam.github.io/StakeAPI/resources/examples Retrieves and prints the available balances for all currencies in the user's account. ```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()) ``` -------------------------------- ### Place a Bet Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Place a bet by providing bet details in a dictionary format, including game ID, amount, and currency. Returns a Bet confirmation object. ```python bet = await client.place_bet({ "game_id": "game_123", "amount": 0.001, "currency": "btc", }) print(f"Bet ID: {bet.id} β€” Status: {bet.status}") ``` -------------------------------- ### Place a bet using StakeAPI Source: https://chipadevteam.github.io/StakeAPI/guides/betting Requires a valid access token and a dictionary containing game details. The client must be used within an asynchronous context. ```python import asyncio from stakeapi import StakeAPI async def place_a_bet(): async with StakeAPI(access_token="your_token") as client: bet = await client.place_bet({ "game_id": "game_123", "amount": 0.001, "currency": "btc", "bet_type": "single" }) print(f"βœ… Bet placed!") print(f" Bet ID: {bet.id}") print(f" Amount: {bet.amount}") print(f" Potential Payout: {bet.potential_payout}") print(f" Status: {bet.status}") asyncio.run(place_a_bet()) ``` -------------------------------- ### Configure Windows Event Loop Source: https://chipadevteam.github.io/StakeAPI/resources/troubleshooting Set the event loop policy to WindowsSelectorEventLoopPolicy to avoid ProactorEventLoop warnings on Windows. ```python import asyncio import sys if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) ``` -------------------------------- ### Manage Client Lifecycle Source: https://chipadevteam.github.io/StakeAPI/resources/troubleshooting Perform API operations within the context manager block to ensure the session remains open. ```python # ❌ Wrong async with StakeAPI(access_token="token") as client: pass # Client is closed here! balance = await client.get_user_balance() # βœ… Correct β€” keep operations inside the context async with StakeAPI(access_token="token") as client: balance = await client.get_user_balance() ``` -------------------------------- ### Initialize AuthManager Source: https://chipadevteam.github.io/StakeAPI/api-reference/auth-manager Initialize AuthManager with an optional access token or session cookie. ```python AuthManager( access_token: Optional[str] = None, session_cookie: Optional[str] = None, ) ``` -------------------------------- ### User Methods Source: https://chipadevteam.github.io/StakeAPI/api-reference/client Provides methods for retrieving user profile and balance information. ```APIDOC ## User Methods ### `get_user_profile()` Get the current user’s profile information. ```python async def get_user_profile(self) -> User ``` **Returns:** `User` β€” User profile object **Example:** ```python user = await client.get_user_profile() print(f"Username: {user.username}") print(f"Verified: {user.verified}") ``` ### `get_user_balance()` Get the user’s account balance across all currencies using GraphQL. ```python async def get_user_balance(self) -> Dict[str, Dict[str, float]] ``` **Returns:** Dictionary with `available` and `vault` balances **Response Format:** ```json { "available": { "btc": 0.001, "eth": 0.05, "usd": 100.0, }, "vault": { "btc": 0.01, "eth": 0.0, } } ``` **Example:** ```python balance = await client.get_user_balance() for currency, amount in balance["available"].items(): if amount > 0: print(f"{currency.upper()}: {amount}") ``` ```