openapi: 3.0.3
info:
  title: FieldFunded Sports API
  description: |
    Real-time sports data API covering **30+ sports & esports** and **1,000+ betting markets** per event. Built for low-latency live odds, settlement, and quantitative analysis.

    ## Official SDK
    The fastest way to integrate is using our official [TypeScript SDK](/sdk). It handles authentication, retries, and provides full type safety for all 1,000+ markets.

    ## Features
    - **Sub-second latency** — Data refreshed every 300ms from live feeds
    - **30+ sports & esports** — Soccer, Basketball, Tennis, Ice Hockey, Baseball, American Football, Rugby, Cricket, MMA, Handball, Volleyball, and more
    - **Full Esports Coverage** — Counter-Strike, Dota 2, LoL, Valorant, Rainbow Six, King of Glory, Call of Duty, Mobile Legends
    - **1,000+ Markets per game** — Match Winner, Over/Under, BTTS, Handicaps, Corners, Cards, Player Props, Map Winner, Round Winner, and more (major leagues like NBA, NFL, Premier League)
    - **Live Scores** — Real-time scoreboards with period scores, serving indicators, and match clocks
    - **Outrights/Futures** — Long-term futures and season-level markets (e.g., League Winner, Top Goalscorer, Most Assists, Tournament MVP)
    - **Settlement Results** (Automatic) — Per-market settlement outcomes (won/lost/refund) for ended events, with gradual market-by-market resolution. No developer action required — markets begin resolving within seconds after game end. Send `stake` to get instant `payout` calculation (currency-agnostic). Poll regularly after the game ends to capture all market resolutions as they arrive.
    - **Parlay Resolution** (Exclusive) — Submit multi-leg parlays (singles, combos) and get combined result + payout calculation with optional `stake`. Refund legs are treated as odds 1.00 in the combined calculation.
    - **Featured Games** — Curated top matches from priority leagues (Premier League, La Liga, Champions League, Europa League, Bundesliga, Serie A, Ligue 1, NBA, NFL, MLB, NHL), live-first sorted.
    - **Rich Visual Assets** — PNG team logos (~85% coverage), PNG & SVG team logos for featured leagues, SVG league logos, 182 SVG country flags and custom SVG sport icons.
    - **Global Coverage** — Premier League, La Liga, NBA, NFL, NHL, MLB, Champions League, and thousands of worldwide leagues including 3rd divisions, regional cups, ITF tournaments, and youth/female leagues, etc.

    ## Pricing
    Free tier with 10,000 requests/month. Paid plans from $29/mo. All features included at every tier. See [full pricing comparison](/compare/pricing).


    ## Learn More
    - [Quick Start Guide](/quickstart) — First API call in 5 minutes
    - [Authentication](/authentication) — API key setup
    - [Rate Limits](/rate-limits) — Per-plan limits and quota monitoring
    - [Supported Sports](/reference/supported-sports) — Full sport key reference
    - [Market Types](/reference/market-types) — 1,000+ market catalogue
    - [Event Statuses](/reference/event-statuses) — Lifecycle and 48-hour rule
    - [Visual Assets](/reference/visual-assets) — Logos, flags, and icons
    - [SDK Reference](/sdk) — TypeScript SDK installation and usage


    ## Sport-Specific Live Data
    Detail endpoints include a `sport_data` object with sport-specific fields:
    - **Tennis/Volleyball**: `home_serving`, `away_serving` (who is serving), `home_game_score`/`away_game_score` (values: `0`, `15`, `30`, `40`, `AD`), `is_tiebreak`
    - **Ice Hockey**: `home_suspend`/`away_suspend` (players in penalty box = power play indicator)
    - **All sports**: Period-by-period scoreboards via `scoreboard` object

    The `scoreboard` object contains:
    - `headers`: Column labels (e.g. `["", "1st", "2nd", "T", "Corner", "YC", "RC"]`)
    - `home`/`away`: Stats arrays matching the headers

    **Sport-specific scoreboard detail:**

    | Sport | Scoreboard Columns | Extra Fields |
    |-------|-------------------|--------------|
    | **Football (Soccer)** | 1st Half, 2nd Half, Total, Corners, Yellow Cards (YC), Red Cards (RC) | `period` (1H, 2H, HT, ET, PEN) |
    | **Tennis** | Set 1, Set 2, Set 3, Set 4, Set 5, Total | `home_game_score`/`away_game_score` (0, 15, 30, 40, AD), `is_tiebreak`, `home_serving`/`away_serving` |
    | **Basketball (NBA)** | Q1, Q2, Q3, Q4, OT, Total | `period` (Q1-Q4, OT1-OT3) |
    | **Ice Hockey (NHL)** | P1, P2, P3, OT, Total | `home_suspend`/`away_suspend` (power play) |
    | **American Football (NFL)** | Q1, Q2, Q3, Q4, OT, Total | `period`, `down_and_distance` |
    | **Baseball (MLB)** | Inn 1-9+, Total, Hits, Errors | `period` (Top/Bot 1-9+), `bases`, `outs` |
    | **Volleyball** | Set 1-5, Points, Total | `home_serving`/`away_serving` |
    | **Table Tennis** | Set 1-7, Total | `home_serving`/`away_serving` |
    | **CS2 / Valorant** | Map 1, Map 2, Map 3, Rounds | `current_map`, `map_score`, `round_score` |
    | **Dota 2 / LoL** | Game 1, Game 2, Game 3, Total | `current_game`, `game_duration` |
    | **Cricket** | Innings 1, Innings 2, Overs, Wickets | `run_rate`, `target` |
    | **Handball** | 1st Half, 2nd Half, Total | `period` |
    | **Rugby** | 1st Half, 2nd Half, Total | `period`, `try_count` |
    | **Darts** | Set/Leg scores | `current_set`, `current_leg` |
    | **Snooker** | Frame scores, Total | `current_frame`, `frame_score` |
    | **MMA / Boxing** | Round 1-12, Total | `current_round` |

    ## Prematch Odds
    - Prematch events include full market odds (up to 1,000+ markets per event on major leagues)
    - Odds are refreshed via incremental cursor — 10 prematch games per 300ms cycle (~10-30s full pass depending on total game count)
    - Detail data (markets, scoreboards) polled every ~16-20s per event
    - All odds formats supported: `decimal`, `american`, `fractional`

    ### Fixture Horizon
    Prematch fixture depth is **league-dependent** — major leagues (e.g. Premier League, NBA) typically appear further ahead than niche or regional events. There is no fixed global limit; it reflects when the data provider publishes upcoming matches. Use `GET /v1/events?starts_within=2h` or `starts_within=1d` to filter by time window. Every event includes a `commence_time` (ISO 8601) field for precise scheduling.


    ## Market Suspension & Locked Odds
    Individual selections or entire markets can become temporarily **locked** (`is_locked: true`).
    This happens during:
    - **Goal/score events** — markets lock for 30-60 seconds while odds are recalculated
    - **Dangerous moments** — e.g. penalty kicks, red cards, break points in tennis
    - **End of game** — as a match approaches final minutes, the provider progressively locks markets
    - **Half-time / period breaks** — some markets lock between periods

    When `is_locked: true`, the odds value is still present (last known value) but the selection
    **cannot be bet on**. Your UI should grey out or disable these selections.

    ### Empty Markets (End of Game)
    Near the end of a live match, the `markets` array may become **empty** (`[]`) or return
    with **all outcomes locked**. This is normal — the provider stops accepting bets in the
    final minutes. The `markets_count` field will reflect `0` in this case.

    After the game finishes (`status: "ended"`), markets are no longer returned.
    Use `/v1/events/{eventId}/result` or `/v1/settlements` for final settlement data.

    ### ended Game Snapshot (Endgame Data)
    When a game finishes (or is cancelled/postponed), the API archives the final score permanently and provides settlement data in a rolling window. This applies to **all sports & esports** (Soccer, NBA, CS2, LoL, Tennis, etc.).

    **Two tiers of post-game data:**

    | Endpoint | Data | Retention |
    |----------|------|-----------|
    | `/v1/events/{eventId}/result` | Final score, status | **Permanent** — archived indefinitely |
    | `/v1/settlements` | Market resolutions (won/lost/refund), team names, scores, logos | **Recent** — poll regularly after game end to capture all market resolutions as they arrive gradually |
    | `/v1/bets/check` | Bet resolution against settlement data | **Recent** (same as settlements) |

    > **Important**: Process settlements promptly by polling every 60 seconds. Final scores remain permanently available via `/v1/events/{eventId}/result`.

    ## Team Side Identification
    Market outcomes include an optional `team_side` field:
    - `"home"` — this selection refers to the home team
    - `"away"` — this selection refers to the away team
    - `null` or absent — neutral selection (Draw, Over/Under totals, etc.)

    This is useful for mapping selections to team names without parsing the `label` string.
    Available on 1X2, Handicap, Double Chance, and similar two-sided markets.


    ### Prematch → Live Transition
    Detected automatically. When a game kicks off, its status changes from `prematch` to `live` and it appears in `/v1/live`. No action needed from the developer.


    All IDs, scores, and timestamps in endpoint examples are **synthetic**. Use /v1/events to discover real event IDs.

  version: "1.0.0"
  termsOfService: https://docs.fieldfunded.com/terms
  contact:
    name: FieldFunded API Support
    url: https://docs.fieldfunded.com
    email: support@fieldfunded.com

servers:
  - url: https://api.fieldfunded.com
    description: Production

tags:
  - name: Sports
    description: Discover available sports and leagues
  - name: Events
    description: Browse and search sports events
  - name: Live
    description: Real-time live event data and scores
  - name: Odds
    description: Current betting odds
  - name: Results
    description: Automatic match settlement and outcomes
  - name: Settlement
    description: |
      Fully automatic bet settlement — markets resolve on their own as soon as a game ends. No developer action required.
      Also includes bet-check endpoints: submit your users' selections to verify outcomes against automatic results.
      Supports single bets and multi-leg parlays/combos.
      The 48-hour rule applies: postponed/suspended games that don't resume within 48h are auto-refunded.

      #### Accurate Settlement Using IDs
      Every market and selection has a unique ID (`market_id` and `selection_id`). Use these IDs for bet placement and settlement to guarantee 100% accuracy. Market names and labels are also available for display purposes.
  - name: Outrights
    description: |
      Season-level winner markets (e.g., League Winner).
      Updated every 3 hours.
  - name: System
    description: API health and status
  - name: Usage Monitoring
    description: Track your API usage, quota status, and active warnings. Data available via the Developer Portal at `/portal`.

