### Install Selenium and WebDriver Manager Source: https://github.com/meisnate12/fantraxapi/blob/master/README.rst Install necessary packages for automated browser login and cookie management. Use pip for installation. ```bash pip install selenium ``` ```bash pip install webdriver-manager ``` -------------------------------- ### Install FantraxAPI Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md Install the FantraxAPI library using pip. This is the first step to using the library. ```python pip install fantraxapi ``` -------------------------------- ### Install Selenium and webdriver-manager Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md Install the necessary Python packages for browser automation and driver management. ```python pip install selenium pip install webdriver-manager ``` -------------------------------- ### Get Season Scores Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md Retrieve and print the scoring periods for a league. This example iterates through the scoring periods and prints each one. ```python from fantraxapi import League league_id = "96igs4677sgjk7ol" league = League(league_id) for _, scoring_period in league.scoring_periods().items(): print("") print(scoring_period) ``` -------------------------------- ### Get Team Roster Information Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve detailed roster information for a specific team, including active/reserve/injured player counts and player details for each position. This snippet also shows how to get a historical roster for a past period. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") team = league.team("wookie") # Get current roster roster = team.roster() print(f"{roster.team.name} Roster") print(f"Active: {roster.active}/{roster.active_max}") print(f"Reserve: {roster.reserve}/{roster.reserve_max}") print(f"Injured: {roster.injured}/{roster.injured_max}") for row in roster.rows: if row.player: print(f"{row.position.short_name}: {row.player.name}") print(f" Total Points: {row.total_fantasy_points}") print(f" PPG: {row.fantasy_points_per_game}") if row.game_today: print(f" Playing today: {row.game_today}") else: print(f"{row.position.short_name}: Empty") # Get roster for a specific daily period historical_roster = team.roster(period_number=8) ``` -------------------------------- ### Get Trade Block Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves a list of all trade blocks available in the league. ```APIDOC ## Get Trade Block ### Description Returns a list of TradeBlock objects that represent each Trade Block. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/trade_block` (Conceptual) ### Returns * **list[TradeBlock]** - List of TradeBlock objects that represent each Trade Block. ### Raises * **NotLoggedIn** - When there is no logged-in User in the Session object. ``` -------------------------------- ### Create League Instance and Get Basic Info Source: https://context7.com/meisnate12/fantraxapi/llms.txt Initialize the League class with a league ID to access league data. This snippet shows how to retrieve the league name, year, start/end dates, and the number of teams. ```python from fantraxapi import League # Initialize with your Fantrax league ID league_id = "96igs4677sgjk7ol" league = League(league_id) # Access basic league information print(f"League Name: {league.name}") # e.g., "Cowley's Chaos" print(f"Year: {league.year}") # e.g., "2024-25 NHL" print(f"Start Date: {league.start_date}") # datetime object print(f"End Date: {league.end_date}") # datetime object print(f"Number of Teams: {len(league.teams)}") # e.g., 12 ``` -------------------------------- ### Setup Auto Login with Cookies Source: https://github.com/meisnate12/fantraxapi/blob/master/README.rst Code to override the API request function for handling private leagues. It uses Selenium for automated login or loads saved cookies. ```python import os import pickle import time from requests import Session from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service ``` -------------------------------- ### Get All Live Scores for a Date Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve live scores for all teams in a league on a specific date and calculate total points per team. ```python # Get scores for all teams on a date all_scores = league.live_scores(scoring_date) for team_id, players in all_scores.items(): team_name = league.team_lookup[team_id].name total = sum(p.points for p in players) print(f"{team_name}: {total} total points") ``` -------------------------------- ### GET /live_scores Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves live scores for players on a given date. ```APIDOC ## GET /live_scores ### Description Returns a Dictionary of Team IDs to a list of LivePlayer objects with scores for that day. ### Method GET ### Endpoint /live_scores ### Parameters #### Query Parameters - **scoring_date** (date) - Required - Date of the Live Scoring. ### Response #### Success Response (200) - **dict[str, list[LivePlayer]]** - Dictionary of Team IDs to a list of LivePlayer objects with scores for that day. #### Response Example { "example": "{\"team1\": [{\"player_id\": \"player123\", \"score\": 15.5}], \"team2\": [{\"player_id\": \"player456\", \"score\": 12.0}]}" } ### Errors - **DateNotInSeason** - When the scoring_date is not in the Season. ``` -------------------------------- ### Get Trade Block Data Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieves and displays information about trade blocks within a league. Requires login. ```python trade_blocks = league.trade_block() for block in trade_blocks: print(f"\n{block.team.name}:") print(f" Note: {block.note}") print(f" Players Offered: {list(block.players_offered.keys())}") print(f" Positions Wanted: {[p.short_name for p in block.positions_wanted]}") ``` -------------------------------- ### Get Pending Trades Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieves and displays details of pending trades in a league. Requires login. ```python pending = league.pending_trades() for trade in pending: print(f"\nTrade proposed by: {trade.proposed_by.name}") print(f" Proposed: {trade.proposed}") print(f" Accepted: {trade.accepted}") for move in trade.moves: print(f" {move}") ``` -------------------------------- ### GET /team_roster Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves the roster for a specific team, optionally for a given period. ```APIDOC ## GET /team_roster ### Description Returns a Roster object that represents the given Team ID’s roster for a specific period or the latest period’s standings when number is None. ### Method GET ### Endpoint /team_roster ### Parameters #### Query Parameters - **team_id** (str) - Required - Team ID. - **period_number** (int | None) - Optional - Daily Period Number, defaults to None. ### Response #### Success Response (200) - **Roster** - Roster object that represent the given Team ID’s roster. #### Response Example { "example": "{\"players\": [{\"player_id\": \"player123\", \"name\": \"John Doe\"}]}" } ### Errors - **PeriodNotInSeason** - When the period_number is not in the Season ``` -------------------------------- ### Get Transactions Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Fetches a list of the latest transactions in the league, with an option to specify the count. ```APIDOC ## Get Transactions ### Description Returns a list of Transaction objects that represent the latest transactions. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/transactions` (Conceptual) ### Parameters #### Query Parameters * **count** (int) - Optional - Number of transactions to return. Defaults to 100. ### Returns * **list[Transaction]** - List of Transaction objects that represent the latest transactions. ``` -------------------------------- ### Handle Fantrax API Exceptions Source: https://context7.com/meisnate12/fantraxapi/llms.txt Demonstrates how to handle various Fantrax API exceptions for robust error management. Includes examples for invalid league IDs, non-existent teams, dates/periods outside the season, and accessing private endpoints without authentication. ```python from datetime import date from fantraxapi import League, FantraxException, NotLoggedIn, NotTeamInLeague from fantraxapi.exceptions import DateNotInSeason, PeriodNotInSeason, NotMemberOfLeague try: # Invalid league ID league = League("invalid_league_id") except FantraxException as e: print(f"Failed to load league: {e}") league = League("96igs4677sgjk7ol") try: # Invalid team identifier team = league.team("nonexistent_team") except NotTeamInLeague as e: print(f"Team not found: {e}") try: # Date outside season team = league.team("wookie") scores = team.live_scores(date(year=2024, month=7, day=18)) except DateNotInSeason as e: print(f"Invalid date: {e}") try: # Period outside season roster = league.team("wookie").roster(period_number=500) except PeriodNotInSeason as e: print(f"Invalid period: {e}") try: # Accessing private endpoint without login trade_block = league.trade_block() except NotLoggedIn as e: print(f"Authentication required: {e}") ``` -------------------------------- ### Get Standings Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves the league standings, either for a specific scoring period or the latest available. ```APIDOC ## Get Standings ### Description Returns Standings object that represents either the standings after a period or the latest period’s standings when scoring_period_number is None. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/standings` (Conceptual) ### Parameters #### Query Parameters * **scoring_period_number** (int | None) - Optional - Period number. Defaults to None (latest standings). * **only_period** (bool) - Optional - Only that specific period’s standings. Defaults to False. ### Returns * **Standings** - Standings object that corresponds with the period standing. ``` -------------------------------- ### Get Pending Trades Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Fetches a list of all pending trades within the league. ```APIDOC ## Get Pending Trades ### Description Returns a list of Trade objects that represent pending trades. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/pending_trades` (Conceptual) ### Returns * **list[Trade]** - List of Trade objects that represent pending trades. ### Raises * **NotLoggedIn** - When there is no logged-in User in the Session object. ``` -------------------------------- ### Get Live Scores for a Specific Date Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve live scoring data for a specific team on a given date. Handles potential 'DateNotInSeason' errors. ```python from datetime import date from fantraxapi import League from fantraxapi.exceptions import DateNotInSeason league = League("96igs4677sgjk7ol") team = league.team("wookie") try: # Get live scores for a specific date scoring_date = date(year=2024, month=10, day=18) live_scores = team.live_scores(scoring_date) print(f"Live scores for {team.name} on {scoring_date}:") for player in live_scores: print(f" {player.name} ({player.pos_short_name}): {player.points} pts") if player.injured: print(f" Status: {'IR' if player.injured_reserve else 'Day-to-Day' if player.day_to_day else 'Out'}") except DateNotInSeason as e: print(f"Error: {e}") ``` -------------------------------- ### Get Scoring Periods and Results Source: https://context7.com/meisnate12/fantraxapi/llms.txt Access information about all scoring periods, including their dates and detailed results for each matchup. This is useful for tracking game progress and outcomes throughout the season. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") # Access all scoring periods for period_num, period in league.scoring_periods.items(): print(f"Period {period.number}: {period.start} to {period.end}") # Get detailed scoring period results with matchups results = league.scoring_period_results(season=True, playoffs=True) for period_num, result in results.items(): print(f"\n{result.name} - {'Complete' if result.complete else 'In Progress'}") print(f" {result.days} days ({result.start} - {result.end})") for matchup in result.matchups: winner, winner_score, loser, loser_score = matchup.winner() print(f" {winner.name} ({winner_score}) vs {loser.name} ({loser_score})") print(f" Margin: {matchup.difference()}") ``` -------------------------------- ### Get Current Position Counts Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve current games played per position for a team, including minimum and maximum allowed counts. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") team = league.team("wookie") # Get current position counts counts = team.position_counts() for pos_name, count in counts.items(): print(f"{pos_name}:") print(f" Games Played: {count.gp}") print(f" Min Required: {count.min}") print(f" Max Allowed: {count.max}") ``` -------------------------------- ### Get Recent Transactions Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve transaction history, including waiver wire pickups, drops, and free agent signings. Defaults to the last 100 transactions. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") # Get last 100 transactions (default) transactions = league.transactions() # Get more transactions transactions = league.transactions(count=160) for tx in transactions[:10]: # Show first 10 print(f"\n{tx.date} - {tx.team.name}") for player in tx.players: print(f" {player.type}: {player.name} ({player.pos_short_name}) - {player.team_short_name}") # Transaction types: WW (Waiver Wire), FA (Free Agent), DROP ``` -------------------------------- ### Get Scoring Period Results Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Fetches scoring period results for the league, optionally including season and playoff data. ```APIDOC ## Get Scoring Period Results ### Description Returns Season ScoringPeriodResult objects for the league. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/scoring_period_results` (Conceptual) ### Parameters #### Query Parameters * **season** (bool) - Optional - Return season Scoring Periods Results for this season. Defaults to True. * **playoffs** (bool) - Optional - Return playoff Scoring Periods Results for this season. Defaults to True. ### Returns * **dict[int, ScoringPeriodResult]** - Dictionary of Period Number to ScoringPeriodResult object. ``` -------------------------------- ### Get Team by Identifier Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves a Team object from the league using its ID or a partial name match. ```APIDOC ## Get Team ### Description Returns a Team object for the given Team ID or where the Team name contains the given value. ### Method GET (Implicit) ### Endpoint `/leagues/{league_id}/teams/{team_identifier}` (Conceptual) ### Parameters #### Path Parameters * **team_identifier** (str) - Required - Team identifier (ID or partial name). ### Returns * **Team** - Team object that corresponds with the provided team identifier. ### Raises * **NotTeamInLeague** - When the team identifier provided is not found to be associated with any team in the League. ``` -------------------------------- ### Get Position Counts for a Specific Scoring Period Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve games played per position for a specific scoring period, useful for lineup optimization. ```python # Get position counts for a specific scoring period period_counts = team.position_counts(scoring_period_number=11) print(f"Center games in period 11: {period_counts['C'].gp}") ``` -------------------------------- ### GET /position_counts Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Retrieves the position counts for a specific team, optionally for a given scoring period. ```APIDOC ## GET /position_counts ### Description Returns a Dictionary of PositionCount objects that represents the positions used for a given Team ID for a specific period or the latest period’s standings when scoring_period_number is None. ### Method GET ### Endpoint /position_counts ### Parameters #### Query Parameters - **team_id** (str) - Required - Team ID to get positions for. - **scoring_period_number** (int | None) - Optional - Period Number, defaults to None. ### Response #### Success Response (200) - **dict[str, PositionCount]** - Dictionary of Position Short Names to PositionCount objects. #### Response Example { "example": "{\"QB\": {\"count\": 1, \"starts\": 1}, \"RB\": {\"count\": 2, \"starts\": 2}}" } ### Errors - **PeriodNotInSeason** - When the period_number is not in the Season ``` -------------------------------- ### Get League Standings Source: https://context7.com/meisnate12/fantraxapi/llms.txt Fetch current league standings or standings for a specific scoring period. This allows for analysis of team performance over time or at a particular point in the season. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") # Get current overall standings standings = league.standings() for rank, record in standings.ranks.items(): print(f"{rank}: {record.team.name} ({record.win}-{record.loss}-{record.tie})") print(f" Points For: {record.points_for}, Points Against: {record.points_against}") # Get standings after a specific scoring period period_standings = league.standings(scoring_period_number=11) print(f"Period 11 Leader: {period_standings.ranks[1].team.name}") # Get standings for only a specific period (not cumulative) period_only = league.standings(scoring_period_number=6, only_period=True) top_scorer = period_only.ranks[1] print(f"Period 6 Winner: {top_scorer.team.name} with {top_scorer.points_for} points") ``` -------------------------------- ### Get All League Teams Source: https://context7.com/meisnate12/fantraxapi/llms.txt Retrieve all teams within a league and access specific teams by name or ID. This is useful for iterating through all participants or fetching a single team's data. ```python from fantraxapi import League league = League("96igs4677sgjk7ol") # List all teams in the league for team in league.teams: print(f"Team: {team.name} (ID: {team.id})") # Get a specific team by partial name match (case-insensitive) team = league.team("wookie") print(f"Found: {team.name}") # "Kashyyyk Wookies" # Get team by exact ID team_by_id = league.team_lookup["er0c60arm15b60vy"] print(f"Team: {team_by_id.name}") ``` -------------------------------- ### Instantiate League Object (Import fantraxapi) Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md An alternative way to instantiate the League object by importing the entire fantraxapi module. Ensure you have your league ID ready. ```python import fantraxapi league_id = "96igs4677sgjk7ol" league = fantraxapi.League(league_id) ``` -------------------------------- ### Instantiate League Object (Import League) Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md Create an instance of the League object by providing your league ID. This object is used to interact with your specific Fantrax league. ```python from fantraxapi import League league_id = "96igs4677sgjk7ol" league = League(league_id) ``` -------------------------------- ### Initialize FantraxAPI League Object Source: https://github.com/meisnate12/fantraxapi/blob/master/README.rst Create an instance of the League object to interact with the Fantrax API. Requires a league ID. ```python from fantraxapi import League league_id = "96igs4677sgjk7ol" league = League(league_id) ``` ```python import fantraxapi league_id = "96igs4677sgjk7ol" league = fantraxapi.League(league_id) ``` -------------------------------- ### League Object Initialization Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/league.md Initializes a League object using the league ID and an optional session. ```APIDOC ## Initialize League Object ### Description Creates an instance of the League object. ### Parameters * **league_id** (str) - Required - Fantrax League ID. * **session** (Session | None) - Optional - Custom Session object. ### Attributes * **league_id** (str) - Fantrax League ID. * **session** (Session) - Request Session Object. * **logged_in** (bool) - True when there’s a logged-in User. * **name** (str) - Name of the League. * **year** (str) - Year of the League. * **start_date** (datetime) - Start date of the League. * **end_date** (datetime) - End date of the League. * **positions** (dict[str, Position]) - Dictionary of Position ID to Positions. * **status** (dict[str, Status]) - Dictionary of Status ID to Status. * **scoring_periods** (dict[int, ScoringPeriod]) - Dictionary of Scoring Period Number to ScoringPeriod. * **scoring_periods_lookup** (dict[str, ScoringPeriod]) - Dictionary of Scoring Period Range to ScoringPeriod. * **scoring_dates** (dict[int, date]) - Dictionary of daily period numbers to dates that have scoring in this season. * **teams** (list[Team]) - List of Teams in the League. * **team_lookup** (dict[str, Team]) - Dictionary of Team IDs to Teams. ``` -------------------------------- ### LivePlayer Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a player with live scoring information, including their league, team, and current fantasy points. ```APIDOC ## LivePlayer Object ### Description Represents a single Player with Live Scoring. ### Attributes - **league** ([League](league.md#fantraxapi.objs.League)) – The League instance this object belongs to. - **id** (str) – Player ID. - **name** (str) – Player Name. - **short_name** (str) – Player Short Name. - **team_name** (str) – Team Name. - **team_short_name** (str) – Team Short Name. - **pos_short_name** (str) – Player Positions. - **positions** (list of [Position](#fantraxapi.objs.Position)) – Player Positions. - **all_positions** (list of [Position](#fantraxapi.objs.Position)) – Positions Player can be placed into. - **day_to_day** (bool) – Player Day-to-Day. - **out** (bool) – Player Out. - **injured_reserve** (bool) – Player on Injured Reserve. - **suspended** (bool) – Player Suspended. - **injured** (bool) – Player either Day-to-Day, Out, or on Injured Reserve. - **team** ([Team](#fantraxapi.objs.Team)) – Fantasy Team Player is on. - **points** (float) – Player Fantasy Points for the Points Date. - **points_date** (date) – date Player scored points. ``` -------------------------------- ### Python Code for Auto Login and Cookie Management Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/intro.md This code sets up an automatic login process for Fantrax using Selenium. It overrides the default API request method to handle authentication. If not logged in, it attempts to add a cookie. If a NotLoggedIn exception occurs, it refreshes the cookie. The cookie is saved to 'fantraxloggedin.cookie' for future use. ```python import os import pickle import time from requests import Session from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager from fantraxapi import League, NotLoggedIn, api from fantraxapi.api import Method username = "YOUR_USERNAME_HERE" # Provide your Fantrax Username here password = "YOUR_PASSWORD_HERE" # Provide your Fantrax Password here cookie_filepath = "fantraxloggedin.cookie" # Name of the saved Cookie file old_request = api.request # Saves the old function def new_request(league: "League", methods: list[Method] | Method) -> dict: try: if not league.logged_in: add_cookie_to_session(league.session) # Tries the login function when not logged in return old_request(league, methods) # Run old function except NotLoggedIn: add_cookie_to_session(league.session, ignore_cookie=True) # Adds/refreshes the cookie when NotLoggedIn is raised return new_request(league, methods) # Rerun the request api.request = new_request # replace the old function with the new function def add_cookie_to_session(session: Session, ignore_cookie: bool = False) -> None: if not ignore_cookie and os.path.exists(cookie_filepath): with open(cookie_filepath, "rb") as f: for cookie in pickle.load(f): session.cookies.set(cookie["name"], cookie["value"]) else: service = Service(ChromeDriverManager().install()) options = Options() options.add_argument("--headless") options.add_argument("--window-size=1920,1600") options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36") with webdriver.Chrome(service=service, options=options) as driver: driver.get("https://www.fantrax.com/login") username_box = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='email']"))) username_box.send_keys(username) password_box = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='password']"))) password_box.send_keys(password) password_box.send_keys(Keys.ENTER) time.sleep(5) cookies = driver.get_cookies() with open(cookie_filepath, "wb") as cookie_file: pickle.dump(driver.get_cookies(), cookie_file) for cookie in cookies: session.cookies.set(cookie["name"], cookie["value"]) league_id = "usglqmvqmelpe6um" my_league = League(league_id) print(my_league.trade_block()) # The Trade Block Page is always private ``` -------------------------------- ### Roster Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a Player's Roster within a league. ```APIDOC ## Roster Object ### Description Represents a Player’s Roster. ### Variables - **league** (*League*) – The League instance this object belongs to. - **team** (*Team*) – Team who made the Transaction. - **period_number** (*int*) – Daily Period Number. - **period_date** (*date*) – Daily Period Date. - **active** (*int*) – Number of Players in Active Slots. - **active_max** (*int*) – Max Number of Players that can be in Active Slots. - **reserve** (*int*) – Number of Players in Reserve Slots. - **reserve_max** (*int*) – Max Number of Players that can be in Reserve Slots. - **injured** (*int*) – Number of Players in Injured Slots. - **injured_max** (*int*) – Max Number of Players that can be in Injured Slots. - **rows** (*list*[*RosterRow*]) – List of RosterRows in the Roster. ``` -------------------------------- ### Matchup Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single matchup between two teams in a league, including scores and participating teams. ```APIDOC ## Matchup Object ### Description Represents a single Matchup. ### Attributes - **league** ([League](league.md#fantraxapi.objs.League)) – The League instance this object belongs to. - **scoring_period** ([ScoringPeriodResult](#fantraxapi.objs.ScoringPeriodResult)) – Scoring Period result this instance belongs to. - **matchup_key** (int) – Team ID. - **away** ([Team](#fantraxapi.objs.Team)) – Away Team. - **away_score** (float) – Away Team Score. - **home** ([Team](#fantraxapi.objs.Team)) – Home Team. - **home_score** (float) – Home Team Score. ``` -------------------------------- ### Standings Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents the standings for a league, including team ranks and records. ```APIDOC ## Standings Object ### Description Represents a single Standings object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **scoring_period_number** (int) - The current scoring period number. - **ranks** (dict[int, Record]) - A dictionary mapping team ranks to their corresponding Record objects. ``` -------------------------------- ### Authenticate and Access Private League Endpoints Source: https://context7.com/meisnate12/fantraxapi/llms.txt Handles login using Selenium for cookie management to access private Fantrax endpoints. It intercepts API requests to ensure a valid session. ```python import os import pickle import time from requests import Session from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager from fantraxapi import League, NotLoggedIn, api from fantraxapi.api import Method username = "YOUR_USERNAME" password = "YOUR_PASSWORD" cookie_filepath = "fantraxloggedin.cookie" old_request = api.request def new_request(league: "League", methods: list[Method] | Method) -> dict: try: if not league.logged_in: add_cookie_to_session(league.session) return old_request(league, methods) except NotLoggedIn: add_cookie_to_session(league.session, ignore_cookie=True) return new_request(league, methods) api.request = new_request def add_cookie_to_session(session: Session, ignore_cookie: bool = False) -> None: if not ignore_cookie and os.path.exists(cookie_filepath): with open(cookie_filepath, "rb") as f: for cookie in pickle.load(f): session.cookies.set(cookie["name"], cookie["value"]) else: service = Service(ChromeDriverManager().install()) options = Options() options.add_argument("--headless") with webdriver.Chrome(service=service, options=options) as driver: driver.get("https://www.fantrax.com/login") username_box = WebDriverWait(driver, 10).until( expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='email']")) ) username_box.send_keys(username) password_box = WebDriverWait(driver, 10).until( expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='password']")) ) password_box.send_keys(password) password_box.send_keys(Keys.ENTER) time.sleep(5) with open(cookie_filepath, "wb") as cookie_file: pickle.dump(driver.get_cookies(), cookie_file) for cookie in driver.get_cookies(): session.cookies.set(cookie["name"], cookie["value"]) # Now access private endpoints league = League("96igs4677sgjk7ol") ``` -------------------------------- ### Record Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single Record of a Standings within a league. ```APIDOC ## Record Object ### Description Represents a single Record of a Standings. ### Variables - **league** (*League*) – The League instance this object belongs to. - **standings** (*Standings*) – The Standings instance this Record belongs to. - **team** (*Team*) – Team. - **rank** (*int*) – Standings Rank. - **win** (*int*) – Number of Wins. - **loss** (*int*) – Number of Losses. - **tie** (*int*) – Number of Ties. - **points** (*int*) – Number of Points. - **win_percentage** (*float*) – Win Percentage. - **games_back** (*int*) – Number of Games Back. - **wavier_wire_order** (*int*) – Wavier Wire Claim Order. - **points_for** (*float*) – Fantasy Points For. - **points_against** (*float*) – Fantasy Points Against. - **streak** (*str*) – Streak. ``` -------------------------------- ### Team Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a fantasy team within a league. ```APIDOC ## Team Object ### Description Represents a single Team object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **id** (str) - The unique identifier for the team. - **name** (str) - The full name of the team. - **short** (str) - The short name of the team. ### Methods #### position_counts(scoring_period_number: int | None = None) -> dict[str, PositionCount] Returns a dictionary of PositionCount objects for a specified scoring period or the latest period if none is provided. - **Parameters**: - **scoring_period_number** (int | None) - The scoring period number. Defaults to None. - **Returns**: A dictionary mapping position short names to PositionCount objects. #### live_scores(score_date: date) -> list[Player] Returns a list of Player objects with their scores for a given date. - **Parameters**: - **score_date** (date) - The date for which to retrieve live scores. - **Returns**: A list of Player objects with their scores for the specified date. #### roster(period_number: int | None = None) -> Roster Returns a Roster object representing the team's roster for a specified period. - **Parameters**: - **period_number** (int | None) - The period number for the roster. Defaults to None. - **Returns**: A Roster object representing the team's roster. ``` -------------------------------- ### Retrieve Fantrax League Trade Block Data Source: https://github.com/meisnate12/fantraxapi/blob/master/README.rst This snippet demonstrates how to instantiate a League object and retrieve its trade block. Note that the trade block page is always private. ```python league_id = "usglqmvqmelpe6um" my_league = League(league_id) print(my_league.trade_block()) # The Trade Block Page is always private ``` -------------------------------- ### TradePlayer Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a player involved in a trade. ```APIDOC ## TradePlayer Object ### Description Represents a single TradePlayer object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **trade** (Trade) - The Trade instance this TradePlayer belongs to. - **from_team** (Team) - The Fantasy Team the player was traded from. - **to_team** (Team) - The Fantasy Team the player was traded to. - **player** (Player) - The Player instance this TradePlayer belongs to. - **fantasy_points_per_game** (float) - The player's fantasy points per game in the context of the trade. - **total_fantasy_points** (float) - The player's total fantasy points in the context of the trade. ``` -------------------------------- ### TransactionPlayer Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single player involved in a transaction. ```APIDOC ## TransactionPlayer Object ### Description Represents a single Player from a Transaction. ### Variables - **league** (League) - The League instance this object belongs to. - **id** (str) - Player ID. - **name** (str) - Player Name. - **short_name** (str) - Player Short Name. - **team_name** (str) - Team Name. - **team_short_name** (str) - Team Short Name. - **pos_short_name** (str) - Player Positions. - **positions** (list[Position]) - Player Positions. - **all_positions** (list[Position]) - Positions Player can be placed into. - **day_to_day** (bool) - Player Day-to-Day. - **out** (bool) - Player Out. - **injured_reserve** (bool) - Player on Injured Reserve. - **suspended** (bool) - Player Suspended. - **injured** (bool) - Player either Day-to-Day, Out, or on Injured Reserve. - **type** (str) - Transaction Type. ``` -------------------------------- ### Game Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single game in Fantrax, including details about the league, player, date, and opponent. ```APIDOC ## Game Object ### Description Represents a single Game. ### Attributes - **league** ([League](league.md#fantraxapi.objs.League)) – The League instance this object belongs to. - **id** (str) – Game ID. - **player** ([Player](#fantraxapi.objs.Player)) – Player to view this game from. - **date** (date) – The date this game is played. - **opponent** (str) – NHL Short Name of the opponent. - **time** (time) – Time of the game start if it hasn’t been played yet. - **home** (bool) – Is Player Home? - **away** (bool) – Is Player Away? ``` -------------------------------- ### TradeBlock Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a team's trade block, listing players they are willing to trade and players they are looking for. ```APIDOC ## TradeBlock Object ### Description Represents a single TradeBlock object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **team** (Team) - The Team associated with this trade block. - **update_date** (datetime) - The last date and time the trade block was updated. - **note** (str) - A note associated with the trade block. - **players_offered** (dict[str, list[Player]]) - A dictionary of players offered in the trade block. - **positions_wanted** (list[Position]) - A list of positions the team is looking for. - **positions_offered** (list[Position]) - A list of positions the team is offering. - **stats_offered** (list[str]) - A list of stats the team is offering. - **stats_wanted** (list[str]) - A list of stats the team is looking for. ``` -------------------------------- ### PositionCount Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents the minimum and maximum counts for a position during a scoring period, along with games played. ```APIDOC ## PositionCount Object ### Description Represents a single Position min/max count for a period. ### Attributes - **league** ([League](league.md#fantraxapi.objs.League)) – The League instance this object belongs to. - **min** (int or None) – Minimum number that have to be played. - **max** (int or None) – Maximum number that can be played. - **gp** (int or None) – Total games played. - **name** (str) – Position Name. - **short_name** (str) – Position Short Name. ``` -------------------------------- ### Handle Fantrax Login and Session Cookies Source: https://github.com/meisnate12/fantraxapi/blob/master/README.rst This function intercepts API requests to automatically log in to Fantrax using provided credentials or a saved cookie file. It uses Selenium for browser automation if a valid cookie is not found. ```python from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait from webdriver_manager.chrome import ChromeDriverManager from fantraxapi import League, NotLoggedIn, api from fantraxapi.api import Method username = "YOUR_USERNAME_HERE" # Provide your Fantrax Username here password = "YOUR_PASSWORD_HERE" # Provide your Fantrax Password here cookie_filepath = "fantraxloggedin.cookie" # Name of the saved Cookie file old_request = api.request # Saves the old function def new_request(league: "League", methods: list[Method] | Method) -> dict: try: if not league.logged_in: add_cookie_to_session(league.session) # Tries the login function when not logged in return old_request(league, methods) # Run old function except NotLoggedIn: add_cookie_to_session(league.session, ignore_cookie=True) # Adds/refreshes the cookie when NotLoggedIn is raised return new_request(league, methods) # Rerun the request api.request = new_request # replace the old function with the new function def add_cookie_to_session(session: Session, ignore_cookie: bool = False) -> None: if not ignore_cookie and os.path.exists(cookie_filepath): with open(cookie_filepath, "rb") as f: for cookie in pickle.load(f): session.cookies.set(cookie["name"], cookie["value"]) else: service = Service(ChromeDriverManager().install()) options = Options() options.add_argument("--headless") options.add_argument("--window-size=1920,1600") options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36") with webdriver.Chrome(service=service, options=options) as driver: driver.get("https://www.fantrax.com/login") username_box = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='email']"))) username_box.send_keys(username) password_box = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, "//input[@formcontrolname='password']"))) password_box.send_keys(password) password_box.send_keys(Keys.ENTER) time.sleep(5) cookies = driver.get_cookies() with open(cookie_filepath, "wb") as cookie_file: pickle.dump(driver.get_cookies(), cookie_file) for cookie in cookies: session.cookies.set(cookie["name"], cookie["value"]) ``` -------------------------------- ### ScoringPeriodResult Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single Scoring Period's results. ```APIDOC ## ScoringPeriodResult Object ### Description Represents a single Scoring Period. ### Variables - **league** (*League*) – The League instance this object belongs to. - **playoffs** (*bool*) – This Scoring Period is Playoffs. - **name** (*str*) – Name. - **period** (*ScoringPeriod*) – Scoring Period object for this result. - **start** (*date*) – Start Date of the Period. - **end** (*date*) – End Date of the Period. - **next** (*date*) – Next Day after the Period. - **days** (*int*) – Number of Days in the Scoring Period. - **complete** (*bool*) – Is the Period Complete? - **current** (*bool*) – Is it the current Period? - **future** (*bool*) – Is the Period in the future? - **matchups** (*list*[*Matchup*]) – List of Matchups. - **other_brackets** (*dict*[str, Matchup]) – Dictionary of Matchups in Other Brackets. - **title** (*str*) – Title of the Period. ``` -------------------------------- ### ScoringPeriod Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single Scoring Period within a league. ```APIDOC ## ScoringPeriod Object ### Description Represents a single Period. ### Variables - **league** (*League*) – The League instance this object belongs to. - **start** (*date*) – Date this scoring period starts. - **end** (*date*) – Date this scoring period ends. - **number** (*int*) – Period number. - **range** (*str*) – String display of the Scoring Period range. ``` -------------------------------- ### RosterRow Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a single Row on a Player's Roster. ```APIDOC ## RosterRow Object ### Description Represents a single Row on a Player’s Roster. ### Variables - **league** (*League*) – The League instance this object belongs to. - **roster** (*Roster*) – The Roster instance this RosterRow belongs to. - **position** (*Position*) – The Position object associated with the RosterRow. - **player** (*Player* | None) – The Player in the RosterRow. - **total_fantasy_points** (*float* | None) – The Total Fantasy Points for the Player in the RosterRow. - **fantasy_points_per_game** (*float* | None) – The Fantasy Points Per Game for the Player in the RosterRow. - **game_today** (*Game*) – Game for the Player in the RosterRow. - **future_games** (*dict*[str, Game]) – Dictionary of dates to future Games or the last game of the season if it’s over. ``` -------------------------------- ### Trade Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents a trade transaction between teams. ```APIDOC ## Trade Object ### Description Represents a single Trade object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **proposed_by** (Team) - The Team that proposed the trade. - **proposed** (datetime) - The date and time the trade was proposed. - **accepted** (datetime) - The date and time the trade was accepted. - **executed** (datetime) - The date and time the trade will be executed. - **moves** (list[TradeDraftPick | TradePlayer]) - A list of moves included in the trade. ``` -------------------------------- ### Status Object Source: https://github.com/meisnate12/fantraxapi/blob/master/docs/objs.md Represents the status of various entities within the Fantrax system. ```APIDOC ## Status Object ### Description Represents a single Status object in Fantrax. ### Variables - **league** (League) - The League instance this object belongs to. - **id** (str) - The unique identifier for the status. - **code** (str) - The status code. - **name** (str) - The full name of the status. - **short_name** (str) - A shortened name for the status. - **description** (str) - A detailed description of the status. ```