paths:
  /v1/usage:
    get:
      tags: [Usage Monitoring]
      summary: Usage Statistics — Current month quota and daily breakdown
      description: |
        Returns your current API usage statistics including today's requests, monthly quota consumption,
        remaining requests, average response time, and error counts. Also includes a 30-day daily breakdown.

        > **Note**: This endpoint counts towards your rate limit quota.
      operationId: getUsage
      responses:
        "200":
          description: The current API quota usage and daily request breakdown for your active plan.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tier:
                    type: string
                    example: "pro"
                  limits:
                    type: object
                    properties:
                      per_second: { type: integer, example: 30 }
                      per_hour: { type: integer, example: 30000 }
                      per_month: { type: integer, example: 1000000 }
                  current:
                    type: object
                    properties:
                      today: { type: integer, example: 4521 }
                      this_month: { type: integer, example: 89432 }
                      month_remaining: { type: integer, example: 910568 }
                      month_percent: { type: number, example: 8.9 }
                      avg_response_ms: { type: integer, example: 42 }
                      errors_today:
                        type: object
                        properties:
                          client: { type: integer, example: 3, description: "Includes 400 Bad Request from invalid parameters" }
                          server: { type: integer, example: 0 }
                      warning:
                        type: object
                        nullable: true
                        properties:
                          level: { type: string, enum: [info, warning, critical, blocked] }
                          message: { type: string }
                          percent: { type: number }
                  daily_breakdown:
                    type: array
                    items:
                      type: object
                      properties:
                        date: { type: string, example: "2026-04-15" }
                        requests: { type: integer, example: 4521 }
                        errors: { type: integer, example: 12 }
              example:
                tier: "pro"
                limits:
                  per_second: 30
                  per_hour: 30000
                  per_month: 1000000
                current:
                  today: 4521
                  this_month: 89432
                  month_remaining: 910568
                  month_percent: 8.9
                  avg_response_ms: 42
                  errors_today:
                    client: 3
                    server: 0
                  warning:
                    level: info
                    message: "You have used 80% of your monthly quota."
                    percent: 80
                daily_breakdown:
                  - date: "2026-04-15"
                    requests: 4521
                    errors: 12
                  - date: "2026-04-14"
                    requests: 3988
                    errors: 9

  /v1/usage/endpoints:
    get:
      tags: [Usage Monitoring]
      summary: Endpoint Breakdown — Request volume by endpoint
      description: |
        Returns request counts per endpoint for the current billing month, sorted by volume (highest first).

        Use this to identify which endpoints consume the most quota and optimize your polling strategy accordingly.
        Pairs well with `/v1/usage` for a complete picture of your API consumption.
      operationId: getUsageEndpoints
      responses:
        "200":
          description: A detailed breakdown of API requests per endpoint for the current billing cycle.
          content:
            application/json:
              schema:
                type: object
                properties:
                  endpoints:
                    type: array
                    items:
                      type: object
                      properties:
                        path: { type: string, example: "/events" }
                        count: { type: integer, example: 3200 }
                  period:
                    type: string
                    example: "current_month"
              example:
                endpoints:
                  - path: "/events"
                    count: 3200
                  - path: "/scores"
                    count: 1850
                  - path: "/settlements"
                    count: 740
                period: "current_month"

  /v1/usage/warnings:
    get:
      tags: [Usage Monitoring]
      summary: Active Warnings — Quota thresholds and error alerts
      description: |
        Returns any active warnings for your API key, including quota threshold alerts and elevated error rate notifications.

        Warning levels: `info` (approaching limit), `warning` (>80% consumed), `critical` (>95% consumed), `blocked` (quota exhausted).
        Poll this periodically to implement proactive alerting in your application before hitting hard limits.
      operationId: getUsageWarnings
      responses:
        "200":
          description: A list of active quota alerts and warning thresholds for your account.
          content:
            application/json:
              schema:
                type: object
                properties:
                  warnings:
                    type: array
                    items:
                      type: object
                      properties:
                        level: { type: string, enum: [info, warning, critical, blocked] }
                        message: { type: string }
                        percent: { type: number }
              example:
                warnings:
                  - level: warning
                    message: "Monthly quota usage is above 80%."
                    percent: 83.4
                  - level: info
                    message: "Elevated server error rate detected today"

  /v1/ping:
    get:
      tags: [System]
      summary: Ping — Zero-cost latency and uptime check
      description: |
        Ultra-lightweight endpoint for uptime monitoring. Returns immediately with minimal payload.
        
        > This endpoint does not count against your monthly quota. Fixed rate limit: 2 req/s, 120 req/h (equal for all plans).
      operationId: ping
      responses:
        "200":
          description: A lightweight confirmation that the API is reachable and responding.
          content:
            application/json:
              schema:
                type: object
                properties:
                  pong:
                    type: boolean
                    example: true
                  timestamp:
                    type: integer
                    description: Unix timestamp in milliseconds
                    example: 1718400000000
              example:
                pong: true
                timestamp: 1777046400000

  /v1/health:
    get:
      tags: [System]
      summary: Health — Service connectivity and data freshness
      description: |
        Reports the health of the API, including service connectivity,
        data freshness, and uptime. Returns HTTP 200 when healthy,
        HTTP 503 when degraded. Use this for monitoring dashboards.
        
        > This endpoint does not count against your monthly quota. Fixed rate limit: 2 req/s, 120 req/h (equal for all plans).
      operationId: getHealth
      responses:
        "200":
          description: Real-time system health metrics, latency data, and active event counts.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    enum: [healthy, degraded, unhealthy]
                    example: healthy
                  version:
                    type: string
                    example: "1.0.0"
                  uptime_seconds:
                    type: integer
                    example: 86400
                  timestamp:
                    type: string
                    format: date-time
                    example: "2026-04-14T18:00:00.000Z"
                  services:
                    type: object
                    properties:
                      redis:
                        type: object
                        properties:
                          status:
                            type: string
                            enum: [connected, degraded, disconnected, not_configured]
                            example: connected
                      data_pipeline:
                        type: object
                        properties:
                          status:
                            type: string
                            enum: [active, stale, down, no_data]
                            example: active
                          last_update_seconds_ago:
                            type: integer
                            example: 12
                          total_events:
                            type: integer
                            example: 1847
              example:
                status: healthy
                version: "1.0.0"
                uptime_seconds: 86400
                timestamp: "2026-04-14T18:00:00.000Z"
                services:
                  redis:
                    status: connected
                    latency_ms: 9
                  data_pipeline:
                    status: active
                    last_update_seconds_ago: 12
                    total_events: 1847
        "503":
          description: System is degraded or unhealthy
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/sports:
    get:
      tags: [Sports]
      summary: Get Sports — 30+ sports and esports with live event counts
      description: |
        Returns all sports that currently have active events (live or prematch). Includes event counts per sport.

        The endpoint provides events counts and metadata for all active sports in our global catalog. Sorting is based on real-time event volume.

        Use the `key` field (e.g. `soccer`, `basketball`, `cs2`) as the `?sport=` filter on other endpoints:
        `/v1/events?sport=soccer`, `/v1/live?sport=basketball`, `/v1/scores?sport=cs2`, etc.
      operationId: getSports
      responses:
        "200":
          description: A complete catalog of active sports and esports, including real-time event counts and visual assets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  sports:
                    type: array
                    items:
                      $ref: "#/components/schemas/Sport"
                  total:
                    type: integer
                    example: 20
              example:
                sports:
                  - key: soccer
                    name: Soccer
                    active_events: 142
                    live_events: 10
                    prematch_events: 132
                    is_esport: false
                    has_outrights: true
                  - key: basketball
                    name: Basketball
                    active_events: 38
                    live_events: 4
                    prematch_events: 34
                    is_esport: false
                  - key: cs2
                    name: CS2
                    active_events: 12
                    live_events: 2
                    prematch_events: 10
                    is_esport: true
                total: 32
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/events:
    get:
      tags: [Events]
      summary: Get Events — Real-time odds with 300ms refresh (filterable)
      description: |
        Returns a paginated list of sports events. Filter by sport, league, or status.
        Results are sorted by start time (live events first, then upcoming).

        **Note**: By default, ended and cancelled events are excluded. Use `?status=all` to include all statuses, or `?status=ended` to retrieve only ended events.
      operationId: getEvents
      parameters:
        - name: sport
          in: query
          description: Filter by sport key (e.g. `soccer`, `basketball`, `cs2`). Use `all` or omit for all sports.
          schema:
            type: string
            example: soccer
        - name: status
          in: query
          description: Filter by event status
          schema:
            type: string
            enum: [live, prematch, all]
            default: all
        - name: league
          in: query
          description: |
            Filter by league. Supports exact slug match (`premier-league`) or partial name match (`Premier`).
            Use `/v1/leagues` to discover available league slugs.
          schema:
            type: string
            example: premier-league
        - name: country
          in: query
          description: Filter by country (exact or partial match, case-insensitive)
          schema:
            type: string
            example: england
        - name: date
          in: query
          description: "Filter events on a specific day (UTC). Format: YYYY-MM-DD. Cannot combine with `from`/`to`."
          schema:
            type: string
            format: date
            example: "2026-04-15"
        - name: from
          in: query
          description: "Filter events starting from this date (UTC inclusive). Format: YYYY-MM-DD. Use with `to` for a range."
          schema:
            type: string
            format: date
            example: "2026-04-15"
        - name: to
          in: query
          description: "Filter events up to this date (UTC inclusive). Format: YYYY-MM-DD. Use with `from` for a range."
          schema:
            type: string
            format: date
            example: "2026-04-17"
        - name: starts_within
          in: query
          description: |
            Filter upcoming events starting within a time window from now.
            Format: `{number}{unit}` where unit is `m` (minutes), `h` (hours), or `d` (days).
            Only returns prematch events — excludes already-live games.
          schema:
            type: string
            example: "60m"
        - name: limit
          in: query
          description: Maximum number of events to return
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
        - name: offset
          in: query
          description: Number of events to skip (for pagination)
          schema:
            type: integer
            minimum: 0
            default: 0
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A paginated list of live and upcoming sports events, including available betting markets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: "#/components/schemas/Event"
                  total:
                    type: integer
                    description: Total events matching filters (before pagination)
                  limit:
                    type: integer
                  offset:
                    type: integer
              example:
                events:
                  - id: "87654321"
                    sport:
                      key: soccer
                      name: Soccer
                    league:
                      slug: premier-league
                      name: Premier League
                      country: England
                    home_team: Arsenal
                    away_team: Chelsea
                    home_logo: https://api.fieldfunded.com/api/logo/t-38
                    away_logo: https://api.fieldfunded.com/api/logo/t-42
                    status: live
                    start_time: "2026-04-12T15:00:00Z"
                    score:
                      home: 2
                      away: 1
                    clock: "67:10 2nd half"
                    period: "2nd Half"
                    odds:
                      home: 1.45
                      draw: 4.50
                      away: 6.00
                    odds_format: "decimal"
                    markets_count: 72
                    updated_at: "2026-04-12T15:45:30.000Z"
                total: 842
                limit: 50
                offset: 0
        "400":
          description: Invalid request body (including invalid `odds` values)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                invalid_odds:
                  summary: Invalid odds in one selection
                  value:
                    error: bad_request
                    message: "Selection at index 0 has invalid 'odds'. Use a decimal number >= 1 when provided."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/events/{eventId}:
    get:
      tags: [Events]
      summary: Event Details — Full market depth (1,000+ markets per event)
      description: |
        Returns complete event details including all available betting markets, 
        detailed scoreboard with period scores, and sport-specific data 
        (serving indicators for tennis, power play for hockey, etc.).
      operationId: getEventDetails
      parameters:
        - name: eventId
          in: path
          required: true
          description: "Unique event identifier. Use GET /v1/events to discover active IDs."
          schema:
            type: string
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: Deep, comprehensive details for the specified event, including all available betting markets.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EventDetail"
              example:
                id: "87654321"
                sport:
                  key: soccer
                  name: Soccer
                league:
                  slug: premier-league
                  name: Premier League
                  country: England
                home_team: Arsenal
                away_team: Chelsea
                home_logo: "https://api.fieldfunded.com/api/logo/t-38"
                away_logo: "https://api.fieldfunded.com/api/logo/t-42"
                status: live
                start_time: "2026-04-12T15:00:00Z"
                score:
                  home: 2
                  away: 1
                clock: "67:10 2nd half"
                period: "2nd Half"
                odds:
                  home: 1.45
                  draw: 4.50
                  away: 6.00
                odds_format: "decimal"
                markets_count: 72
                scoreboard:
                  headers: ["", "1st", "2nd", "T"]
                  home: ["", "1", "1", "2"]
                  away: ["", "0", "1", "1"]
                markets:
                  - key: "1x2"
                    name: "Match Winner"
                    outcomes:
                      - label: Home
                        odds: 1.45
                        is_locked: false
                        team_side: home
                      - label: Draw
                        odds: 4.50
                        is_locked: false
                        team_side: null
                      - label: Away
                        odds: 6.00
                        is_locked: false
                        team_side: away
                  - key: "over_under_2_5"
                    name: "Over/Under 2.5"
                    outcomes:
                      - label: "Over 2.5"
                        odds: 1.60
                        is_locked: false
                        team_side: null
                      - label: "Under 2.5"
                        odds: 2.30
                        is_locked: false
                        team_side: null
                updated_at: "2026-04-12T15:67:10Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/events/{eventId}/odds:
    get:
      tags: [Odds]
      summary: Event Odds — Lightweight odds-only payload (60-70% smaller)
      description: |
        Returns current odds for all markets of a specific event without the full event envelope (scores, metadata, etc.).

        This is a **lightweight, odds-only** alternative to `/v1/events/{eventId}` — ideal for high-frequency polling
        when you already have the event metadata cached and only need fresh odds.
        Typically 60–70% smaller payload than full event details.
      operationId: getEventOdds
      parameters:
        - name: eventId
          in: path
          required: true
          description: "Unique event identifier. Use GET /v1/events to discover active IDs."
          schema:
            type: string
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A lightweight payload containing only the current odds and market statuses for the specified event.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                  status:
                    type: string
                  markets:
                    type: array
                    items:
                      $ref: "#/components/schemas/Market"
                  updated_at:
                    type: string
                    format: date-time
              example:
                id: "87654321"
                status: live
                markets:
                  - key: match_winner
                    name: Match Winner
                    outcomes:
                      - label: Home
                        odds: 1.72
                        is_locked: false
                        team_side: home
                      - label: Draw
                        odds: 3.90
                        is_locked: false
                        team_side: null
                      - label: Away
                        odds: 5.10
                        is_locked: false
                        team_side: away
                  - key: over_under_2_5
                    name: Over/Under 2.5
                    outcomes:
                      - label: "Over 2.5"
                        odds: 1.87
                        is_locked: false
                        team_side: null
                      - label: "Under 2.5"
                        odds: 1.95
                        is_locked: false
                        team_side: null
                updated_at: "2026-04-14T18:03:10.000Z"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/events/{eventId}/result:
    get:
      tags: [Results]
      summary: Event Result — Official final score and match status
      description: |
        Returns the official score/state for an event result. Available automatically as soon as the game finishes — no developer action required.
        This endpoint is **score-only** and does not return market-level resolutions.
        For market outcomes (`won`/`lost`/`refund` with `market_id` and `selection_id`), use `/v1/settlements`.
        
        **Response states:**
        - `status: "ended"` — Official score finalised. Market-level details are available in `/v1/settlements`.
        - `status: "not_ended"` — Match is currently in progress. Use `/v1/scores` or `/v1/events/{eventId}` for real-time updates.
        - `status: "disrupted"` (Cancelled, Postponed, etc.) — Match interrupted. Results successfully archived.
        
        Official match scores are permanently archived in our database and remain available via this endpoint indefinitely.
      operationId: getEventResult
      parameters:
        - name: eventId
          in: path
          required: true
          description: "Unique event identifier. Use GET /v1/events to discover active IDs."
          schema:
            type: string
      responses:
        "200":
          description: |
            Event result. Check `status` field:
            - `ended` — Event finalised (market-level outcomes available via `/v1/settlements`)
            - `not_ended` — Game still in progress or not started
            - `cancelled` / `abandoned` / `retired` / `walkover` / `postponed` / `suspended` / `interrupted` / `delayed` — Professional non-final states
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Result"
              examples:
                ended:
                  summary: Ended event (score-only response, including 0-0)
                  value:
                    id: "87654321"
                    status: ended
                    score:
                      home: 0
                      away: 0
                    ended_at: "2026-04-12T16:55:00Z"
                not_ended:
                  summary: Match in progress
                  value:
                    id: "87654321"
                    status: not_ended
                    message: "Match is currently in progress. Use /v1/scores or /v1/events/{id} for real-time updates."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          description: Event not found — the event ID does not exist
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/live:
    get:
      tags: [Live]
      summary: Live Events — All in-play matches with scores and headline odds
      description: |
        Returns all currently live in-play events across all sports. This is a **lightweight listing endpoint** —
        each event includes real-time scores, match clocks, event metadata, summary 1X2 odds (`odds.home`,
        `odds.draw`, `odds.away`), and a `markets_count` field, but **does NOT include the full `markets`
        array** (no individual market selections, player-prop markets (including pre-match and dynamic live/in-play variants), or deep odds).

        This is functionally equivalent to `GET /v1/events?status=live` — a convenience alias that pre-filters to live games only.

        > **For full market depth** (all 1,000+ markets, selections, scoreboards, sport-specific data),
        > fetch individual events via `GET /v1/events/{eventId}` or use `POST /v1/events/batch` for up to 20 events at once.

        #### Typical response size
        ~1–3 KB per event (vs. 50–200 KB with full markets on the detail endpoint).

        #### Recommended usage pattern
        Poll `/v1/live` every 5–10 seconds to discover which games are in-play and get headline odds, then fetch
        `/v1/events/{eventId}` for the specific games where you need full market depth.
      operationId: getLiveEvents
      parameters:
        - name: sport
          in: query
          description: Filter by sport key
          schema:
            type: string
            example: soccer
        - name: limit
          in: query
          description: "Maximum number of live events to return (default: all, max: 200)"
          schema:
            type: integer
            minimum: 1
            maximum: 200
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A real-time list of all currently live sporting events and their dynamically updating odds.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: "#/components/schemas/Event"
                  total:
                    type: integer
              example:
                events:
                  - id: "749302"
                    sport: { key: soccer, name: Soccer }
                    league: { slug: premier-league, name: Premier League, country: England }
                    home_team: Arsenal
                    away_team: Chelsea
                    home_logo: "https://api.fieldfunded.com/api/logo/t-38"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-42"
                    status: live
                    start_time: "2026-04-12T15:00:00Z"
                    score: { home: 2, away: 1 }
                    clock: "67:10"
                    period: "2nd Half"
                    odds:
                      home: 1.45
                      draw: 4.50
                      away: 6.00
                    odds_format: "decimal"
                    markets_count: 72
                    updated_at: "2026-04-12T15:45:30.000Z"
                total: 64
        "400":
          description: Invalid settlements filters or pagination parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                too_many_event_ids:
                  summary: event_ids exceeds max 50
                  value:
                    error: bad_request
                    message: Maximum 50 event ids are allowed for settlements filters
                cursor_offset_conflict:
                  summary: cursor and offset were sent together
                  value:
                    error: bad_request
                    message: "Use either 'cursor' or 'offset', not both."
                invalid_cursor:
                  summary: malformed cursor token
                  value:
                    error: bad_request
                    message: "Invalid 'cursor'. Expected base64url encoded { ended_at, event_id }."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/featured:
    get:
      tags: [Events]
      summary: Featured Games — Top matches from priority leagues (PL, NBA, NFL)
      description: |
        Returns top games from **priority leagues** —  the biggest matches happening now
        or coming up soon. Live games are shown first, followed by nearest upcoming.

        Priority leagues: Premier League, La Liga, Champions League, Europa League,
        Bundesliga, Serie A, Ligue 1, NBA, NFL, MLB, NHL.
        For major US leagues, featured selection includes season-phase competitions in general
        (e.g., Preseason, Regular Season, Playoffs, Finals) when available.

        Perfect for building a homepage hero section or "Top Matches" widget.

        **Default mode** returns summary odds (home/draw/away) and metadata — no full market depth.
        Set `markets=true` to include complete market data (same depth as `/v1/events/{eventId}`).

        ⚠️ With `markets=true`, response payloads can be significantly larger (1–5 MB+).
        Use smaller `limit` values (5–10) when markets are enabled.
      operationId: getFeaturedGames
      parameters:
        - name: limit
          in: query
          description: "Max number of featured games to return (default: 15, max: 30)"
          schema:
            type: integer
            default: 15
            maximum: 30
        - name: markets
          in: query
          description: "Include full market depth for each game (default: false). When true, each event includes all available markets, scoreboard, and sport-specific data."
          schema:
            type: boolean
            default: false
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A curated list of top-tier matches from priority leagues, sorted with live events first.
          content:
            application/json:
              schema:
                type: object
                properties:
                  featured:
                    type: array
                    items:
                      $ref: "#/components/schemas/Event"
                  total:
                    type: integer
                  markets_included:
                    type: boolean
                    description: "Whether full market data is included in the response"
                  priority_leagues:
                    type: array
                    items:
                      type: string
                    description: "List of priority league names included in the selection"
              example:
                featured:
                  - id: "627126"
                    home_team: Boston Celtics
                    away_team: Philadelphia 76ers
                    home_logo: "https://api.fieldfunded.com/api/logo/t-3422"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-3420"
                    status: live
                    score: { home: 87, away: 92 }
                    clock: "Q3 04:22"
                    period: "3rd Quarter"
                    odds:
                      home: 1.30
                      draw: null
                      away: 3.40
                    odds_format: "decimal"
                    sport: { key: basketball, name: Basketball }
                    league: { slug: nba, name: NBA, country: USA }
                    start_time: "2026-04-12T19:00:00Z"
                    markets_count: 85
                    updated_at: "2026-04-12T20:15:30.000Z"
                total: 12
                markets_included: false
                priority_leagues: ["Premier League", "La Liga", "Champions League", "NBA", "NFL", "MLB", "NHL"]
        "400":
          description: Invalid settlements filters or pagination parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                too_many_event_ids:
                  summary: event_ids exceeds max 50
                  value:
                    error: bad_request
                    message: Maximum 50 event ids are allowed for settlements filters
                cursor_offset_conflict:
                  summary: cursor and offset were sent together
                  value:
                    error: bad_request
                    message: "Use either 'cursor' or 'offset', not both."
                invalid_cursor:
                  summary: malformed cursor token
                  value:
                    error: bad_request
                    message: "Invalid 'cursor'. Expected base64url encoded { ended_at, event_id }."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/leagues:
    get:
      tags: [Sports]
      summary: Get Leagues — Active competitions with event counts by sport
      description: |
        Returns all active leagues with event counts, grouped by sport.
        Each league includes a `slug` that can be used as a stable identifier for filtering via `/v1/events?league={slug}`.

        > [!NOTE]
        > **Active Discovery**: This endpoint returns only the leagues that currently have active (live or upcoming) events. While the platform supports **thousands** of total leagues, the real-time response is scoped to current market activity to ensure all returned data is immediately actionable.
      operationId: getLeagues
      parameters:
        - name: sport
          in: query
          description: Filter leagues by sport key
          schema:
            type: string
            example: soccer
      responses:
        "200":
          description: A list of available leagues and tournaments, filterable by sport.
          content:
            application/json:
              schema:
                type: object
                properties:
                  leagues:
                    type: array
                    items:
                      type: object
                      properties:
                        slug:
                          type: string
                          description: URL-friendly league identifier. Use this in `?league=` filter.
                          example: premier-league
                        name:
                          type: string
                          example: Premier League
                        country:
                          type: string
                          example: England
                        sport:
                          type: object
                          properties:
                            key:
                              type: string
                            name:
                              type: string
                        active_events:
                          type: integer
                        live_events:
                          type: integer
                  total:
                    type: integer
              example:
                leagues:
                  - slug: premier-league
                    name: Premier League
                    country: England
                    sport: { key: soccer, name: Soccer }
                    active_events: 22
                    live_events: 4
                  - slug: nba-regular-season
                    name: "NBA, Regular Season"
                    country: USA
                    sport: { key: basketball, name: Basketball }
                    active_events: 25
                    live_events: 2
                  - slug: la-liga
                    name: "La Liga"
                    country: Spain
                    sport: { key: soccer, name: Soccer }
                    active_events: 18
                    live_events: 5
                  - slug: bundesliga
                    name: "Bundesliga"
                    country: Germany
                    sport: { key: soccer, name: Soccer }
                    active_events: 15
                    live_events: 3
                  - slug: serie-a
                    name: "Serie A"
                    country: Italy
                    sport: { key: soccer, name: Soccer }
                    active_events: 13
                    live_events: 4
                  - slug: nhl-regular-season
                    name: "NHL, Regular Season"
                    country: USA
                    sport: { key: ice-hockey, name: Ice Hockey }
                    active_events: 12
                    live_events: 2
                  - slug: nfl-regular-season
                    name: "NFL, Regular Season"
                    country: USA
                    sport: { key: american-football, name: American Football }
                    active_events: 16
                    live_events: 1
                total: 2134
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/markets:
    get:
      tags: [Sports]
      summary: Market Discovery — All available market types grouped by sport
      description: |
        Discovers all known market types currently available, grouped by sport.
        Samples active events to extract available market names and keys.
        Useful for building market selectors, mapping market keys to display names, and understanding coverage.
      operationId: getMarkets
      parameters:
        - name: sport
          in: query
          description: Filter markets by sport key
          schema:
            type: string
            example: soccer
      responses:
        "200":
          description: A catalog of supported betting market types, organized by sport.
          content:
            application/json:
              schema:
                type: object
                properties:
                  markets:
                    type: object
                    additionalProperties:
                      type: array
                      items:
                        type: object
                        properties:
                          key:
                            type: string
                            description: Normalized market key (lowercase, snake_case)
                            example: match_winner
                          name:
                            type: string
                            description: Display name of the market
                            example: Match Winner
                          outcomes_count:
                            type: integer
                            description: Number of outcomes in this market (e.g. 3 for 1X2)
                            example: 3
                  total_unique:
                    type: integer
                    description: Total number of unique market types found
              example:
                markets:
                  soccer:
                    - { key: match_winner, name: Match Winner, outcomes_count: 3 }
                    - { key: over_under_2_5, name: "Over/Under 2.5", outcomes_count: 2 }
                    - { key: both_teams_to_score, name: Both Teams to Score, outcomes_count: 2 }
                  basketball:
                    - { key: match_winner, name: Match Winner, outcomes_count: 2 }
                    - { key: total_points, name: Total Points, outcomes_count: 2 }
                total_unique: 200
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/scores:
    get:
      tags: [Live]
      summary: Live Scores — Real-time scoreboards optimized for high-frequency polling
      description: |
        Returns live scores for all in-play events. Matches that recently ended are kept in the response for a 5-minute buffer window so your polling system can safely capture the final score before it is removed.
        Lightweight endpoint optimized for frequent polling — returns only score data, no markets.
      operationId: getScores
      parameters:
        - name: sport
          in: query
          description: Filter by sport key
          schema:
            type: string
            example: soccer
        - name: limit
          in: query
          description: "Maximum number of live events to return (default: all, max: 200)"
          schema:
            type: integer
            minimum: 1
            maximum: 200
      responses:
        "200":
          description: A lightweight feed of live scores and match timers, optimized for high-frequency polling.
          content:
            application/json:
              schema:
                type: object
                properties:
                  scores:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: string
                        home_team:
                          type: string
                        away_team:
                          type: string
                        score:
                          $ref: "#/components/schemas/Score"
                        status:
                          type: string
                          enum: [live, ended]
                        clock:
                          type: string
                        period:
                          type: string
                        sport:
                          type: string
                  total:
                    type: integer
              example:
                scores:
                  - id: "87654321"
                    home_team: Arsenal
                    away_team: Chelsea
                    score: { home: 2, away: 1 }
                    status: live
                    clock: "67:10"
                    period: "2nd half"
                    sport: soccer
                total: 842
        "400":
          description: Invalid settlements filters or pagination parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                too_many_event_ids:
                  summary: event_ids exceeds max 50
                  value:
                    error: bad_request
                    message: Maximum 50 event ids are allowed for settlements filters
                cursor_offset_conflict:
                  summary: cursor and offset were sent together
                  value:
                    error: bad_request
                    message: "Use either 'cursor' or 'offset', not both."
                invalid_cursor:
                  summary: malformed cursor token
                  value:
                    error: bad_request
                    message: "Invalid 'cursor'. Expected base64url encoded { ended_at, event_id }."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/search:
    get:
      tags: [Events]
      summary: Search — Find events by team or league name (partial match)
      description: |
        Search for events by team name or league name. Returns matching events
        across all sports. Supports partial matching.
      operationId: searchEvents
      parameters:
        - name: q
          in: query
          required: true
          description: "Search query (min 2 characters). Matches against home team, away team, and league names."
          schema:
            type: string
            minLength: 2
            example: Arsenal
        - name: limit
          in: query
          description: Maximum results to return
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 25
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A list of sports events matching the provided search query.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: "#/components/schemas/Event"
                  total:
                    type: integer
                  query:
                    type: string
              example:
                events:
                  - id: "87654321"
                    sport: { key: soccer, name: Soccer }
                    league: { slug: premier-league, name: Premier League, country: England }
                    home_team: Arsenal
                    away_team: Chelsea
                    home_logo: "https://api.fieldfunded.com/api/logo/t-38"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-42"
                    status: live
                    start_time: "2026-04-12T15:00:00Z"
                    score: { home: 2, away: 1 }
                    clock: "67:10"
                    period: "2nd Half"
                    odds:
                      home: 1.45
                      draw: 4.50
                      away: 6.00
                    odds_format: "decimal"
                    markets_count: 72
                    updated_at: "2026-04-12T15:45:30.000Z"
                  - id: "87654322"
                    sport: { key: baseball, name: Baseball }
                    league: { slug: mlb, name: "MLB", country: USA }
                    home_team: St. Louis Cardinals
                    away_team: Los Angeles Dodgers
                    home_logo: "https://api.fieldfunded.com/api/logo/t-3632"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-3638"
                    status: prematch
                    start_time: "2026-04-14T20:10:00Z"
                    score: { home: 0, away: 0 }
                    clock: null
                    period: ""
                    odds:
                      home: 2.10
                      draw: null
                      away: 1.75
                    odds_format: "decimal"
                    markets_count: 120
                    updated_at: "2026-04-12T18:00:00.000Z"
                total: 42
                query: "Arsenal"
        "400":
          description: Query too short
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/events/batch:
    post:
      tags: [Events]
      summary: Batch Events — Full market depth for up to 20 events in one request
      description: |
        Fetch full details for up to 20 events in a single request. More efficient than individual requests.
        Returns **400 Bad Request** if more than 20 IDs are provided.

        **Full Market Depth**: Each event in the batch response contains the **same complete market data** as `/v1/events/{eventId}` — up to 1,000+ markets per event on major leagues (NBA, NFL, Premier League). There is no market capping or reduction in batch mode.

        **Performance Advisory**: Batching 20 market-heavy events (e.g., live NBA games with 700+ selections each) can produce very large response payloads (5-15 MB+). For optimal performance:
        - Use smaller batch sizes (5-10 IDs) when fetching market-intensive events
        - Use `/v1/scores` for lightweight status polling (no markets), then batch-fetch only the events you need full odds for
        - Use `/v1/events/{eventId}` for single-event deep dives
      operationId: getEventsBatch
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [ids]
              properties:
                ids:
                  type: array
                  items:
                    type: string
                  maxItems: 20
                  description: "Array of event IDs (max 20). Use GET /v1/events to discover active IDs."
      parameters:
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: A dictionary of comprehensive event details mapped by their respective event IDs.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: object
                    additionalProperties:
                      $ref: "#/components/schemas/EventDetail"
                  found:
                    type: integer
                  requested:
                    type: integer
              example:
                events:
                  "87654321":
                    id: "87654321"
                    sport: { key: soccer, name: Soccer }
                    league: { slug: premier-league, name: Premier League, country: England }
                    home_team: Arsenal
                    away_team: Chelsea
                    home_logo: "https://api.fieldfunded.com/api/logo/t-38"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-42"
                    status: live
                    start_time: "2026-04-12T15:00:00Z"
                    score: { home: 2, away: 1 }
                    clock: "67:10"
                    period: "2nd Half"
                    odds:
                      home: 1.45
                      draw: 4.50
                      away: 6.00
                    odds_format: "decimal"
                    markets_count: 72
                    markets:
                      - key: "1x2"
                        name: "Match Winner"
                        outcomes:
                          - label: Home
                            odds: 1.45
                    updated_at: "2026-04-12T15:45:30.000Z"
                  "87654322":
                    id: "87654322"
                    sport: { key: soccer, name: Soccer }
                    league: { slug: la-liga, name: La Liga, country: Spain }
                    home_team: Real Madrid
                    away_team: Barcelona
                    home_logo: "https://api.fieldfunded.com/api/logo/t-2829"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-2817"
                    status: prematch
                    start_time: "2026-04-14T20:00:00Z"
                    score: { home: 0, away: 0 }
                    clock: null
                    period: ""
                    odds:
                      home: 2.10
                      draw: 3.40
                      away: 3.50
                    odds_format: "decimal"
                    markets_count: 350
                    markets:
                      - key: "1x2"
                        name: "Match Winner"
                        outcomes:
                          - label: Home
                            odds: 2.10
                    updated_at: "2026-04-12T18:00:00.000Z"
                found: 2
                requested: 3
        "400":
          description: Invalid request body or more than 20 event IDs provided
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/bets/check:
    post:
      tags: [Settlement]
      summary: Check Bets — Automatic settlement with payout calculation
      description: |
        Submit your users' bet selections and check their resolution status — the API automatically determines if each bet `won`, `lost`, `refund`, or is still `pending`. Each selection is matched by
        `market` name and `outcome` label (with smart alias handling for common variants like
        "Match Winner" / "1X2" / "Moneyline").

        Team names and final scores are included in the response.
        Process settlements promptly — poll regularly after the game ends to capture all market resolutions as they arrive gradually.

        Each selection requires: `event_id`, `market` (name), and `outcome` (label).
        For guaranteed accuracy, include **`market_id`** and **`selection_id`** (**primary** identification — from `/events` or `/settlements`) to match by ID instead of name.
        Optionally include `odds` to get `payout_multiplier` and `stake` to get calculated `payout` in the response.
        The `stake` field is **currency-agnostic** — send any numeric amount in your platform's currency.
        The response includes `matched_market_id` and `matched_selection_id` for your records.
        
        Request body supports:
        - batch mode: `{ selections: [...] }`
        - single mode: `{ selection: {...} }`
        - single shortcut: `{ event_id, market, outcome, odds?, stake? }`
      operationId: checkBets
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                selections:
                  type: array
                  maxItems: 50
                  description: Batch mode (optional when using single mode)
                  items:
                    type: object
                    required: [event_id, market, outcome]
                    properties:
                      event_id:
                        type: string
                        description: Event ID from the events endpoint
                      market:
                        type: string
                        description: Market name (e.g. "Match Winner", "Over/Under 2.5")
                      outcome:
                        type: string
                        description: Selection label (e.g. "Home", "Over 2.5")
                      odds:
                        type: number
                        minimum: 1
                        description: Optional — odds at time of bet, used to calculate payout_multiplier. If provided, must be a decimal >= 1.
                      stake:
                        type: number
                        minimum: 0.01
                        description: Optional — stake amount for payout calculation. Currency-agnostic (any numeric amount).
                      market_id:
                        oneOf:

                          - type: integer

                          - type: string
                        description: Primary — stable market identifier from /events or /settlements. Guarantees 100% accuracy by matching on ID instead of name.
                      selection_id:
                        oneOf:

                          - type: integer

                          - type: string
                        description: Primary — stable selection identifier from /events or /settlements. Guarantees 100% accuracy by matching on ID instead of label.
                selection:
                  type: object
                  description: Single selection mode
                  required: [event_id, market, outcome]
                  properties:
                    event_id:
                      type: string
                    market:
                      type: string
                    outcome:
                      type: string
                    odds:
                      type: number
                      minimum: 1
                    stake:
                      type: number
                      minimum: 0.01
                    market_id:
                      oneOf:

                        - type: integer

                        - type: string
                    selection_id:
                      oneOf:

                        - type: integer

                        - type: string
                event_id:
                  type: string
                  description: Root-level single shortcut (requires market and outcome)
                market:
                  type: string
                outcome:
                  type: string
                odds:
                  type: number
                  minimum: 1
                stake:
                  type: number
                  minimum: 0.01
                market_id:
                  oneOf:

                    - type: integer

                    - type: string
                selection_id:
                  oneOf:

                    - type: integer

                    - type: string
            example:
              selections:
                - event_id: "87654321"
                  market: "Match Winner"
                  outcome: "Home"
                  odds: 1.85
                  stake: 10
                  market_id: 340168
                  selection_id: 1824650
                - event_id: "87654321"
                  market: "Over/Under 2.5"
                  outcome: "Over 2.5"
                  odds: 1.60
                  stake: 15
                - event_id: "87654322"
                  market: "Match Winner"
                  outcome: "Away"
                  odds: 3.20
                  stake: 5
      responses:
        "200":
          description: Automated resolution and payout calculations for the submitted single bets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  results:
                    type: array
                    items:
                      type: object
                      properties:
                        event_id:
                          type: string
                        market:
                          type: string
                        outcome:
                          type: string
                        result:
                          type: string
                          enum: [won, lost, refund, pending]
                          description: "Settlement result. 'refund' = market nullified, stake returned. 'pending' = not yet settled"
                        event_status:
                          type: string
                          enum: [live, ended, prematch, postponed, cancelled]
                        score:
                          $ref: "#/components/schemas/Score"
                        matched_market:
                          type: string
                          description: Actual market name matched (may differ from input). Only present when a market was matched.
                        matched_market_id:
                          oneOf:

                            - type: integer

                            - type: string
                          nullable: true
                          description: "Unique market identifier of the matched market. Only present when a market was matched (omitted when result is 'pending')."
                        matched_outcome:
                          type: string
                          description: Actual outcome label matched. Only present when an outcome was matched.
                        matched_selection_id:
                          oneOf:

                            - type: integer

                            - type: string
                          nullable: true
                          description: "Unique selection identifier of the matched outcome. Only present when an outcome was matched (omitted when result is 'pending')."
                        available_markets:
                          type: array
                          items:
                            type: string
                          description: "List of settled market names for this event. Only present when the requested market was not found."
                        available_outcomes:
                          type: array
                          items:
                            type: string
                          description: "List of outcome labels in the matched market. Only present when the requested outcome was not found."
                        payout_multiplier:
                          type: number
                          description: "Multiply by stake for payout (0=lost, 1.0=refund, odds=won)"
                        odds:
                          type: number
                          description: "Echo of the odds value provided in the request. Only present when odds was provided."
                        stake:
                          type: number
                          description: "Echo of the stake amount provided in the request"
                        payout:
                          type: number
                          description: "Calculated payout: stake × payout_multiplier (rounded to 2dp). Only present when stake was provided."
                        reason:
                          type: string
                          description: "Explanation when result is 'pending' (e.g. 'Event not yet settled', 'Market not yet settled')"
                  summary:
                    type: object
                    properties:
                      total:
                        type: integer
                      settled:
                        type: integer
                      won:
                        type: integer
                      lost:
                        type: integer
                      refunded:
                        type: integer
                      pending:
                        type: integer
              example:
                results:
                  - event_id: "87654321"
                    market: "Match Winner"
                    outcome: "Home"
                    odds: 1.85
                    stake: 10
                    result: won
                    event_status: ended
                    score: { home: 2, away: 1 }
                    matched_market: "Match Winner"
                    matched_market_id: 340168
                    matched_outcome: "Home"
                    matched_selection_id: 1824650
                    payout_multiplier: 1.85
                    payout: 18.50
                  - event_id: "87654321"
                    market: "Over/Under 2.5"
                    outcome: "Over 2.5"
                    odds: 1.60
                    stake: 15
                    result: won
                    event_status: ended
                    score: { home: 2, away: 1 }
                    matched_market: "Over/Under 2.5"
                    matched_market_id: 340172
                    matched_outcome: "Over 2.5"
                    matched_selection_id: 1824658
                    payout_multiplier: 1.60
                    payout: 24.00
                  - event_id: "87654322"
                    market: "Match Winner"
                    outcome: "Away"
                    odds: 3.20
                    stake: 5
                    result: pending
                    event_status: live
                    score: { home: 1, away: 1 }
                    reason: "Event not yet settled"
                summary:
                  total: 3
                  settled: 2
                  won: 2
                  lost: 0
                  refunded: 0
                  pending: 1
        "400":
          description: Invalid request body (including invalid `odds` when provided)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                invalid_odds:
                  summary: Invalid odds in one selection
                  value:
                    error: bad_request
                    message: "Selection at index 0 has invalid 'odds'. Use a decimal number >= 1 when provided."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/bets/check-parlay:
    post:
      tags: [Settlement]
      summary: Resolve Parlay — Multi-leg combo resolution with combined payout
      description: |
        Submit a multi-leg parlay and get the combined resolution. The API resolves
        each leg individually by matching `market` name and `outcome` label,
        then calculates the combined payout.
        For maximum accuracy, include `market_id` and `selection_id` (from `/events` or `/settlements`).
        
        Team names and final scores are included in the response.
        Process parlays promptly — poll regularly after the game ends to capture all market resolutions as they arrive gradually.

        **Parlay rules:**
        - All legs must win for the parlay to win
        - One lost leg = entire parlay lost
        - Refunded legs are removed from combined odds (leg treated as odds 1.0)
        - Partial settlement supported (some legs still pending)
        
        Optionally include `stake` to get exact payout amounts.
        
        Request body supports:
        - single parlay: `{ legs: [...], stake? }` or `{ parlay: { legs: [...], stake? } }`
        - batch mode: `{ parlays: [{ parlay_id?, legs: [...], stake? }, ...] }`
      operationId: checkParlay
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                legs:
                  type: array
                  minItems: 2
                  maxItems: 25
                  description: Single parlay mode (optional when using `parlay` or `parlays`)
                  items:
                    type: object
                    required: [event_id, market, outcome]
                    properties:
                      event_id:
                        type: string
                      market:
                        type: string
                      outcome:
                        type: string
                      odds:
                        type: number
                        minimum: 1
                        description: Decimal odds for this leg (required, must be >= 1)
                      market_id:
                        oneOf:

                          - type: integer

                          - type: string
                        description: Optional — market identifier for exact matching
                      selection_id:
                        oneOf:

                          - type: integer

                          - type: string
                        description: Optional — selection identifier for exact matching
                stake:
                  type: number
                  description: Optional stake amount for payout calculation
                parlay:
                  type: object
                  description: Alternative single parlay wrapper
                  required: [legs]
                  properties:
                    parlay_id:
                      type: string
                    legs:
                      type: array
                      minItems: 2
                      maxItems: 25
                      items:
                        type: object
                        required: [event_id, market, outcome, odds]
                        properties:
                          event_id: { type: string }
                          market: { type: string }
                          outcome: { type: string }
                          odds: { type: number, minimum: 1 }
                          market_id:

                            oneOf:

                              - type: integer

                              - type: string
                          selection_id:

                            oneOf:

                              - type: integer

                              - type: string
                    stake:
                      type: number
                parlays:
                  type: array
                  maxItems: 20
                  description: Batch mode for multiple parlays in a single call
                  items:
                    type: object
                    required: [legs]
                    properties:
                      parlay_id:
                        type: string
                      legs:
                        type: array
                        minItems: 2
                        maxItems: 25
                        items:
                          type: object
                          required: [event_id, market, outcome, odds]
                          properties:
                            event_id: { type: string }
                            market: { type: string }
                            outcome: { type: string }
                            odds: { type: number, minimum: 1 }
                            market_id:

                              oneOf:

                                - type: integer

                                - type: string
                            selection_id:

                              oneOf:

                                - type: integer

                                - type: string
                      stake:
                        type: number
            example:
              legs:
                - event_id: "87654321"
                  market: "Match Winner"
                  outcome: "Home"
                  odds: 1.85
                - event_id: "87654322"
                  market: "Match Winner"
                  outcome: "Away"
                  odds: 2.40
                - event_id: "87654323"
                  market: "Over/Under 2.5"
                  outcome: "Over 2.5"
                  odds: 1.72
              stake: 10
      responses:
        "200":
          description: Per-leg resolution and combined payout calculations for the submitted parlay/accumulator bets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  type:
                    type: string
                    enum: [parlay]
                  total_legs:
                    type: integer
                  legs:
                    type: array
                    items:
                      type: object
                      properties:
                        leg:
                          type: integer
                        event_id:
                          type: string
                        market:
                          type: string
                        outcome:
                          type: string
                        odds:
                          type: number
                          nullable: true
                        result:
                          type: string
                          enum: [won, lost, refund, pending]
                        teams:
                          type: string
                        event_status:
                          type: string
                  payout:
                    type: object
                    properties:
                      combined_odds:
                        type: number
                      result:
                        type: string
                        enum: [won, lost, pending]
                      payout:
                        type: number
                        description: Final payout (only if result=won and stake provided)
                      potential_payout:
                        type: number
                        description: Potential payout (only if result=pending and stake provided)
                  summary:
                    type: object
                    properties:
                      won:
                        type: integer
                      lost:
                        type: integer
                      refund:
                        type: integer
                      pending:
                        type: integer
              example:
                type: parlay
                total_legs: 3
                legs:
                  - leg: 1
                    event_id: "87654321"
                    market: "Match Winner"
                    outcome: "Home"
                    odds: 1.85
                    result: won
                    teams: "Arsenal vs Chelsea"
                  - leg: 2
                    event_id: "87654322"
                    market: "Match Winner"
                    outcome: "Away"
                    odds: 2.40
                    result: won
                    teams: "Real Madrid vs Barcelona"
                  - leg: 3
                    event_id: "87654323"
                    market: "Over/Under 2.5"
                    outcome: "Over 2.5"
                    odds: 1.72
                    result: pending
                    teams: "Liverpool vs Man City"
                payout:
                  combined_odds: 7.64
                  result: pending
                  note: "1 leg(s) still pending"
                  potential_payout: 76.40
                summary:
                  won: 2
                  lost: 0
                  refund: 0
                  pending: 1
        "400":
          description: Invalid request body (including missing/invalid `odds` in any leg)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                less_than_2_legs:
                  summary: Parlay requires at least two legs
                  value:
                    error: bad_request
                    message: "A parlay requires at least 2 legs. Each leg needs { event_id, market, outcome, odds }"
                missing_odds:
                  summary: One leg is missing required odds
                  value:
                    error: bad_request
                    message: "Leg at index 0 is missing required field 'odds'"
                invalid_odds:
                  summary: One leg has invalid odds
                  value:
                    error: bad_request
                    message: "Leg at index 0 has invalid 'odds'. Use a decimal number >= 1."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/settlements:
    get:
      tags: [Settlement]
      summary: Settlement Feed — Auto-resolved market outcomes (won/lost/refund)
      description: |
        Fully automatic — markets resolve without developer intervention as soon as a game ends.

        Retrieves a real-time feed of recently settled match results and market resolutions.
        Optimized for automated betting systems to process payouts as soon as results are finalized.
        An event appears in this feed as soon as **at least one** market is resolved (`resolved_markets_count >= 1`);
        additional markets are appended gradually until `pending_markets_count` reaches `0`.
        This includes standard markets, player-prop markets, and dynamic live markets as each one is officially resolved.
        Team names, logos, and final scores are included with each settlement entry.
        
        ⚠️ Poll regularly after the game ends to capture all market resolutions as they arrive gradually.
        Poll every ~60s to capture all market resolutions before they expire.
        This endpoint can return larger responses than lightweight endpoints (e.g. `/v1/scores`) because each
        item may include multiple resolved markets and outcomes. We recommend keeping
        `limit` small (20-50).
        
        Results are returned newest first (`ended_at` descending), with `event_id` as a tie-breaker.
        Use `cursor` pagination for efficient incremental processing.
        For permanent score data, use `/v1/events/{eventId}/result`.
      operationId: getSettlements
      parameters:
        - name: limit
          in: query
          description: "Maximum number of settlements to return (default: 100, max: 200). Recommended 20-50 for recurring polling."
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 100
        - name: offset
          in: query
          description: "Number of settlements to skip for pagination (default: 0). For recurring polling, keep offset=0."
          schema:
            type: integer
            minimum: 0
            default: 0
        - name: cursor
          in: query
          description: "Cursor-based pagination token (base64url encoded `{ended_at,event_id}` from `next_cursor`). Do not combine with offset."
          schema:
            type: string
        - name: event_id
          in: query
          description: "Filter settlements by a single event id."
          schema:
            type: string
        - name: event_ids
          in: query
          description: "Filter settlements by multiple event ids (CSV). Maximum 50 ids."
          schema:
            type: string
      responses:
        "200":
          description: A feed of recently ended events and their finalized market outcomes (won, lost, refund).
          content:
            application/json:
              schema:
                type: object
                properties:
                  settlements:
                    type: array
                    items:
                      type: object
                      properties:
                        event_id:
                          type: string
                        home_team:
                          type: string
                        away_team:
                          type: string
                        home_logo:
                          type: string
                          format: uri
                          description: "PNG team logo URL. Most major teams have logos; returns a default placeholder when unavailable."
                        away_logo:
                          type: string
                          format: uri
                          description: "PNG team logo URL. Most major teams have logos; returns a default placeholder when unavailable."
                        final_score:
                          $ref: "#/components/schemas/Score"
                        sport:
                          type: string
                          nullable: true
                          description: "Sport name (e.g. 'Soccer', 'Baseball'). May be null for older settled events where Redis data has expired."
                        league:
                          type: string
                          nullable: true
                        country:
                          type: string
                          nullable: true
                        start_time:
                          type: string
                          format: date-time
                          nullable: true
                        ended_at:
                          type: string
                          format: date-time
                        status:
                          type: string
                          enum: [settled]
                          description: "Event settlement status (always 'settled' in this feed)"
                        settlement_status:
                          type: string
                          enum: [settled]
                          description: "'settled' = per-market results available."
                        resolved_markets:
                          type: array
                          items:
                            type: object
                            properties:
                              key:
                                type: string
                              name:
                                type: string
                              market_id:
                                type: integer
                                nullable: true
                                description: Unique market identifier for accurate settlement
                              outcomes:
                                type: array
                                items:
                                  type: object
                                  properties:
                                    label:
                                      type: string
                                    result:
                                      type: string
                                      enum: [won, lost, refund]
                                    selection_id:
                                      type: integer
                                      nullable: true
                                      description: Unique selection identifier for accurate settlement
                        resolved_markets_count:
                          type: integer
                          description: Number of markets with at least one resolved outcome. During gradual settlement, this number increases over time.
                        total_markets_count:
                          type: integer
                          nullable: true
                          description: Total number of markets for this event (resolved + pending). Null for legacy entries. Compare with resolved_markets_count to track settlement progress.
                        pending_markets_count:
                          type: integer
                          nullable: true
                          description: Number of markets still pending resolution. 0 when fully settled. Null for legacy entries.
                  total:
                    type: integer
                  fully_settled:
                    type: integer
                  score_only:
                    type: integer
                  limit:
                    type: integer
                  offset:
                    type: integer
                  has_more:
                    type: boolean
                  next_cursor:
                    type: string
                    nullable: true
                    description: Cursor for next page when using cursor-based incremental polling
                  applied_filters:
                    type: object
                    properties:
                      event_ids_count:
                        type: integer
                      using_cursor:
                        type: boolean
              example:
                settlements:
                  - event_id: "87654321"
                    home_team: Arsenal
                    away_team: Chelsea
                    home_logo: "https://api.fieldfunded.com/api/logo/t-38"
                    away_logo: "https://api.fieldfunded.com/api/logo/t-42"
                    final_score: { home: 2, away: 1 }
                    sport: soccer
                    league: Premier League
                    country: England
                    start_time: "2026-04-12T15:00:00Z"
                    status: settled
                    settlement_status: settled
                    ended_at: "2026-04-12T16:55:00Z"
                    resolved_markets:
                      - key: match_winner
                        name: "Match Winner"
                        market_id: 340159
                        outcomes:
                          - { label: "Home", result: "won", selection_id: 1824561 }
                          - { label: "Draw", result: "lost", selection_id: 1824562 }
                          - { label: "Away", result: "lost", selection_id: 1824563 }
                      - key: over_under_2_5
                        name: "Over/Under 2.5"
                        market_id: 340160
                        outcomes:
                          - { label: "Over 2.5", result: "won", selection_id: 1824570 }
                          - { label: "Under 2.5", result: "lost", selection_id: 1824571 }
                      - key: double_chance
                        name: "Double Chance"
                        market_id: 340161
                        outcomes:
                          - { label: "Home/Draw", result: "won", selection_id: 1824580 }
                          - { label: "Home/Away", result: "lost", selection_id: 1824581 }
                          - { label: "Draw/Away", result: "lost", selection_id: 1824582 }
                      - key: both_teams_to_score
                        name: "Both Teams To Score"
                        market_id: 340162
                        outcomes:
                          - { label: "Yes", result: "won", selection_id: 1824590 }
                          - { label: "No", result: "lost", selection_id: 1824591 }
                      - key: half_time_result
                        name: "Half-time Result"
                        market_id: 340163
                        outcomes:
                          - { label: "Home", result: "lost", selection_id: 1824600 }
                          - { label: "Draw", result: "won", selection_id: 1824601 }
                          - { label: "Away", result: "lost", selection_id: 1824602 }
                      - key: correct_score
                        name: "Correct Score"
                        market_id: 340164
                        outcomes:
                          - { label: "2-1", result: "won", selection_id: 1824610 }
                          - { label: "1-1", result: "lost", selection_id: 1824611 }
                          - { label: "2-0", result: "lost", selection_id: 1824612 }
                      - key: asian_handicap_minus_1
                        name: "Asian Handicap -1.0"
                        market_id: 340165
                        outcomes:
                          - { label: "Home (-1.0)", result: "won", selection_id: 1824620 }
                          - { label: "Away (+1.0)", result: "lost", selection_id: 1824621 }
                      - key: total_corners_over_9_5
                        name: "Total Corners Over 9.5"
                        market_id: 340166
                        outcomes:
                          - { label: "Over 9.5", result: "won", selection_id: 1824630 }
                          - { label: "Under 9.5", result: "lost", selection_id: 1824631 }
                      - key: first_goalscorer
                        name: "First Goalscorer"
                        market_id: 340167
                        outcomes:
                          - { label: "Harry Kane", result: "won", selection_id: 1824640 }
                          - { label: "Bukayo Saka", result: "lost", selection_id: 1824641 }
                      - key: total_cards_over_3_5
                        name: "Total Cards Over 3.5"
                        market_id: 340168
                        outcomes:
                          - { label: "Over 3.5", result: "won", selection_id: 1824650 }
                          - { label: "Under 3.5", result: "lost", selection_id: 1824651 }
                    resolved_markets_count: 1118
                    total_markets_count: 1118
                    pending_markets_count: 0
                total: 842
                fully_settled: 10
                score_only: 0
                limit: 50
                offset: 0
                has_more: true
                next_cursor: "BASE64URL_CURSOR_TOKEN_FROM_PREVIOUS_RESPONSE"
                applied_filters:
                  event_ids_count: 0
                  using_cursor: false
        "400":
          description: Invalid settlements filters or pagination parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                too_many_event_ids:
                  summary: event_ids exceeds max 50
                  value:
                    error: bad_request
                    message: Maximum 50 event ids are allowed for settlements filters
                cursor_offset_conflict:
                  summary: cursor and offset were sent together
                  value:
                    error: bad_request
                    message: "Use either 'cursor' or 'offset', not both."
                invalid_cursor:
                  summary: malformed cursor token
                  value:
                    error: bad_request
                    message: "Invalid 'cursor'. Expected base64url encoded { ended_at, event_id }."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"




  /v1/settlements/outrights:
    get:
      tags: [Settlement]
      summary: Outrights Settlement — League and tournament futures results
      description: |
        Returns settled outcomes for outright/futures markets (tournament-level settlements).
        This endpoint is separate from `/v1/settlements`, which is match/event settlement only.
        
        Supports deterministic cursor pagination and optional tournament filters.
      operationId: getOutrightSettlements
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 100
        - name: offset
          in: query
          schema:
            type: integer
            minimum: 0
            default: 0
        - name: cursor
          in: query
          description: "Cursor-based pagination token (base64url encoded `{settled_at,entry_id}` from `next_cursor`). Do not combine with offset."
          schema:
            type: string
        - name: tournament_id
          in: query
          description: "Filter by a single tournament id."
          schema:
            type: string
        - name: tournament_ids
          in: query
          description: "Filter by multiple tournament ids (CSV). Maximum 50 ids."
          schema:
            type: string
      responses:
        "200":
          description: A feed of recently resolved futures and outright markets (e.g. tournament winners).
          content:
            application/json:
              schema:
                type: object
                properties:
                  outright_settlements:
                    type: array
                    items:
                      type: object
                      properties:
                        entry_id: { type: string }
                        tournament_id: { type: string, nullable: true }
                        tournament: { type: string, nullable: true }
                        market_id: { type: integer, nullable: true }
                        market: { type: string, nullable: true }
                        selection_id: { type: integer, nullable: true }
                        selection: { type: string, nullable: true }
                        result:
                          type: string
                          enum: [won, lost, refund]
                        settled_at:
                          type: string
                          format: date-time
                        sport:
                          type: string
                          nullable: true
                  total: { type: integer }
                  limit: { type: integer }
                  offset: { type: integer }
                  has_more: { type: boolean }
                  next_cursor:
                    type: string
                    nullable: true
                  applied_filters:
                    type: object
                    properties:
                      tournament_ids_count: { type: integer }
                      using_cursor: { type: boolean }
              example:
                outright_settlements:
                  - entry_id: "95:341101:192002:won"
                    tournament_id: "95"
                    tournament: "Premier League"
                    market_id: 341101
                    market: "Premier League Winner"
                    selection_id: 192002
                    selection: "Arsenal"
                    result: won
                    settled_at: "2026-05-18T21:35:00Z"
                    sport: Soccer
                total: 1
                limit: 50
                offset: 0
                has_more: false
                next_cursor: null
                applied_filters:
                  tournament_ids_count: 0
                  using_cursor: false
        "400":
          description: Invalid outrights settlements filters or pagination parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
              examples:
                too_many_tournament_ids:
                  summary: tournament_ids exceeds max 50
                  value:
                    error: bad_request
                    message: Maximum 50 tournament ids are allowed
                cursor_offset_conflict:
                  summary: cursor and offset were sent together
                  value:
                    error: bad_request
                    message: "Use either 'cursor' or 'offset', not both."
                invalid_cursor:
                  summary: malformed cursor token
                  value:
                    error: bad_request
                    message: "Invalid 'cursor'. Expected base64url encoded { settled_at, entry_id }."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/outrights:
    get:
      tags: [Outrights]
      summary: Outright Tournaments — Season-level futures across all sports
      description: |
        Returns tournaments that have **outright (futures) markets** — long-term bets
        like "Who will win the Premier League?" or "Ballon d'Or winner".

        These are NOT match-by-match odds. They are season/tournament-level markets
        with many selections (e.g., all teams or players).

        **Available across all sports**: Soccer, Basketball, Tennis, Ice Hockey, CS2, and more.
        Use `/v1/outrights/sports` to discover which sports currently have outrights.

        **Live Feed** — data is fetched live from the provider with a 5-minute cache.
        Not part of the real-time polling cycle.
      operationId: getOutrights
      parameters:
        - name: sport_id
          in: query
          description: "Sport ID to filter outrights (default: 124 = Soccer). Use /v1/outrights/sports to discover IDs."
          schema:
            type: integer
            default: 124
            example: 124
        - name: country
          in: query
          description: "Filter by country name or country code (e.g. `ENG`, `USA`, `England`)"
          schema:
            type: string
            example: ENG
      responses:
        "200":
          description: A list of tournaments that currently have active outright/futures betting markets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  outrights:
                    type: array
                    items:
                      type: object
                      properties:
                        tournament_id:
                          type: integer
                        name:
                          type: string
                        sport_id:
                          type: integer
                        country:
                          type: string
                        country_code:
                          type: string
                        outright_count:
                          type: integer
                        category:
                          type: string
                          description: "Tournament category (e.g. 'International Clubs', 'England')"
                  total:
                    type: integer
                  sport_id:
                    type: integer
              example:
                outrights:
                  - tournament_id: 95
                    name: Premier League
                    sport_id: 124
                    country: England
                    country_code: ENG
                    outright_count: 1
                    category: England
                  - tournament_id: 74
                    name: UEFA Champions League
                    sport_id: 124
                    country: International Clubs
                    country_code: INT
                    outright_count: 1
                    category: International Clubs
                total: 48
                sport_id: 124
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/outrights/sports:
    get:
      tags: [Outrights]
      summary: Outright Sports — Discover which sports have futures markets
      description: |
        Discovers which sports currently have outright (futures) markets available.
        Returns sport IDs and tournament counts — use these IDs with `/v1/outrights?sport_id=X`.

        Scans 17 sports across traditional and esports providers.
        Results cached for 5 minutes.
      operationId: getOutrightSports
      responses:
        "200":
          description: A list of sports that currently feature outright/futures betting markets.
          content:
            application/json:
              schema:
                type: object
                properties:
                  sports:
                    type: array
                    items:
                      type: object
                      properties:
                        sport_id:
                          type: integer
                        name:
                          type: string
                        tournament_count:
                          type: integer
                  total:
                    type: integer
              example:
                sports:
                  - sport_id: 124
                    name: Soccer
                    tournament_count: 48
                  - sport_id: 200
                    name: Tennis
                    tournament_count: 14
                  - sport_id: 8
                    name: Basketball
                    tournament_count: 8
                  - sport_id: 11
                    name: CS2
                    tournament_count: 3
                total: 4
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"

  /v1/outrights/{tournamentId}:
    get:
      tags: [Outrights]
      summary: Outright Odds — Full futures markets for a specific tournament
      description: |
        Returns all **outright/futures markets and odds** for a specific tournament.

        Example markets: "Premier League Winner", "Top Scorer", "Most Assists",
        "Relegation", "Top 4 Finish", etc.

        Selections are sorted by odds (favourite first = lowest odds).

        **Live Feed** — fetched live from the provider with 5-minute cache.
      operationId: getOutrightDetail
      parameters:
        - name: tournamentId
          in: path
          required: true
          description: Tournament ID from the `/v1/outrights` listing
          schema:
            type: integer
            example: 95
        - name: odds_format
          in: query
          description: "Odds format for all values in response. Default: decimal"
          schema:
            type: string
            enum: [decimal, american, fractional]
            default: decimal
      responses:
        "200":
          description: The complete set of outright/futures markets and odds for the specified tournament.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tournament_id:
                    type: integer
                  events:
                    type: array
                    items:
                      type: object
                      properties:
                        event_id:
                          type: string
                        tournament_id:
                          type: string
                        tournament:
                          type: string
                        description:
                          type: string
                        sport:
                          type: string
                        country:
                          type: string
                        total_markets:
                          type: integer
                        markets:
                          type: array
                          items:
                            type: object
                            properties:
                              market_id:
                                type: integer
                              name:
                                type: string
                              status:
                                type: string
                                enum: [active, suspended]
                              selections:
                                type: array
                                items:
                                  type: object
                                  properties:
                                    selection_id:
                                      type: integer
                                    name:
                                      type: string
                                    odds:
                                      type: number
                                    status:
                                      type: string
                  total:
                    type: integer
                  odds_format:
                    type: string
                    enum: [decimal, american, fractional]
              example:
                tournament_id: 95
                events:
                  - event_id: "7454"
                    tournament_id: "95"
                    tournament: Premier League
                    description: "Premier League 25/26"
                    sport: Soccer
                    country: England
                    total_markets: 140
                    markets:
                      - market_id: 18635070
                        name: "Premier League - Winner"
                        status: active
                        selections:
                          - selection_id: 49426700
                            name: "Arsenal"
                            odds: 3.50
                            status: active
                          - selection_id: 49426701
                            name: "Manchester City"
                            odds: 4.00
                            status: active
                          - selection_id: 49426702
                            name: "Liverpool"
                            odds: 5.00
                            status: active
                      - market_id: 18635075
                        name: "Premier League - Top Goalscorer"
                        status: active
                        selections:
                          - selection_id: 49426750
                            name: "Haaland, Erling"
                            odds: 2.75
                            status: active
                          - selection_id: 49426751
                            name: "Salah, Mohamed"
                            odds: 6.00
                            status: active
                          - selection_id: 49426752
                            name: "Isak, Alexander"
                            odds: 8.00
                            status: active
                      - market_id: 18635080
                        name: "Premier League - Most Assists"
                        status: active
                        selections:
                          - selection_id: 49426793
                            name: "Fernandes, Bruno"
                            odds: 1.01
                            status: active
                          - selection_id: 49426828
                            name: "Cherki, Mathis Rayan"
                            odds: 11
                            status: active
                total: 1
                odds_format: decimal
        "404":
          description: No outrights found for this tournament
        "429":
          $ref: "#/components/responses/RateLimited"
        "503":
          $ref: "#/components/responses/ServiceUnavailable"
        "500":
          $ref: "#/components/responses/InternalServerError"


  /v1/status:
    get:
      tags: [System]
      summary: API Status — Public health check (no auth required)
      description: |
        Returns current API health, data freshness timestamps, and global event counts.
        **No authentication required** — safe to call from status pages, monitoring dashboards, or public health checks.

        Use this to verify the API is operational and data is fresh before relying on authenticated endpoints.
        
        > This endpoint does not count against your monthly quota. Fixed rate limit: 2 req/s, 120 req/h (equal for all plans).
      operationId: getStatus
      security: []
      responses:
        "200":
          description: High-level status information including live and prematch event volumes across the platform.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    enum: [operational, degraded, down]
                  version:
                    type: string
                  data_freshness_ms:
                    type: integer
                    description: How often data is refreshed (milliseconds)
                  active_sports:
                    type: integer
                  live_events:
                    type: integer
                  prematch_events:
                    type: integer
              example:
                status: operational
                version: "1.0.0"
                data_freshness_ms: 300
                active_sports: 32
                live_events: 142
                prematch_events: 700

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-API-Key
      description: Your FieldFunded API Key

  schemas:
    Sport:
      type: object
      properties:
        key:
          type: string
          description: URL-friendly sport identifier (use this value in `?sport=` filters)
          example: soccer
        name:
          type: string
          description: Display name
          example: Soccer
        sport_id:
          type: integer
          nullable: true
          description: Internal sport ID (may be null for some sports)
          example: 124
        active_events:
          type: integer
          description: Total currently active events (live + prematch)
          example: 142
        live_events:
          type: integer
          description: Number of currently live (in-play) events
          example: 10
        prematch_events:
          type: integer
          description: Number of upcoming/prematch events
          example: 132
        is_esport:
          type: boolean
          description: "`true` for esports titles (CS2, Dota 2, LoL, etc.), `false` for traditional sports. Use this to separate your UI into Sports vs Esports sections."
          example: false
        has_outrights:
          type: boolean
          description: Whether this sport currently has outright/futures markets (e.g. League Winner, Top Scorer)
          example: true

    Event:
      type: object
      properties:
        id:
          type: string
          example: "87654321"
        sport:
          type: object
          properties:
            key:
              type: string
            name:
              type: string
        league:
          type: object
          properties:
            slug:
              type: string
              description: "URL-friendly league identifier for filtering (e.g. 'premier-league')"
            name:
              type: string
            country:
              type: string
              description: "Country name (e.g. 'England', 'Spain')."
        home_team:
          type: string
        away_team:
          type: string
        home_logo:
          type: string
          format: uri
          description: "PNG team logo URL. Most major teams have logos; returns a default placeholder when unavailable."
        away_logo:
          type: string
          format: uri
          description: "PNG team logo URL. Most major teams have logos; returns a default placeholder when unavailable."
        status:
          type: string
          enum: [live, prematch, ended, delayed, postponed, cancelled, suspended, retired]
          description: |
            Event status. `delayed` = past start time but not live (auto-detected).
            `postponed`/`suspended` trigger the 48-hour settlement timer.
            `cancelled` includes walkovers and abandoned games.
        start_time:
          type: string
          format: date-time
          nullable: true
          description: "Scheduled start time in ISO 8601. May be null if the event date is unknown."
        score:
          $ref: "#/components/schemas/Score"
        clock:
          type: string
          nullable: true
          description: "Current match time (e.g. \"67:10 2nd half\"). Returns `null` for sports without a running clock (tennis, darts, CS2, etc.)."
        odds:
          type: object
          nullable: true
          description: "Main market odds (1X2 summary). May be absent or null for events without main market odds."
          properties:
            home:
              type: number
              nullable: true
            draw:
              type: number
              nullable: true
            away:
              type: number
              nullable: true
        odds_format:
          type: string
          enum: [decimal, american, fractional]
          description: "Odds format used in this response. Only present when odds are included."
        period:
          type: string
          description: "Current game period (e.g. '1st Half', '2nd Period', 'Set 3'). Empty string when not applicable."
        markets_count:
          type: integer
          description: Total number of available markets
        is_delayed:
          type: boolean
          description: "True when the event is past its scheduled start_time but not yet live. Only present for delayed events."
        delay_minutes:
          type: integer
          description: "Minutes since scheduled start_time. Only present when is_delayed is true."
        updated_at:
          type: string
          format: date-time
          description: "ISO 8601 timestamp of when this event data was last polled/updated."

    EventDetail:
      allOf:
        - $ref: "#/components/schemas/Event"
        - type: object
          properties:
            scoreboard:
              type: object
              description: Detailed period-by-period scores
              properties:
                headers:
                  type: array
                  items:
                    type: string
                home:
                  type: array
                  items:
                    type: string
                away:
                  type: array
                  items:
                    type: string
            markets:
              type: array
              items:
                $ref: "#/components/schemas/Market"
            sport_data:
              type: object
              description: Sport-specific live data
              properties:
                home_serving:
                  type: boolean
                  description: Tennis/Volleyball — home player is serving
                away_serving:
                  type: boolean
                home_game_score:
                  type: string
                  description: Tennis — current game score (e.g. "40")
                  nullable: true
                away_game_score:
                  type: string
                  nullable: true
                is_tiebreak:
                  type: boolean
                  description: Tennis — currently in a tiebreak
                home_suspend:
                  type: integer
                  description: Ice Hockey — home players in penalty box
                  nullable: true
                away_suspend:
                  type: integer
                  nullable: true
            updated_at:
              type: string
              format: date-time

    Market:
      type: object
      properties:
        market_id:
          type: integer
          description: Unique identifier for the market. Use this as the primary key for accurate settlement.
          example: 36
        key:
          type: string
          description: Normalized machine-readable key (secondary identifier).
          example: "1x2"
        name:
          type: string
          description: Human-readable display name.
          example: "Match Winner"
        outcomes:
          type: array
          items:
            $ref: "#/components/schemas/Outcome"

    Outcome:
      type: object
      properties:
        selection_id:
          type: integer
          description: Unique identifier for the selection. Use this as the primary key for accurate settlement.
          example: 206301062
        label:
          type: string
          description: Human-readable outcome label (secondary identifier).
          example: Home
        odds:
          oneOf:
            - type: number
              format: float
            - type: string
          example: 1.85
        is_locked:
          type: boolean
          description: Whether this selection is currently suspended
        team_side:
          type: string
          nullable: true
          enum: [home, away, null]
          description: |
            Which team this selection refers to. Present on 1X2, Handicap, and similar
            two-sided markets. `null` for neutral selections (Draw, Over/Under, etc.).
          example: home

    Score:
      type: object
      description: Home/away goals or points. A value of `0` is a valid score (for example, 0-0) and is returned as numeric zero.
      properties:
        home:
          type: integer
          example: 2
        away:
          type: integer
          example: 1

    Result:
      type: object
      properties:
        id:
          type: string
        status:
          type: string
          enum: [ended, not_ended, postponed, delayed, cancelled, abandoned, retired, suspended, interrupted, walkover]
        score:
          $ref: "#/components/schemas/Score"
        ended_at:
          type: string
          format: date-time
          nullable: true

    Error:
      type: object
      properties:
        error:
          type: string
          description: Error type
        message:
          type: string
          description: Human-readable error message
      example:
        error: not_found
        message: Event not found. For historical results, use /v1/settlements.

  responses:
    BadRequest:
      description: Invalid or malformed request parameters
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: bad_request
            message: "Parameter 'limit' must be a valid integer."
    ServiceUnavailable:
      description: |
        Backend data store temporarily unavailable. The `Retry-After` header indicates
        how many seconds to wait before retrying. The `component` field identifies
        which service is degraded (`realtime_data` for live odds/scores, `historical_data` for settlements).
      headers:
        Retry-After:
          description: Recommended wait time in seconds before retrying
          schema:
            type: integer
            example: 30
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
                example: service_unavailable
              message:
                type: string
                example: Data store temporarily unavailable
              component:
                type: string
                enum: [realtime_data, historical_data]
                description: Which service is temporarily degraded
                example: realtime_data
          example:
            error: service_unavailable
            message: Data store temporarily unavailable
            component: realtime_data
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: unauthorized
            message: Invalid or missing API key. Visit docs.fieldfunded.com for access.
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    RateLimited:
      description: Rate limit exceeded
      headers:
        Retry-After:
          description: Seconds until rate limit resets
          schema:
            type: integer
        X-RateLimit-Limit:
          schema:
            type: integer
        X-RateLimit-Remaining:
          schema:
            type: integer
        X-RateLimit-Reset:
          schema:
            type: integer
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: rate_limited
            message: Rate limit exceeded. Upgrade your plan for higher limits.
    InternalServerError:
      description: |
        Internal server error. Something went wrong on our end.
        Usually transient — please retry after a short delay.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: server_error
            message: Internal server error


security:
  - ApiKeyAuth: []
